metadata
dict | text
stringlengths 60
3.49M
|
---|---|
{
"source": "jejjohnson/gp_autograd",
"score": 3
}
|
#### File: gp_autograd/gp_autograd/gaussianprocess.py
```python
import autograd.numpy as np
import matplotlib.pyplot as plt
from autograd import elementwise_grad as egrad, value_and_grad
from scipy.linalg import solve_triangular
from scipy.optimize import minimize
from sklearn.base import BaseEstimator, RegressorMixin
from operator import itemgetter
from data import example_1d
# TODO: Draw Samples from Prior
# TODO: Draw Samples from Posterior
# Link: https://github.com/paraklas/GPTutorial/blob/master/code/gaussian_process.py
# TODO: Generalize for any kernel methods
# TODO: Add Comments
# TODO: Constrained Optimization Function
# TODO: Multiple Iterations for finding best weights for the derivative
# Link: https://github.com/scikit-learn/scikit-learn/blob/f0ab589f/sklearn/gaussian_process/gpr.py#L451
class GaussianProcess(BaseEstimator, RegressorMixin):
def __init__(self, jitter=1e-8, random_state=None):
self.jitter = jitter
self.random_state = random_state
def init_theta(self):
"""Initializes the hyperparameters."""
signal_variance = 1.0
length_scale = np.ones(self.X_train_.shape[1])
noise_likelihood = 0.01
theta = np.array([signal_variance, noise_likelihood, length_scale])
return np.log(theta)
def fit(self, X, y):
self.X_train_ = X
self.y_train_ = y
# initial hyper-parameters
theta0 = self.init_theta()
# minimize the objective function
best_params = minimize(value_and_grad(self.log_marginal_likelihood), theta0, jac=True,
method='L-BFGS-B')
# Gather hyper parameters
signal_variance, noise_likelihood, length_scale = \
self._get_kernel_params(best_params.x)
self.signal_variance = np.exp(signal_variance)
self.noise_likelihood = np.exp(noise_likelihood)
self.length_scale = np.exp(length_scale)
# Calculate the weights
K = self.rbf_covariance(X, length_scale=self.length_scale,
signal_variance=self.signal_variance)
K += self.noise_likelihood * np.eye(K.shape[0])
L = np.linalg.cholesky(K + self.jitter * np.eye(K.shape[0]))
weights = np.linalg.solve(L.T, np.linalg.solve(L, y))
self.weights = weights
self.L = L
self.K = K
L_inv = solve_triangular(self.L.T, np.eye(self.L.shape[0]))
self.K_inv = np.dot(L_inv, L_inv.T)
return self
def log_marginal_likelihood(self, theta):
x_train = self.X_train_
y_train = self.y_train_
if np.ndim == 1:
y_train = y_train[:, np.newaxis]
# Gather hyper parameters
signal_variance, noise_likelihood, length_scale = \
self._get_kernel_params(theta)
signal_variance = np.exp(signal_variance)
noise_likelihood = np.exp(noise_likelihood)
length_scale = np.exp(length_scale)
n_samples = x_train.shape[0]
# train kernel
K = self.rbf_covariance(x_train, length_scale=length_scale,
signal_variance=signal_variance)
K += noise_likelihood * np.eye(n_samples)
L = np.linalg.cholesky(K + self.jitter * np.eye(n_samples))
weights = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
log_likelihood_dims = -0.5 * np.einsum("ik,ik->k", y_train, weights)
log_likelihood_dims -= np.log(np.diag(L)).sum()
log_likelihood_dims -= (K.shape[0] / 2) * np.log(2 * np.pi)
log_likelihood = log_likelihood_dims.sum(-1)
return -log_likelihood
def predict(self, X, return_std=False):
# Train test kernel
K_trans = self.rbf_covariance(X, self.X_train_,
length_scale=self.length_scale,
signal_variance=self.signal_variance)
pred_mean = np.dot(K_trans, self.weights)
if not return_std:
return pred_mean
else:
return pred_mean, self.variance(X, K_trans=K_trans)
def variance(self, X, K_trans=None):
if K_trans is None:
K_trans = self.rbf_covariance(X, y=self.X_train_,
length_scale=self.length_scale,
signal_variance=self.signal_variance)
# compute the variance
y_var = np.diag(self.rbf_covariance(X, length_scale=self.length_scale,
signal_variance=self.signal_variance)) \
+ self.noise_likelihood
y_var -= np.einsum("ij,ij->i", np.dot(K_trans, self.K_inv), K_trans)
return y_var
def _get_kernel_params(self, theta):
signal_variance = theta[0]
noise_likelihood = theta[1] + self.jitter
length_scale = theta[2:]
return signal_variance, noise_likelihood, length_scale
def rbf_covariance(self, X, y=None, signal_variance=1.0, length_scale=1.0):
if y is None:
y = X
D = np.expand_dims(X / length_scale, 1) - np.expand_dims(y / length_scale, 0)
return signal_variance * np.exp(-0.5 * np.sum(D ** 2, axis=2))
def mu_grad(self, X, nder=1, return_std=False):
# Construct the autogradient function for the
# predictive mean
mu = lambda x: self.predict(x)
grad_mu = egrad(mu)
mu_sol = X
while nder:
mu_sol = grad_mu(mu_sol)
nder -= 1
if return_std:
return mu_sol, self.sigma_grad(X, nder=nder)
else:
return mu_sol
# if not return_std:
# return grad_mu(X)
# else:
# return grad_mu(X), self.sigma_grad(X, nder=1)
# else:
# grad_mu = egrad(egrad(mu))
# if not return_std:
# return grad_mu(X)
# else:
# return grad_mu(X), self.sigma_grad(X, nder=2)
def sigma_grad(self, X, nder=1):
# Construct the autogradient function for the
# predictive variance
sigma = lambda x: self.variance(x)
if nder == 1:
grad_var = egrad(sigma)
return grad_var(X)
else:
grad_var = egrad(egrad(sigma))
return grad_var(X)
class GaussianProcessError(BaseEstimator, RegressorMixin):
def __init__(self, jitter=1e-8, x_covariance=None, random_state=None, n_iters=3):
self.jitter = jitter
self.x_covariance = x_covariance
self.random_state = random_state
self.n_ters= n_iters
def init_theta(self):
"""Initializes the hyperparameters."""
signal_variance = np.log(1.0)
length_scale = np.log(np.ones(self.X_train_.shape[1]))
noise_likelihood = np.log(0.01)
theta = np.hstack([signal_variance, noise_likelihood, length_scale])
return theta
def fit(self, X, y):
self.X_train_ = X
self.y_train_ = y
if self.x_covariance is None:
self.x_covariance = 0.0 * self.X_train_.shape[1]
if np.ndim(self.x_covariance) == 1:
self.x_covariance = np.array([self.x_covariance])
# initial hyper-parameters
theta0 = self.init_theta()
# Calculate the initial weights
self.derivative = np.ones(self.X_train_.shape)
print(self.derivative[:10, :10])
# minimize the objective function
optima = [minimize(value_and_grad(self.log_marginal_likelihood), theta0, jac=True,
method='L-BFGS-B')]
fig, ax = plt.subplots()
ax.scatter(self.X_train_, self.derivative)
if self.n_ters is not None:
for iteration in range(self.n_ters):
print(theta0)
# Find the minimum
iparams = minimize(value_and_grad(self.log_marginal_likelihood), theta0, jac=True,
method='L-BFGS-B')
print(iparams)
# extract best values
signal_variance, noise_likelihood, length_scale = \
self._get_kernel_params(iparams.x)
# Recalculate the derivative
K = self.rbf_covariance(self.X_train_, length_scale=np.exp(length_scale),
signal_variance=np.exp(signal_variance))
K += np.exp(noise_likelihood) * np.eye(K.shape[0])
L = np.linalg.cholesky(K + self.jitter * np.eye(K.shape[0]))
iweights = np.linalg.solve(L.T, np.linalg.solve(L, self.y_train_))
self.derivative = self.weights_grad(self.X_train_, iweights,
np.exp(length_scale), np.exp(signal_variance))
print(self.derivative[:10, :10])
ax.scatter(self.X_train_, self.derivative)
# make a new theta
theta0 = np.hstack([signal_variance, noise_likelihood, length_scale])
plt.show()
print()
print(optima)
lml_values = list(map(itemgetter(1), optima))
best_params = optima[np.argmin(lml_values)][0]
print(best_params)
# Gather hyper parameters
signal_variance, noise_likelihood, length_scale = \
self._get_kernel_params(best_params)
self.signal_variance = np.exp(signal_variance)
self.noise_likelihood = np.exp(noise_likelihood)
self.length_scale = np.exp(length_scale)
# Calculate the weights
K = self.rbf_covariance(X, length_scale=self.length_scale,
signal_variance=self.signal_variance)
K += self.noise_likelihood * np.eye(K.shape[0])
L = np.linalg.cholesky(K + self.jitter * np.eye(K.shape[0]))
weights = np.linalg.solve(L.T, np.linalg.solve(L, y))
self.weights = weights
self.L = L
self.K = K
L_inv = solve_triangular(self.L.T, np.eye(self.L.shape[0]))
self.K_inv = np.dot(L_inv, L_inv.T)
return self
def log_marginal_likelihood(self, theta):
x_train = self.X_train_
y_train = self.y_train_
if np.ndim == 1:
y_train = y_train[:, np.newaxis]
# Gather hyper parameters
signal_variance, noise_likelihood, length_scale = \
self._get_kernel_params(theta)
signal_variance = np.exp(signal_variance)
noise_likelihood = np.exp(noise_likelihood)
length_scale = np.exp(length_scale)
# Calculate the derivative
# derivative_term = np.diag(np.einsum("ij,ij->i", np.dot(self.derivative, self.x_covariance), self.derivative))
derivative_term = np.dot(self.derivative, np.dot(self.x_covariance, self.derivative.T))
n_samples = x_train.shape[0]
# Calculate derivative of the function
# train kernel
K = self.rbf_covariance(x_train, length_scale=length_scale,
signal_variance=signal_variance)
K += noise_likelihood * np.eye(n_samples)
K += derivative_term
L = np.linalg.cholesky(K + self.jitter * np.eye(n_samples))
weights = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
log_likelihood_dims = -0.5 * np.einsum("ik,ik->k", y_train, weights)
log_likelihood_dims -= np.log(np.diag(L)).sum()
log_likelihood_dims -= (K.shape[0] / 2) * np.log(2 * np.pi)
log_likelihood = log_likelihood_dims.sum(-1)
return -log_likelihood
def predict(self, X, return_std=False):
# Train test kernel
K_trans = self.rbf_covariance(X, self.X_train_,
length_scale=self.length_scale,
signal_variance=self.signal_variance)
pred_mean = np.dot(K_trans, self.weights)
if not return_std:
return pred_mean
else:
return pred_mean, self.variance(X, K_trans=K_trans)
def variance(self, X, K_trans=None):
if K_trans is None:
K_trans = self.rbf_covariance(X, y=self.X_train_,
length_scale=self.length_scale,
signal_variance=self.signal_variance)
# compute the variance
y_var = np.diag(self.rbf_covariance(X, length_scale=self.length_scale,
signal_variance=self.signal_variance)) \
+ self.noise_likelihood
y_var -= np.einsum("ij,ij->i", np.dot(K_trans, self.K_inv), K_trans)
return y_var
def _get_kernel_params(self, theta):
signal_variance = theta[0]
noise_likelihood = theta[1] + self.jitter
length_scale = theta[2:self.X_train_.shape[1] + 2]
# print(length_scale.shape, init_weights.shape)
return signal_variance, noise_likelihood, length_scale
def rbf_covariance(self, X, y=None, signal_variance=1.0, length_scale=1.0):
if y is None:
y = X
D = np.expand_dims(X / length_scale, 1) - np.expand_dims(y / length_scale, 0)
return signal_variance * np.exp(-0.5 * np.sum(D ** 2, axis=2))
def predict_weights(self, X, weights, length_scale, signal_variance):
# Train test kernel
K_trans = self.rbf_covariance(X,
length_scale=length_scale,
signal_variance=signal_variance)
pred = np.dot(K_trans, weights)
return pred
def weights_grad(self, X, weights, length_scale, signal_variance):
mu = lambda x: self.predict_weights(x, weights, length_scale, signal_variance)
grad_mu = egrad(mu)
return grad_mu(X)
def mu_grad(self, X, nder=1, return_std=False):
# Construct the autogradient function for the
# predictive mean
mu = lambda x: self.predict(x)
if nder == 1:
grad_mu = egrad(mu)
if not return_std:
return grad_mu(X)
else:
return grad_mu(X), self.sigma_grad(X, nder=1)
else:
grad_mu = egrad(egrad(mu))
if not return_std:
return grad_mu(X)
else:
return grad_mu(X), self.sigma_grad(X, nder=2)
def sigma_grad(self, X, nder=1):
# Construct the autogradient function for the
# predictive variance
sigma = lambda x: self.variance(x)
if nder == 1:
grad_var = egrad(sigma)
return grad_var(X)
else:
grad_var = egrad(egrad(sigma))
return grad_var(X)
def np_gradient(y_pred, xt):
return np.gradient(y_pred.squeeze(), xt.squeeze(), edge_order=2)[:, np.newaxis]
def sample_data():
"""Gets some sample data."""
d_dimensions = 1
n_samples = 20
noise_std = 0.1
seed = 123
rng = np.random.RandomState(seed)
n_train = 20
n_test = 1000
n_train = 20
n_test = 1000
xtrain = np.linspace(-4, 5, n_train).reshape(n_train, 1)
xtest = np.linspace(-4, 5, n_test).reshape(n_test, 1)
f = lambda x: np.sin(x) * np.exp(0.2 * x)
ytrain = f(xtrain) + noise_std * rng.randn(n_train, 1)
ytest = f(xtest)
return xtrain, xtest, ytrain, ytest
def main():
test_error()
pass
def test_error():
X, y, error_params = example_1d()
# Initialize GP Model
gp_autograd = GaussianProcessError()
# Fit GP Model
gp_autograd.fit(X['train'], y['train'])
# Make Predictions
y_pred, y_var = gp_autograd.predict(X['test'], return_std=True)
pass
def test_original():
# Get sample data
xtrain, xtest, ytrain, ytest = sample_data()
# Initialize GP Model
gp_autograd = GaussianProcess()
# Fit GP Model
gp_autograd.fit(xtrain, ytrain)
# Make Predictions
y_pred, y_var = gp_autograd.predict(xtest, return_std=True)
##########################
# First Derivative
##########################
# Autogradient
mu_der = gp_autograd.mu_grad(xtest)
# # Numerical Gradient
num_grad = np_gradient(y_pred, xtest)
assert (mu_der.shape == num_grad.shape)
# Plot Data
fig, ax = plt.subplots(figsize=(10, 7))
ax.scatter(xtrain, ytrain, color='r', label='Training Noise')
ax.plot(xtest, y_pred, color='k', label='Predictions')
ax.plot(xtest, mu_der, color='b', linestyle=":", label='Autograd 1st Derivative')
ax.plot(xtest, num_grad, color='y', linestyle="--", label='Numerical Derivative')
ax.legend()
plt.show()
############################
# 2nd Derivative
############################
mu_der2 = gp_autograd.mu_grad(xtest, nder=2)
num_grad2 = np_gradient(num_grad, xtest)
# Plot
fig, ax = plt.subplots(figsize=(10, 7))
# ax.scatter(xtrain, ytrain)
ax.scatter(xtrain, ytrain, color='r', label='Training Points')
ax.plot(xtest, y_pred, color='k', label='Predictions')
ax.plot(xtest, mu_der2, color='b', linestyle=":", label='Autograd 2nd Derivative')
ax.plot(xtest, num_grad2, color='y', linestyle="--", label='Numerical 2nd Derivative')
ax.legend()
plt.show()
assert (mu_der2.all() == num_grad2.all())
return None
if __name__ == '__main__':
main()
```
|
{
"source": "jejjohnson/GPJax-1",
"score": 4
}
|
#### File: docs/nbs/spatial_preprocessing.py
```python
import geopandas as gpd
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
def slice_hour(df: pd.DataFrame, timestamp):
"""
Extract an hour slice of a spatiotemporal dataset.
"""
df = df[["latitude", "longitude", "date_utc", "no2_ugm3"]]
df["timestamp"] = pd.to_datetime(df.date_utc)
return (
df[df["timestamp"] == timestamp]
.dropna()
.drop(["timestamp", "date_utc"], axis=1)
.reset_index(drop=True)
)
if __name__ == "__main__":
# Download air quality data directly from a given url
aq_data = pd.read_csv(
"https://data.london.gov.uk/download/breathe-london-aqmesh-pods/267507cc-9740-4ea7-be05-4d6ae16a5e4a/stationary_data.csv"
)
# Slice out 9am on 15th February 2019
hour_of_interest = dt.datetime(year=2019, month=2, day=15, hour=9)
spatial_data = slice_hour(aq_data, of_interest)
spatial_data.to_file("datasets/aq/aq.shp")
```
#### File: gpjax/objectives/spectral.py
```python
from typing import Callable
import jax.numpy as jnp
from jax.scipy.linalg import solve_triangular
from multipledispatch import dispatch
from ..gps import SpectralPosterior
from ..utils import I, concat_dictionaries
@dispatch(SpectralPosterior)
def marginal_ll(
gp: SpectralPosterior,
transform: Callable,
negative: bool = False,
) -> Callable:
def mll(params: dict, x: jnp.DeviceArray, y: jnp.DeviceArray, static_params: dict = None):
params = transform(params)
if static_params:
params = concat_dictionaries(params, static_params)
m = gp.prior.kernel.num_basis
phi = gp.prior.kernel._build_phi(x, params)
A = (params["variance"] / m) * jnp.matmul(jnp.transpose(phi), phi) + params[
"obs_noise"
] * I(2 * m)
RT = jnp.linalg.cholesky(A)
R = jnp.transpose(RT)
RtiPhit = solve_triangular(RT, jnp.transpose(phi))
# Rtiphity=RtiPhit*y_tr;
Rtiphity = jnp.matmul(RtiPhit, y)
out = (
0.5
/ params["obs_noise"]
* (jnp.sum(jnp.square(y)) - params["variance"] / m * jnp.sum(jnp.square(Rtiphity)))
)
n = x.shape[0]
out += (
jnp.sum(jnp.log(jnp.diag(R)))
+ (n / 2.0 - m) * jnp.log(params["variance"])
+ n / 2 * jnp.log(2 * jnp.pi)
)
constant = jnp.array(-1.0) if negative else jnp.array(1.0)
return constant * out.reshape()
return mll
```
#### File: GPJax-1/gpjax/sampling.py
```python
import jax.numpy as jnp
from jax.scipy.linalg import solve_triangular
from multipledispatch import dispatch
from tensorflow_probability.substrates.jax import distributions as tfd
from .gps import (ConjugatePosterior, NonConjugatePosterior, Prior,
SpectralPosterior)
from .kernels import cross_covariance, gram
from .likelihoods import predictive_moments
from .predict import mean, variance
from .types import Array
from .utils import I, concat_dictionaries
@dispatch(Prior, dict, jnp.DeviceArray)
def random_variable(
gp: Prior, params: dict, sample_points: Array, jitter_amount: float = 1e-6
) -> tfd.Distribution:
mu = gp.mean_function(sample_points)
gram_matrix = gram(gp.kernel, sample_points, params)
jitter_matrix = I(sample_points.shape[0]) * jitter_amount
covariance = gram_matrix + jitter_matrix
return tfd.MultivariateNormalFullCovariance(mu.squeeze(), covariance)
@dispatch(ConjugatePosterior, dict, jnp.DeviceArray, jnp.DeviceArray, jnp.DeviceArray)
def random_variable(
gp: ConjugatePosterior,
params: dict,
sample_points: Array,
train_inputs: Array,
train_outputs: Array,
jitter_amount: float = 1e-6,
) -> tfd.Distribution:
n = sample_points.shape[0]
# TODO: Return kernel matrices here to avoid replicated computation.
mu = mean(gp, params, sample_points, train_inputs, train_outputs)
cov = variance(gp, params, sample_points, train_inputs, train_outputs)
return tfd.MultivariateNormalFullCovariance(mu.squeeze(), cov + I(n) * jitter_amount)
@dispatch(NonConjugatePosterior, dict, jnp.DeviceArray, jnp.DeviceArray, jnp.DeviceArray)
def random_variable(
gp: NonConjugatePosterior,
params: dict,
sample_points: Array,
train_inputs: Array,
train_outputs: Array,
) -> tfd.Distribution:
ell, alpha, nu = params["lengthscale"], params["variance"], params["latent"]
n_train = train_inputs.shape[0]
Kff = gram(gp.prior.kernel, train_inputs, params)
Kfx = cross_covariance(gp.prior.kernel, train_inputs, sample_points, params)
Kxx = gram(gp.prior.kernel, sample_points, params)
L = jnp.linalg.cholesky(Kff + jnp.eye(train_inputs.shape[0]) * 1e-6)
A = solve_triangular(L, Kfx.T, lower=True)
latent_var = Kxx - jnp.sum(jnp.square(A), -2)
latent_mean = jnp.matmul(A.T, nu)
lvar = jnp.diag(latent_var)
moment_fn = predictive_moments(gp.likelihood)
return moment_fn(latent_mean.ravel(), lvar)
@dispatch(SpectralPosterior, dict, jnp.DeviceArray, jnp.DeviceArray, jnp.DeviceArray)
def random_variable(
gp: SpectralPosterior,
params: dict,
train_inputs: Array,
train_outputs: Array,
test_inputs: Array,
static_params: dict = None,
) -> tfd.Distribution:
params = concat_dictionaries(params, static_params)
m = gp.prior.kernel.num_basis
w = params["basis_fns"] / params["lengthscale"]
phi = gp.prior.kernel._build_phi(train_inputs, params)
A = (params["variance"] / m) * jnp.matmul(jnp.transpose(phi), phi) + params["obs_noise"] * I(
2 * m
)
RT = jnp.linalg.cholesky(A)
R = jnp.transpose(RT)
RtiPhit = solve_triangular(RT, jnp.transpose(phi))
# Rtiphity=RtiPhit*y_tr;
Rtiphity = jnp.matmul(RtiPhit, train_outputs)
alpha = params["variance"] / m * solve_triangular(R, Rtiphity, lower=False)
phistar = jnp.matmul(test_inputs, jnp.transpose(w))
# phistar = [cos(phistar) sin(phistar)]; % test design matrix
phistar = jnp.hstack([jnp.cos(phistar), jnp.sin(phistar)])
# out1(beg_chunk:end_chunk) = phistar*alfa; % Predictive mean
mean = jnp.matmul(phistar, alpha)
print(mean.shape)
RtiPhistart = solve_triangular(RT, jnp.transpose(phistar))
PhiRistar = jnp.transpose(RtiPhistart)
cov = (
params["obs_noise"]
* params["variance"]
/ m
* jnp.matmul(PhiRistar, jnp.transpose(PhiRistar))
+ I(test_inputs.shape[0]) * 1e-6
)
return tfd.MultivariateNormalFullCovariance(mean.squeeze(), cov)
@dispatch(jnp.DeviceArray, Prior, dict, jnp.DeviceArray)
def sample(key, gp, params, sample_points, n_samples=1) -> Array:
rv = random_variable(gp, params, sample_points)
return rv.sample(sample_shape=(n_samples,), seed=key)
@dispatch(jnp.DeviceArray, tfd.Distribution)
def sample(key: jnp.DeviceArray, random_variable: tfd.Distribution, n_samples: int = 1) -> Array:
return random_variable.sample(sample_shape=(n_samples,), seed=key)
```
#### File: jejjohnson/GPJax-1/setup.py
```python
from setuptools import setup, find_packages
def parse_requirements_file(filename):
with open(filename, encoding="utf-8") as fid:
requires = [l.strip() for l in fid.readlines() if l]
return requires
# Optional Packages
EXTRAS = {
"dev": [
"black",
"isort",
"pylint",
"flake8",
],
"tests": [
"pytest",
],
"docs": [
"furo==2020.12.30b24",
"nbsphinx==0.8.1",
"nb-black==1.0.7",
"matplotlib==3.3.3",
"sphinx-copybutton==0.3.3",
],
}
setup(
name="GPJax",
version="0.3.3",
author="<NAME>",
author_email="<EMAIL>",
packages=find_packages(".", exclude=["tests"]),
license="LICENSE",
description="Didactic Gaussian processes in Jax and ObJax.",
long_description="GPJax aims to provide a low-level interface to Gaussian process models. Code is written entirely in Jax and Objax to enhance readability, and structured so as to allow researchers to easily extend the code to suit their own needs. When defining GP prior in GPJax, the user need only specify a mean and kernel function. A GP posterior can then be realised by computing the product of our prior with a likelihood function. The idea behind this is that the code should be as close as possible to the maths that we would write on paper when working with GP models.",
install_requires=parse_requirements_file("requirements.txt"),
extras_require=EXTRAS,
keywords=["gaussian-processes jax machine-learning bayesian"],
)
```
#### File: tests/objectives/test_mlls.py
```python
from typing import Callable
import jax.numpy as jnp
import jax.random as jr
import pytest
from tensorflow_probability.substrates.jax import distributions as tfd
from gpjax import Prior
from gpjax.config import get_defaults
from gpjax.kernels import RBF
from gpjax.likelihoods import Bernoulli, Gaussian
from gpjax.objectives import marginal_ll
from gpjax.parameters import (build_all_transforms, build_unconstrain,
initialise)
def test_conjugate():
posterior = Prior(kernel=RBF()) * Gaussian()
x = jnp.linspace(-1.0, 1.0, 20).reshape(-1, 1)
y = jnp.sin(x)
params = initialise(posterior)
config = get_defaults()
unconstrainer, constrainer = build_all_transforms(params.keys(), config)
params = unconstrainer(params)
mll = marginal_ll(posterior, transform=constrainer)
assert isinstance(mll, Callable)
neg_mll = marginal_ll(posterior, transform=constrainer, negative=True)
assert neg_mll(params, x, y) == jnp.array(-1.0) * mll(params, x, y)
def test_non_conjugate():
posterior = Prior(kernel=RBF()) * Bernoulli()
n = 20
x = jnp.linspace(-1.0, 1.0, n).reshape(-1, 1)
y = jnp.sin(x)
params = initialise(posterior, 20)
config = get_defaults()
unconstrainer, constrainer = build_all_transforms(params.keys(), config)
params = unconstrainer(params)
mll = marginal_ll(posterior, transform=constrainer)
assert isinstance(mll, Callable)
neg_mll = marginal_ll(posterior, transform=constrainer, negative=True)
assert neg_mll(params, x, y) == jnp.array(-1.0) * mll(params, x, y)
def test_prior_mll():
"""
Test that the MLL evaluation works with priors attached to the parameter values.
"""
key = jr.PRNGKey(123)
x = jnp.sort(jr.uniform(key, minval=-5.0, maxval=5.0, shape=(100, 1)), axis=0)
f = lambda x: jnp.sin(jnp.pi * x) / (jnp.pi * x)
y = f(x) + jr.normal(key, shape=x.shape) * 0.1
posterior = Prior(kernel=RBF()) * Gaussian()
params = initialise(posterior)
config = get_defaults()
constrainer, unconstrainer = build_all_transforms(params.keys(), config)
params = unconstrainer(params)
print(params)
mll = marginal_ll(posterior, transform=constrainer)
priors = {
"lengthscale": tfd.Gamma(1.0, 1.0),
"variance": tfd.Gamma(2.0, 2.0),
"obs_noise": tfd.Gamma(2.0, 2.0),
}
mll_eval = mll(params, x, y)
mll_eval_priors = mll(params, x, y, priors)
assert pytest.approx(mll_eval) == jnp.array(-103.28180663)
assert pytest.approx(mll_eval_priors) == jnp.array(-105.509218857)
```
#### File: tests/parameters/test_priors.py
```python
import jax.numpy as jnp
import pytest
from tensorflow_probability.substrates.jax import distributions as tfd
from gpjax.gps import Prior
from gpjax.kernels import RBF
from gpjax.likelihoods import Bernoulli
from gpjax.parameters import log_density
from gpjax.parameters.priors import evaluate_prior, prior_checks
@pytest.mark.parametrize("x", [-1.0, 0.0, 1.0])
def test_lpd(x):
val = jnp.array(x)
dist = tfd.Normal(loc=0.0, scale=1.0)
lpd = log_density(val, dist)
assert lpd is not None
def test_prior_evaluation():
"""
Test the regular setup that every parameter has a corresponding prior distribution attached to its unconstrained
value.
"""
params = {
"lengthscale": jnp.array([1.0]),
"variance": jnp.array([1.0]),
"obs_noise": jnp.array([1.0]),
}
priors = {
"lengthscale": tfd.Gamma(1.0, 1.0),
"variance": tfd.Gamma(2.0, 2.0),
"obs_noise": tfd.Gamma(3.0, 3.0),
}
lpd = evaluate_prior(params, priors)
assert pytest.approx(lpd) == -2.0110168
def test_none_prior():
"""
Test that multiple dispatch is working in the case of no priors.
"""
params = {
"lengthscale": jnp.array([1.0]),
"variance": jnp.array([1.0]),
"obs_noise": jnp.array([1.0]),
}
lpd = evaluate_prior(params, None)
assert lpd == 0.0
def test_incomplete_priors():
"""
Test the case where a user specifies priors for some, but not all, parameters.
"""
params = {
"lengthscale": jnp.array([1.0]),
"variance": jnp.array([1.0]),
"obs_noise": jnp.array([1.0]),
}
priors = {
"lengthscale": tfd.Gamma(1.0, 1.0),
"variance": tfd.Gamma(2.0, 2.0),
}
lpd = evaluate_prior(params, priors)
assert pytest.approx(lpd) == -1.6137061
def test_checks():
incomplete_priors = {"lengthscale": jnp.array([1.0])}
posterior = Prior(kernel=RBF()) * Bernoulli()
priors = prior_checks(posterior, incomplete_priors)
assert "latent" in priors.keys()
assert "variance" not in priors.keys()
def test_check_needless():
complete_prior = {
"lengthscale": tfd.Gamma(1.0, 1.0),
"variance": tfd.Gamma(2.0, 2.0),
"obs_noise": tfd.Gamma(3.0, 3.0),
"latent": tfd.Normal(loc=0.0, scale=1.0),
}
posterior = Prior(kernel=RBF()) * Bernoulli()
priors = prior_checks(posterior, complete_prior)
assert priors == complete_prior
```
#### File: GPJax-1/tests/test_mean_functions.py
```python
import jax.numpy as jnp
import pytest
from gpjax.mean_functions import Zero, initialise
@pytest.mark.parametrize("dim", [1, 2, 5])
def test_shape(dim):
x = jnp.linspace(-1.0, 1.0, num=10).reshape(-1, 1)
if dim > 1:
x = jnp.hstack([x] * dim)
meanf = Zero()
mu = meanf(x)
assert mu.shape[0] == x.shape[0]
assert mu.shape[1] == 1
def test_initialisers():
params = initialise(Zero())
assert not params
```
#### File: GPJax-1/tests/test_types.py
```python
from gpjax.types import NoneType
def test_nonetype():
assert isinstance(None, NoneType)
```
|
{
"source": "jejjohnson/gp_model_zoo",
"score": 2
}
|
#### File: numpyro/src/base.py
```python
from flax import struct
import jax.numpy as jnp
from chex import dataclass
@dataclass
class Predictive:
def predict_mean(self, xtest):
raise NotImplementedError()
def predict_cov(self, xtest, noiseless=False):
raise NotImplementedError()
def _predict(self, xtest, full_covariance: bool = False, noiseless: bool = True):
raise NotImplementedError()
def predict_f(self, xtest, full_covariance: bool = False):
return self._predict(xtest, full_covariance=full_covariance, noiseless=True)
def predict_y(self, xtest, full_covariance: bool = False):
return self._predict(xtest, full_covariance=full_covariance, noiseless=False)
def predict_var(self, xtest, noiseless=False):
raise jnp.sqrt(self.predict_cov(xtest=xtest, noiseless=noiseless))
```
#### File: numpyro/src/data.py
```python
import jax
import jax.numpy as jnp
def regression_near_square(
n_train: int = 50,
n_test: int = 1_000,
x_noise: float = 0.3,
y_noise: float = 0.2,
seed: int = 123,
buffer: float = 0.1,
):
key = jax.random.PRNGKey(seed)
# function
f = lambda x: jnp.sin(1.0 * jnp.pi / 1.6 * jnp.cos(5 + 0.5 * x))
# input training data (clean)
xtrain = jnp.linspace(-10, 10, n_train).reshape(-1, 1)
ytrain = f(xtrain) + jax.random.normal(key, shape=xtrain.shape) * y_noise
xtrain_noise = xtrain + x_noise * jax.random.normal(key, shape=xtrain.shape)
# output testing data (noisy)
xtest = jnp.linspace(-10.0 - buffer, 10.0 + buffer, n_test)[:, None]
ytest = f(xtest)
xtest_noise = xtest + x_noise * jax.random.normal(key, shape=xtest.shape)
idx_sorted = jnp.argsort(xtest_noise, axis=0)
xtest_noise = xtest_noise[idx_sorted[:, 0]]
ytest_noise = ytest[idx_sorted[:, 0]]
return xtrain, xtrain_noise, ytrain, xtest, xtest_noise, ytest, ytest_noise
def regression_simple(
n_train: int = 50,
n_test: int = 1_000,
noise: float = 0.2,
seed: int = 123,
buffer: float = 0.1,
):
key = jax.random.PRNGKey(seed)
x = (
jax.random.uniform(key=key, minval=-3.0, maxval=3.0, shape=(n_train,))
.sort()
.reshape(-1, 1)
)
f = lambda x: jnp.sin(4 * x) + jnp.cos(2 * x)
signal = f(x)
y = signal + jax.random.normal(key, shape=signal.shape) * noise
xtest = jnp.linspace(-3.0 - buffer, 3.0 + buffer, n_test).reshape(-1, 1)
ytest = f(xtest)
return x, y, xtest, ytest
def regression_complex(
n_train: int = 1_000,
n_test: int = 1_000,
noise: float = 0.2,
seed: int = 123,
buffer: float = 0.1,
):
key = jax.random.PRNGKey(seed)
x = jnp.linspace(-1.0, 1.0, n_train).reshape(-1, 1) # * 2.0 - 1.0
f = (
lambda x: jnp.sin(x * 3 * 3.14)
+ 0.3 * jnp.cos(x * 9 * 3.14)
+ 0.5 * jnp.sin(x * 7 * 3.14)
)
signal = f(x)
y = signal + noise * jax.random.normal(key, shape=signal.shape)
xtest = jnp.linspace(-1.0 - buffer, 1.0 + buffer, n_test).reshape(-1, 1)
ytest = f(xtest)
return x, y, xtest, ytest
```
#### File: numpyro/src/plots.py
```python
import matplotlib.pyplot as plt
from uncertainty_toolbox import viz as utviz
import wandb
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_context(context="talk", font_scale=0.7)
def plot_calibration(y_mu, y_std, y_real):
fig, ax = plt.subplots()
return fig, ax
def plot_all_uncertainty(y_pred, y_var, y_true, model, data, log: bool = False):
y_std = np.sqrt(y_var)
utviz.plot_parity(y_pred=y_pred.ravel(), y_true=y_true.ravel())
plt.tight_layout()
plt.gcf()
if log:
wandb.log({f"parity_{model}_{data}": wandb.Image(plt)})
plt.show()
utviz.plot_calibration(
y_pred=y_pred.ravel(), y_std=y_std.ravel(), y_true=y_true.ravel()
)
plt.tight_layout()
plt.gcf()
if log:
wandb.log({f"calib_{model}_{data}": wandb.Image(plt)})
plt.show()
# utviz.plot_intervals_ordered(
# y_pred=y_pred.ravel(), y_std=y_std.ravel(), y_true=y_true.ravel(), n_subset=100
# )
# # plt.gcf()
# # wandb.log({f"intervals_{data}": wandb.Image(plt)})
# plt.show()
utviz.plot_sharpness(y_std=y_std.ravel(),)
plt.tight_layout()
plt.gcf()
if log:
wandb.log({f"sharpness_{model}_{data}": wandb.Image(plt)})
plt.show()
# utviz.plot_adversarial_group_calibration(
# y_pred=y_pred.ravel(), y_std=y_std.ravel(), y_true=y_true.ravel(), n_subset=100
# )
# # plt.gcf()
# # wandb.log({f"adverse_{data}": wandb.Image(plt)})
# plt.show()
```
#### File: numpyro/src/sparse.py
```python
from jax.scipy.linalg import cholesky, solve_triangular
from .utils import add_to_diagonal, init_inducing_kmeans
from .base import Predictive
from .means import zero_mean
from .kernels import RBF
from copy import deepcopy
from typing import Callable, Tuple
import jax.numpy as jnp
from chex import Array, dataclass
import numpyro
import numpyro.distributions as dist
from flax import struct
@struct.dataclass
class SGPFITC:
X: Array
y: Array
X_u: Array
mean: Callable
kernel: Callable
obs_noise: Array
jitter: float
def to_numpyro(self, y=None):
f_loc = self.mean(self.X)
_, W, D = fitc_precompute(
self.X, self.X_u, self.obs_noise, self.kernel, jitter=self.jitter
)
# Sample y according SGP
if y is not None:
return numpyro.sample(
"y",
dist.LowRankMultivariateNormal(loc=f_loc, cov_factor=W, cov_diag=D)
.expand_by(self.y.shape[:-1])
.to_event(self.y.ndim - 1),
obs=self.y,
)
else:
return numpyro.sample(
"y", dist.LowRankMultivariateNormal(loc=f_loc, cov_factor=W, cov_diag=D)
)
@struct.dataclass
class SGPVFE:
X: Array
y: Array
X_u: Array
mean: Callable
kernel: Callable
obs_noise: Array
jitter: float
def trace_term(self, X, W, obs_noise):
Kffdiag = self.kernel.diag(X)
Qffdiag = jnp.power(W, 2).sum(axis=1)
trace_term = (Kffdiag - Qffdiag).sum() / obs_noise
trace_term = jnp.clip(trace_term, a_min=0.0)
return -trace_term / 2.0
def to_numpyro(self, y=None):
f_loc = self.mean(self.X)
_, W, D = vfe_precompute(
self.X, self.X_u, self.obs_noise, self.kernel, jitter=self.jitter
)
numpyro.factor("trace_term", self.trace_term(self.X, W, self.obs_noise))
# Sample y according SGP
if y is not None:
return numpyro.sample(
"y",
dist.LowRankMultivariateNormal(loc=f_loc, cov_factor=W, cov_diag=D)
.expand_by(self.y.shape[:-1])
.to_event(self.y.ndim - 1),
obs=self.y,
)
else:
return numpyro.sample(
"y", dist.LowRankMultivariateNormal(loc=f_loc, cov_factor=W, cov_diag=D)
)
@struct.dataclass
class SGPPredictive(Predictive):
X: Array
y: Array
x_u: Array
Luu: Array
L: Array
W_Dinv_y: Array
obs_noise: dict
kernel_params: dict
kernel: Callable
def _pred_factorize(self, xtest):
Kux = self.kernel.cross_covariance(self.x_u, xtest)
Ws = solve_triangular(self.Luu, Kux, lower=True)
# pack
pack = jnp.concatenate([self.W_Dinv_y, Ws], axis=1)
Linv_pack = solve_triangular(self.L, pack, lower=True)
# unpack
Linv_W_Dinv_y = Linv_pack[:, : self.W_Dinv_y.shape[1]]
Linv_Ws = Linv_pack[:, self.W_Dinv_y.shape[1] :]
return Ws, Linv_W_Dinv_y, Linv_Ws
def predict_mean(self, xtest):
_, Linv_W_Dinv_y, Linv_Ws = self._pred_factorize(xtest)
loc_shape = self.y.T.shape[:-1] + (xtest.shape[0],)
loc = (Linv_W_Dinv_y.T @ Linv_Ws).reshape(loc_shape)
return loc.T
def predict_cov(self, xtest, noiseless=False):
n_test_samples = xtest.shape[0]
Ws, _, Linv_Ws = self._pred_factorize(xtest)
Kxx = self.kernel.gram(xtest)
if not noiseless:
Kxx = add_to_diagonal(Kxx, self.obs_noise)
Qss = Ws.T @ Ws
Σ = Kxx - Qss + Linv_Ws.T @ Linv_Ws
Σ_shape = self.y.T.shape[:-1] + (n_test_samples, n_test_samples)
Σ = jnp.reshape(Σ, Σ_shape)
return jnp.transpose(Σ, [1, 2, 0])
def _predict(self, xtest, full_covariance: bool = False, noiseless: bool = False):
n_test_samples = xtest.shape[0]
Ws, Linv_W_Dinv_y, Linv_Ws = self._pred_factorize(xtest)
loc_shape = self.y.T.shape[:-1] + (xtest.shape[0],)
μ = (Linv_W_Dinv_y.T @ Linv_Ws).reshape(loc_shape)
if full_covariance:
Kxx = self.kernel.gram(xtest)
if not noiseless:
Kxx = add_to_diagonal(Kxx, self.obs_noise)
Qss = Ws.T @ Ws
Σ = Kxx - Qss + Linv_Ws.T @ Linv_Ws
Σ_shape = self.y.T.shape[:-1] + (n_test_samples, n_test_samples)
Σ = jnp.reshape(Σ, Σ_shape)
return μ, Σ.reshape([1, 2, 0])
else:
Kxx = self.kernel.diag(xtest)
if not noiseless:
Kxx += self.obs_noise
Qss = jnp.power(Ws, 2).sum(axis=0)
σ = Kxx - Qss + jnp.power(Linv_Ws, 2).sum(axis=0)
cov_shape = self.y.T.shape[:-1] + (n_test_samples,)
σ = jnp.reshape(σ, cov_shape)
return μ.T, σ.T
def predict_var(self, xtest, noiseless=False):
n_test_samples = xtest.shape[0]
Ws, _, Linv_Ws = self._pred_factorize(xtest)
Kxx = self.kernel.diag(xtest)
if not noiseless:
Kxx += self.obs_noise
Qss = jnp.power(Ws, 2).sum(axis=0)
σ = Kxx - Qss + jnp.power(Linv_Ws, 2).sum(axis=0)
cov_shape = self.y.T.shape[:-1] + (n_test_samples,)
σ = jnp.reshape(σ, cov_shape)
return σ.T
def init_default_sgp_model(
Xtrain, n_features=1, inference="map", n_inducing=100, jitter=1e-5
):
X_u_init = init_inducing_kmeans(Xtrain, n_inducing, seed=123)
def numpyro_model(X, y):
if inference == "map" or "vi_mf" or "vi_full":
# Set priors on hyperparameters.
η = numpyro.sample("variance", dist.HalfCauchy(scale=5.0))
ℓ = numpyro.sample(
"length_scale", dist.Gamma(2.0, 1.0), sample_shape=(n_features,)
)
σ = numpyro.sample("obs_noise", dist.HalfCauchy(scale=5.0))
elif inference == "mll":
# set params and constraints on hyperparams
η = numpyro.param(
"variance", init_value=1.0, constraints=dist.constraints.positive
)
ℓ = numpyro.param(
"length_scale",
init_value=jnp.ones(n_features),
constraints=dist.constraints.positive,
)
σ = numpyro.param(
"obs_noise", init_value=0.01, onstraints=dist.constraints.positive
)
else:
raise ValueError(f"Unrecognized inference scheme: {inference}")
x_u = numpyro.param("x_u", init_value=X_u_init)
# Kernel Function
rbf_kernel = RBF(variance=η, length_scale=ℓ)
# GP Model
gp_model = SGPVFE(
X=X,
X_u=x_u,
y=y,
mean=zero_mean,
kernel=rbf_kernel,
obs_noise=σ,
jitter=jitter,
)
# Sample y according SGP
return gp_model.to_numpyro(y=y)
return numpyro_model
def init_sgp_predictive(kernel, params, x, y, jitter):
return SGPPredictive(
**get_cond_params(kernel=kernel, params=params, x=x, y=y, jitter=jitter)
)
def vfe_precompute(X, X_u, obs_noise, kernel, jitter: float = 1e-5):
# Kernel
Kuu = kernel.gram(X_u)
Kuu = add_to_diagonal(Kuu, jitter)
Luu = cholesky(Kuu, lower=True)
Kuf = kernel.cross_covariance(X_u, X)
# calculate cholesky
Luu = cholesky(Kuu, lower=True)
# compute W
W = solve_triangular(Luu, Kuf, lower=True).T
# compute D
D = jnp.ones(Kuf.shape[1]) * obs_noise
return Luu, W, D
def fitc_precompute(X, X_u, obs_noise, kernel, jitter: float = 1e-5):
# Kernel
Kuu = kernel.gram(X_u)
Kuu = add_to_diagonal(Kuu, jitter)
Luu = cholesky(Kuu, lower=True)
Kuf = kernel.cross_covariance(X_u, X)
# calculate cholesky
Luu = cholesky(Kuu, lower=True)
# compute W
W = solve_triangular(Luu, Kuf, lower=True).T
Kffdiag = kernel.diag(X)
Qffdiag = jnp.power(W, 2).sum(axis=1)
D = Kffdiag - Qffdiag + obs_noise
return Luu, W, D
def get_cond_params(
kernel, params: dict, x: Array, y: Array, jitter: float = 1e-5
) -> dict:
params = deepcopy(params)
x_u = params.pop("x_u")
obs_noise = params.pop("obs_noise")
kernel = kernel(**params)
n_samples = x.shape[0]
# calculate the cholesky factorization
Luu, W, D = vfe_precompute(x, x_u, obs_noise, kernel, jitter=jitter)
W_Dinv = W.T / D
K = W_Dinv @ W
K = add_to_diagonal(K, 1.0)
L = cholesky(K, lower=True)
# mean function
y_residual = y # mean function
y_2D = y_residual.reshape(-1, n_samples).T
W_Dinv_y = W_Dinv @ y_2D
return {
"X": x,
"y": y,
"Luu": Luu,
"L": L,
"W_Dinv_y": W_Dinv_y,
"x_u": x_u,
"kernel_params": params,
"obs_noise": obs_noise,
"kernel": kernel,
}
```
#### File: src/uncertain/monte_carlo.py
```python
from typing import Tuple
from .moment import MomentTransform, MomentTransformClass
import jax
from chex import Array, dataclass
import jax.numpy as jnp
import jax.random as jr
import tensorflow_probability.substrates.jax as tfp
dist = tfp.distributions
import abc
from distrax._src.utils.jittable import Jittable
class MCTransform(MomentTransformClass):
def __init__(self, gp_pred, n_samples: int, cov_type: bool = "diag"):
self.gp_pred = gp_pred
self.n_samples = n_samples
if cov_type == "diag":
self.z = dist.MultivariateNormalDiag
elif cov_type == "full":
self.z = dist.MultivariateNormalFullCovariance
else:
raise ValueError(f"Unrecognized covariance type: {cov_type}")
self.wm, self.wc = get_mc_weights(n_samples)
def predict_f(self, key, x, x_cov, full_covariance=False):
# create distribution
# print(x.min(), x.max(), x_cov.min(), x_cov.max())
x_dist = self.z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((self.n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(self.gp_pred.predict_mean, in_axes=0, out_axes=1)(
x_mc_samples
)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
if full_covariance:
# ===================
# Covariance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_mc - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
Wc = jnp.eye(self.n_samples) * self.wc
cov = jnp.einsum("ijk,jl,mlk->ikm", dfydx, Wc, dfydx.T)
# cov = self.wc * jnp.einsum("ijk,lmn->ilk", dfydx, dfydx)
return y_mu, cov
else:
# (N,P) = (N,M,P)
var = jnp.var(y_mu_mc, axis=1)
return y_mu, var
def predict_mean(self, key, x, x_cov):
# create distribution
x_dist = self.z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((self.n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(self.gp_pred.predict_mean, in_axes=0, out_axes=1)(
x_mc_samples
)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
return y_mu
def predict_cov(self, key, x, x_cov):
# create distribution
x_dist = self.z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((self.n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(self.gp_pred.predict_mean, in_axes=0, out_axes=1)(
x_mc_samples
)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
# ===================
# Covariance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_mc - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
cov = self.wc * jnp.einsum("ijk,lmn->ikl", dfydx, dfydx.T)
return y_mu, cov
def predict_var(self, key, x, x_cov):
# create distribution
x_dist = self.z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((self.n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(self.gp_pred.predict_mean, in_axes=0, out_axes=1)(
x_mc_samples
)
# variance of mc samples
# (N,P,) = (N,M,P)
y_var = jnp.var(y_mu_mc, axis=1)
return y_var
def init_mc_transform(gp_pred, n_samples: int, cov_type: bool = "diag"):
if cov_type == "diag":
z = dist.MultivariateNormalDiag
elif cov_type == "full":
z = dist.MultivariateNormalFullCovariance
else:
raise ValueError(f"Unrecognized covariance type: {cov_type}")
wm, wc = get_mc_weights(n_samples)
def predict_mean(key, x, x_cov):
# create distribution
x_dist = z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(gp_pred.predict_mean, in_axes=0, out_axes=1)(x_mc_samples)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
return y_mu
def predict_f(key, x, x_cov, full_covariance=False):
# create distribution
# print(x.min(), x.max(), x_cov.min(), x_cov.max())
x_dist = z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(gp_pred.predict_mean, in_axes=0, out_axes=1)(x_mc_samples)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
if full_covariance:
# ===================
# Covariance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_mc - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
cov = wc * jnp.einsum("ijk,lmn->ikl", dfydx, dfydx.T)
return y_mu, cov
else:
# (N,P) = (N,M,P)
var = jnp.var(y_mu_mc, axis=1)
return y_mu, var
def predict_cov(key, x, x_cov):
# create distribution
x_dist = z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(gp_pred.predict_mean, in_axes=0, out_axes=1)(x_mc_samples)
# mean of mc samples
# (N,P,) = (N,M,P)
y_mu = jnp.mean(y_mu_mc, axis=1)
# ===================
# Covariance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_mc - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
cov = wc * jnp.einsum("ijk,lmn->ikl", dfydx, dfydx.T)
return y_mu, cov
def predict_var(key, x, x_cov):
# create distribution
x_dist = z(x, x_cov)
# sample
x_mc_samples = x_dist.sample((n_samples,), key)
# function predictions over mc samples
# (N,M,P) = f(N,D,M)
y_mu_mc = jax.vmap(gp_pred.predict_mean, in_axes=0, out_axes=1)(x_mc_samples)
# mean of mc samples
# (N,P,) = (N,M,P)
y_var = jnp.var(y_mu_mc, axis=1)
return y_var
return MomentTransform(
predict_mean=predict_mean,
predict_cov=predict_cov,
predict_f=predict_f,
predict_var=predict_var,
)
def get_mc_weights(n_samples: int = 100) -> Tuple[float, float]:
"""Generate normalizers for MCMC samples"""
mean = 1.0 / n_samples
cov = 1.0 / (n_samples - 1)
return mean, cov
def get_mc_sigma_points(rng_key, n_features: int, n_samples: int = 100) -> Array:
"""Generate MCMC samples from a normal distribution"""
sigma_dist = dist.Normal(loc=jnp.zeros((n_features,)), scale=jnp.ones(n_features))
return sigma_dist.sample((n_samples,), rng_key)
```
#### File: src/uncertain/quadrature.py
```python
import chex
import jax
import jax.numpy as jnp
from typing import Callable, Optional, Tuple
from .moment import MomentTransform
from .unscented import UnscentedTransform
from chex import Array, dataclass
from scipy.special import factorial
from sklearn.utils.extmath import cartesian
from numpy.polynomial.hermite_e import hermegauss, hermeval
class GaussHermiteTransform(UnscentedTransform):
def __init__(self, gp_pred, n_features: int, degree: int = 3):
self.gp_pred = gp_pred
self.wm = get_quadrature_weights(n_features=n_features, degree=degree)
self.wc = self.wm
self.Wm, self.Wc = self.wm, jnp.diag(self.wm)
self.sigma_pts = get_quadrature_sigma_points(
n_features=n_features, degree=degree
)
def get_quadrature_sigma_points(n_features: int, degree: int = 3,) -> Array:
"""Generate Unscented samples"""
# 1D sigma-points (x) and weights (w)
x, w = hermegauss(degree)
# nD sigma-points by cartesian product
return cartesian([x] * n_features).T # column/sigma-point
def get_quadrature_weights(n_features: int, degree: int = 3,) -> Array:
"""Generate normalizers for MCMC samples"""
# 1D sigma-points (x) and weights (w)
x, w = hermegauss(degree)
# hermegauss() provides weights that cause posdef errors
w = factorial(degree) / (degree ** 2 * hermeval(x, [0] * (degree - 1) + [1]) ** 2)
return jnp.prod(cartesian([w] * n_features), axis=1)
```
#### File: src/uncertain/unscented.py
```python
import chex
import jax
import jax.numpy as jnp
from typing import Callable, Optional, Tuple
from .moment import MomentTransform, MomentTransformClass
from chex import Array, dataclass
import tensorflow_probability.substrates.jax as tfp
dist = tfp.distributions
class UnscentedTransform(MomentTransformClass):
def __init__(
self,
gp_pred,
n_features: int,
alpha: float = 1.0,
beta: float = 1.0,
kappa: Optional[float] = None,
):
self.gp_pred = gp_pred
self.sigma_pts = get_unscented_sigma_points(n_features, kappa, alpha)
self.Wm, self.wc = get_unscented_weights(n_features, kappa, alpha, beta)
self.Wc = jnp.diag(self.wc)
def predict_mean(self, x, x_cov):
# cholesky decomposition
L = jnp.linalg.cholesky(x_cov)
# calculate sigma points
# (D,M) = (D,1) + (D,D)@(D,M)
x_sigma_samples = x[..., None] + L @ self.sigma_pts
# ===================
# Mean
# ===================
# function predictions over mc samples
# (P,M) = (D,M)
y_mu_sigma = jax.vmap(self.gp_pred.predict_mean, in_axes=2, out_axes=1)(
x_sigma_samples
)
# mean of mc samples
# (N,M,P) @ (M,) -> (N,P)
y_mu = jnp.einsum("ijk,j->ik", y_mu_sigma, self.Wm)
return y_mu
def predict_f(self, x, x_cov, full_covariance=False):
# cholesky decomposition
L = jnp.linalg.cholesky(x_cov)
# calculate sigma points
# (D,M) = (D,1) + (D,D)@(D,M)
x_sigma_samples = x[..., None] + L @ self.sigma_pts
# ===================
# Mean
# ===================
# function predictions over mc samples
# (N,M,P) = (D,M)
y_mu_sigma = jax.vmap(self.gp_pred.predict_mean, in_axes=2, out_axes=1)(
x_sigma_samples
)
# mean of mc samples
# (N,M,P) @ (M,) -> (N,P)
y_mu = jnp.einsum("ijk,j->ik", y_mu_sigma, self.Wm)
# ===================
# Covariance
# ===================
if full_covariance:
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_sigma - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
cov = jnp.einsum("ijk,jl,mlk->ikm", dfydx, self.Wc, dfydx.T)
return y_mu, cov
else:
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_sigma - y_mu[..., None]
# (N,M,P) @ (M,) -> (N,P)
var = jnp.einsum("ijk,j->ik", dfydx ** 2, self.wc)
return y_mu, var
def predict_cov(self, key, x, x_cov):
# cholesky decomposition
L = jnp.linalg.cholesky(x_cov)
# calculate sigma points
# (D,M) = (D,1) + (D,D)@(D,M)
x_sigma_samples = x[..., None] + L @ self.sigma_pts
# ===================
# Mean
# ===================
# function predictions over mc samples
# (N,P,M) = (D,M)
y_mu_sigma = jax.vmap(self.gp_pred.predict_mean, in_axes=2, out_axes=1)(
x_sigma_samples
)
# mean of mc samples
# (N,P,M) @ (M,) -> (N,P)
y_mu = jnp.einsum("ijk,j->ik", y_mu_sigma, self.Wm)
# ===================
# Covariance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_sigma - y_mu[..., None]
# (N,M,P) @ (M,M) @ (N,M,P) -> (N,P,D)
y_cov = jnp.einsum("ijk,jl,mlk->ikm", dfydx, self.Wc, dfydx.T)
return y_cov
def predict_var(self, key, x, x_cov):
# cholesky decomposition
L = jnp.linalg.cholesky(x_cov)
# calculate sigma points
# (D,M) = (D,1) + (D,D)@(D,M)
x_sigma_samples = x[..., None] + L @ self.sigma_pts
# ===================
# Mean
# ===================
# function predictions over mc samples
# (N,P,M) = (D,M)
y_mu_sigma = jax.vmap(self.gp_pred.predict_mean, in_axes=2, out_axes=1)(
x_sigma_samples
)
# mean of mc samples
# (N,P,M) @ (M,) -> (N,P)
y_mu = jnp.einsum("ijk,j->ik", y_mu_sigma, self.Wm)
# ===================
# Variance
# ===================
# (N,P,M) - (N,P,1) -> (N,P,M)
dfydx = y_mu_sigma - y_mu[..., None]
# (N,M,P) @ (M,) -> (N,P)
var = jnp.einsum("ijk,j->ik", dfydx ** 2, self.wc)
return var
class SphericalTransform(UnscentedTransform):
def __init__(self, gp_pred, n_features: int):
super().__init__(
gp_pred=gp_pred, n_features=n_features, alpha=1.0, beta=0.0, kappa=0.0
)
def get_unscented_sigma_points(
n_features: int, kappa: Optional[float] = None, alpha: float = 1.0
) -> Tuple[chex.Array, chex.Array]:
"""Generate Unscented samples"""
# calculate kappa value
if kappa is None:
kappa = jnp.maximum(3.0 - n_features, 0.0)
lam = alpha ** 2 * (n_features + kappa) - n_features
c = jnp.sqrt(n_features + lam)
return jnp.hstack(
(jnp.zeros((n_features, 1)), c * jnp.eye(n_features), -c * jnp.eye(n_features))
)
def get_unscented_weights(
n_features: int,
kappa: Optional[float] = None,
alpha: float = 1.0,
beta: float = 2.0,
) -> Tuple[float, float]:
"""Generate normalizers for MCMC samples"""
# calculate kappa value
if kappa is None:
kappa = jnp.maximum(3.0 - n_features, 0.0)
lam = alpha ** 2 * (n_features + kappa) - n_features
wm = 1.0 / (2.0 * (n_features + lam)) * jnp.ones(2 * n_features + 1)
wc = wm.copy()
wm = jax.ops.index_update(wm, 0, lam / (n_features + lam))
wc = jax.ops.index_update(wc, 0, wm[0] + (1 - alpha ** 2 + beta))
return wm, wc
```
|
{
"source": "jejjohnson/hsic_alignment",
"score": 3
}
|
#### File: src/experiments/utils.py
```python
import itertools
from typing import Callable, Dict, Iterable, List, Union
from joblib import Parallel, delayed
def dict_product(dicts: Dict) -> List[Dict]:
"""Returns the product of a dictionary with lists
Parameters
----------
dicts : Dict,
a dictionary where each key has a list of inputs
Returns
-------
prod : List[Dict]
the list of dictionary products
Example
-------
>>> parameters = {
"samples": [100, 1_000, 10_000],
"dimensions": [2, 3, 10, 100, 1_000]
}
>>> parameters = list(dict_product(parameters))
>>> parameters
[{'samples': 100, 'dimensions': 2},
{'samples': 100, 'dimensions': 3},
{'samples': 1000, 'dimensions': 2},
{'samples': 1000, 'dimensions': 3},
{'samples': 10000, 'dimensions': 2},
{'samples': 10000, 'dimensions': 3}]
"""
return (dict(zip(dicts.keys(), x)) for x in itertools.product(*dicts.values()))
def run_parallel_step(
exp_step: Callable,
parameters: Iterable,
n_jobs: int = 2,
verbose: int = 1,
**kwargs
) -> List:
"""Helper function to run experimental loops in parallel
Parameters
----------
exp_step : Callable
a callable function which does each experimental step
parameters : Iterable,
an iterable (List, Dict, etc) of parameters to be looped through
n_jobs : int, default=2
the number of cores to use
verbose : int, default=1
the amount of information to display in the
Returns
-------
results : List
list of the results from the function
Examples
--------
Example 1 - No keyword arguments
>>> parameters = [1, 10, 100]
>>> def step(x): return x ** 2
>>> results = run_parallel_step(
exp_step=step,
parameters=parameters,
n_jobs=1, verbose=1
)
>>> results
[1, 100, 10000]
Example II: Keyword arguments
>>> parameters = [1, 10, 100]
>>> def step(x, a=1.0): return a * x ** 2
>>> results = run_parallel_step(
exp_step=step,
parameters=parameters,
n_jobs=1, verbose=1,
a=10
)
>>> results
[100, 10000, 1000000]
"""
# loop through parameters
results = Parallel(n_jobs=n_jobs, verbose=verbose)(
delayed(exp_step)(iparam, **kwargs) for iparam in parameters
)
return results
```
#### File: src/features/utils.py
```python
import itertools
from collections import namedtuple
from typing import List, Optional, Union
import pandas as pd
from scipy import stats
def dict_product(dicts):
"""
>>> list(dict_product(dict(number=[1,2], character='ab')))
[{'character': 'a', 'number': 1},
{'character': 'a', 'number': 2},
{'character': 'b', 'number': 1},
{'character': 'b', 'number': 2}]
"""
return (dict(zip(dicts.keys(), x)) for x in itertools.product(*dicts.values()))
corr_stats = namedtuple("corr_stats", ["pearson", "spearman"])
df_query = namedtuple("df_query", ["name", "elements"])
def subset_dataframe(df: pd.DataFrame, queries: List[df_query],) -> pd.DataFrame:
# copy dataframe to prevent overwriting
sub_df = df.copy()
#
for iquery in queries:
sub_df = sub_df[sub_df[iquery.name].isin(iquery.elements)]
return sub_df
def get_correlations(df: pd.DataFrame):
"""Inputs a dataframe and outputs the correlation between
the mutual information and the score.
Requires the 'mutual_info' and 'score' columns."""
# check that columns are in dataframe
msg = "No 'mutual_info' and/or 'score' column(s) found in dataframe"
assert {"mutual_info", "score"}.issubset(df.columns), msg
# get pearson correlation
corr_pear = stats.pearsonr(df.score, df.mutual_info)[0]
# get spearman correlation
corr_spear = stats.spearmanr(df.score, df.mutual_info)[0]
return corr_stats(corr_pear, corr_spear)
```
#### File: src/models/dependence.py
```python
import os
import sys
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Tuple, Union
# Kernel Dependency measure
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.kernel_approximation import Nystroem, RBFSampler
from sklearn.metrics.pairwise import linear_kernel, pairwise_kernels
from sklearn.preprocessing import KernelCenterer
from sklearn.utils import check_array, check_random_state
from scipy.spatial.distance import pdist, squareform
# Insert path to package,.
pysim_path = f"/home/emmanuel/code/pysim/"
sys.path.insert(0, pysim_path)
@dataclass
class HSICModel:
"""HSICModel as a form of a dataclass with a score method.
This initializes the parameters and then fits to some input
data and gives out a score.
Parameters
----------
kernel : str, default='rbf'
the kernel function
bias : bool, default=True
option for the bias term (only affects the HSIC method)
gamma_X : float, (optional, default=None)
gamma parameter for the kernel matrix of X
gamma_Y : float, (optional, default=None)
gamma parameter for the kernel matrix of Y
subsample : int, (optional, default=None)
option to subsample the X, Y
Example
--------
>>> from src.models.dependence import HSICModel
>>> from sklearn import datasets
>>> X, _ = datasets.make_blobs(n_samples=1_000, n_features=2, random_state=123)
>>> Y, _ = datasets.make_blobs(n_samples=1_000, n_features=2, random_state=1)
>>> hsic_model = HSICModel()
>>> hsic_model.gamma_X = 100
>>> hsic_model.gamma_Y = 0.01
>>> hsic_score = hsic_model.score(X, Y, 'hsic')
>>> print(hsic_score)
0.00042726396990996684
"""
kernel_X: str = "rbf"
kernel_Y: Optional[str] = "rbf"
bias: bool = True
gamma_X: Optional[float] = None
gamma_Y: Optional[float] = None
subsample: Optional[int] = None
kernel_kwargs_X: Optional[Dict] = None
kernel_kwargs_Y: Optional[Dict] = None
def get_score(
self, X: np.ndarray, Y: np.ndarray, method: str = "hsic", **kwargs
) -> float:
"""method to get the HSIC score
Parameters
----------
X : np.ndarray, (n_samples, n_features)
Y : np.ndarray, (n_samples, n_features)
method : str, default = 'hsic'
{'hsic', 'ka', 'cka'}
kwargs : dict, (optional)
Returns
-------
score : float
the score based on the hsic method proposed above
"""
if method == "hsic":
# change params for HSIC
self.normalize = False
self.center = True
elif method == "ka":
# change params for Kernel Alignment
self.normalize = True
self.center = False
elif method == "cka":
# change params for centered Kernel Alignment
self.normalize = True
self.center = True
else:
raise ValueError(f"Unrecognized hsic method: {method}")
# initialize HSIC model
clf_hsic = HSIC(
kernel_X=self.kernel_X,
kernel_Y=self.kernel_Y,
center=self.center,
subsample=self.subsample,
bias=self.bias,
gamma_X=self.gamma_X,
gamma_Y=self.gamma_Y,
kernel_params_X=self.kernel_kwargs_X,
kernel_params_Y=self.kernel_kwargs_Y,
**kwargs,
)
# calculate HSIC return scorer
clf_hsic.fit(X, Y)
# return score
return clf_hsic.score(X, normalize=self.normalize)
class HSIC(BaseEstimator):
"""Hilbert-Schmidt Independence Criterion (HSIC). This is
a method for measuring independence between two variables.
Methods in the Literature
* HSIC - centered, unnormalized
* KA - uncentered, normalized
* CKA - centered, normalized
Parameters
----------
center : bool, default=True
The option to center the kernel matrices after construction
bias : bool, default=True
To add the bias for the scaling. Only necessary if calculating HSIC alone.
subsample : int, default=None
The option to subsample the data.
random_state : int, default=123
The random state for the subsample.
kernel : string or callable, default="linear"
Kernel mapping used internally. A callable should accept two arguments
and the keyword arguments passed to this object as kernel_params, and
should return a floating point number. Set to "precomputed" in
order to pass a precomputed kernel matrix to the estimator
methods instead of samples.
gamma_X : float, default=None
Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
and sigmoid kernels. Used only by the X parameter.
Interpretation of the default value is left to the kernel;
see the documentation for sklearn.metrics.pairwise.
Ignored by other kernels.
gamma_Y : float, default=None
The same gamma parameter as the X. If None, the gamma will be estimated.
degree : float, default=3
Degree of the polynomial kernel. Ignored by other kernels.
coef0 : float, default=1
Zero coefficient for polynomial and sigmoid kernels.
Ignored by other kernels.
kernel_params : mapping of string to any, optional
Additional parameters (keyword arguments) for kernel function passed
as callable object.
Attributes
----------
hsic_value : float
The HSIC value is scored after fitting.
Information
-----------
Author : <NAME>
Email : <EMAIL>
Date : 14-Feb-2019
Example
-------
>>> samples, features = 100, 50
>>> X = np.random.randn(samples, features)
>>> A = np.random.rand(features, features)
>>> Y = X @ A
>>> hsic_clf = HSIC(center=True, kernel='linear')
>>> hsic_clf.fit(X, Y)
>>> cka_score = hsic_clf.score(X)
>>> print(f"<K_x,K_y> / ||K_xx|| / ||K_yy||: {cka_score:.3f}")
"""
def __init__(
self,
gamma_X: Optional[float] = None,
gamma_Y: Optional[float] = None,
kernel_X: Optional[Union[Callable, str]] = "linear",
kernel_Y: Optional[Union[Callable, str]] = "linear",
degree: float = 3,
coef0: float = 1,
kernel_params_X: Optional[dict] = None,
kernel_params_Y: Optional[dict] = None,
random_state: Optional[int] = None,
center: Optional[int] = True,
subsample: Optional[int] = None,
bias: bool = True,
):
self.gamma_X = gamma_X
self.gamma_Y = gamma_Y
self.center = center
self.kernel_X = kernel_X
self.kernel_Y = kernel_Y
self.degree = degree
self.coef0 = coef0
self.kernel_params_X = kernel_params_X
self.kernel_params_Y = kernel_params_Y
self.random_state = random_state
self.rng = check_random_state(random_state)
self.subsample = subsample
self.bias = bias
def fit(self, X, Y):
# Check sizes of X, Y
X = check_array(X, ensure_2d=True)
Y = check_array(Y, ensure_2d=True)
# Check samples are the same
assert (
X.shape[0] == Y.shape[0]
), f"Samples of X ({X.shape[0]}) and Samples of Y ({Y.shape[0]}) are not the same"
self.n_samples = X.shape[0]
self.dx_dimensions = X.shape[1]
self.dy_dimensions = Y.shape[1]
# subsample data if necessary
X = subset_indices(X, subsample=self.subsample, random_state=self.random_state)
Y = subset_indices(Y, subsample=self.subsample, random_state=self.random_state)
self.X_train_ = X
self.Y_train_ = Y
# Calculate the kernel matrices
K_x = self.compute_kernel(
X, kernel=self.kernel_X, gamma=self.gamma_X, params=self.kernel_params_X
)
K_y = self.compute_kernel(
Y, kernel=self.kernel_Y, gamma=self.gamma_Y, params=self.kernel_params_Y
)
# Center Kernel
# H = np.eye(n_samples) - (1 / n_samples) * np.ones(n_samples)
# K_xc = K_x @ H
if self.center == True:
K_x = KernelCenterer().fit_transform(K_x)
K_y = KernelCenterer().fit_transform(K_y)
# Compute HSIC value
self.hsic_value = np.sum(K_x * K_y)
# Calculate magnitudes
self.K_x_norm = np.linalg.norm(K_x)
self.K_y_norm = np.linalg.norm(K_y)
return self
def compute_kernel(self, X, Y=None, kernel="rbf", gamma=None, params=None):
# check if kernel is callable
if callable(kernel) and params == None:
params = {}
else:
# estimate the gamma parameter
if gamma is None:
gamma = estimate_gamma(X)
# set parameters for pairwise kernel
params = {"gamma": gamma, "degree": self.degree, "coef0": self.coef0}
return pairwise_kernels(X, Y, metric=kernel, filter_params=True, **params)
@property
def _pairwise(self):
return self.kernel == "precomputed"
def score(self, X, y=None, normalize=False):
"""This is not needed. It's only needed to comply with sklearn API.
We will use the target kernel alignment algorithm as a score
function. This can be used to find the best parameters."""
if normalize == True:
return self.hsic_value / self.K_x_norm / self.K_y_norm
elif normalize == False:
if self.bias:
self.hsic_bias = 1 / (self.n_samples ** 2)
else:
self.hsic_bias = 1 / (self.n_samples - 1) ** 2
return self.hsic_bias * self.hsic_value
else:
raise ValueError(f"Unrecognized normalize argument: {normalize}")
class RandomizedHSIC(BaseEstimator):
"""Hilbert-Schmidt Independence Criterion (HSIC). This is
a method for measuring independence between two variables. This method
uses the Nystrom method as an approximation to the large kernel matrix.
Typically this works really well as it is data-dependent; thus it will
converge to the real kernel matrix as the number of components increases.
Methods in the Literature
* HSIC - centered, unnormalized
* KA - uncentered, normalized
* CKA - centered, normalized
Parameters
----------
center : bool, default=True
The option to center the kernel matrices after construction
bias : bool, default=True
To add the bias for the scaling. Only necessary if calculating HSIC alone.
subsample : int, default=None
The option to subsample the data.
random_state : int, default=123
The random state for the subsample.
kernel : string or callable, default="linear"
Kernel mapping used internally. A callable should accept two arguments
and the keyword arguments passed to this object as kernel_params, and
should return a floating point number. Set to "precomputed" in
order to pass a precomputed kernel matrix to the estimator
methods instead of samples.
gamma_X : float, default=None
Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
and sigmoid kernels. Used only by the X parameter.
Interpretation of the default value is left to the kernel;
see the documentation for sklearn.metrics.pairwise.
Ignored by other kernels.
gamma_Y : float, default=None
The same gamma parameter as the X. If None, the same gamma_X will be
used for the Y.
degree : float, default=3
Degree of the polynomial kernel. Ignored by other kernels.
coef0 : float, default=1
Zero coefficient for polynomial and sigmoid kernels.
Ignored by other kernels.
kernel_params : mapping of string to any, optional
Additional parameters (keyword arguments) for kernel function passed
as callable object.
Attributes
----------
hsic_value : float
The HSIC value is scored after fitting.
Information
-----------
Author : <NAME>
Email : <EMAIL>
Date : 14-Feb-2019
Example
-------
>>> samples, features, components = 100, 50, 10
>>> X = np.random.randn(samples, features)
>>> A = np.random.rand(features, features)
>>> Y = X @ A
>>> rhsic_clf = RandomizeHSIC(center=True, n_components=components)
>>> rhsic_clf.fit(X, Y)
>>> cka_score = rhsic_clf.score(X)
>>> print(f"<K_x,K_y> / ||K_xx|| / ||K_yy||: {cka_score:.3f}")
"""
def __init__(
self,
n_components: int = 100,
gamma_X: Optional[None] = None,
gamma_Y: Optional[None] = None,
kernel: Union[Callable, str] = "linear",
degree: float = 3,
coef0: float = 1,
kernel_params: Optional[dict] = None,
random_state: Optional[int] = None,
center: Optional[int] = True,
normalized: Optional[bool] = True,
subsample: Optional[int] = None,
bias: bool = True,
):
self.n_components = n_components
self.gamma_X = gamma_X
self.gamma_Y = gamma_Y
self.center = center
self.kernel = kernel
self.degree = degree
self.coef0 = coef0
self.kernel_params = kernel_params
self.random_state = random_state
self.rng = check_random_state(random_state)
self.subsample = subsample
self.bias = bias
def fit(self, X, Y):
# Check sizes of X, Y
X = check_array(X, ensure_2d=True)
Y = check_array(Y, ensure_2d=True)
# Check samples are the same
assert (
X.shape[0] == Y.shape[0]
), f"Samples of X ({X.shape[0]}) and Samples of Y ({Y.shape[0]}) are not the same"
self.n_samples = X.shape[0]
self.dx_dimensions = X.shape[1]
self.dy_dimensions = Y.shape[1]
# subsample data if necessary
X = subset_indices(X, subsample=self.subsample, random_state=self.random_state)
Y = subset_indices(Y, subsample=self.subsample, random_state=self.random_state)
self.X_train_ = X
self.Y_train_ = Y
# Calculate Kernel Matrices
Zx = self.compute_kernel(X, gamma=self.gamma_X)
Zy = self.compute_kernel(Y, gamma=self.gamma_Y)
# Center Kernel
# H = np.eye(n_samples) - (1 / n_samples) * np.ones(n_samples)
# K_xc = K_x @ H
if self.center == True:
Zx = Zx - Zx.mean(axis=0)
Zy = Zy - Zy.mean(axis=0)
# Compute HSIC value
if self.n_components < self.n_samples:
Rxy = Zx.T @ Zy
self.hsic_value = np.sum(Rxy * Rxy)
# Calculate magnitudes
self.Zx_norm = np.linalg.norm(Zx.T @ Zx)
# print("Norm (FxF):", np.linalg.norm(Zx.T @ Zx))
# print("Norm (NxN):", np.linalg.norm(Zx @ Zx.T))
self.Zy_norm = np.linalg.norm(Zy.T @ Zy)
# print("Norm (FxF):", np.linalg.norm(Zy.T @ Zy))
# print("Norm (NxN):", np.linalg.norm(Zy @ Zy.T))
else:
Rxx = Zx @ Zx.T
Ryy = Zy @ Zy.T
self.hsic_value = np.sum(Rxx * Ryy)
# Calculate magnitudes
self.Zx_norm = np.linalg.norm(Zx @ Zx.T)
self.Zy_norm = np.linalg.norm(Zy @ Zy.T)
return self
def compute_kernel(self, X, Y=None, gamma=None, *args, **kwargs):
# estimate gamma if None
if gamma is None:
gamma = estimate_gamma(X)
# initialize RBF kernel
nystrom_kernel = Nystroem(
gamma=gamma,
kernel=self.kernel,
n_components=self.n_components,
coef0=self.coef0,
degree=self.degree,
random_state=self.random_state,
*args,
**kwargs,
)
# transform data
return nystrom_kernel.fit_transform(X)
def score(self, X, y=None, normalize=False):
"""This is not needed. It's only needed to comply with sklearn API.
We will use the target kernel alignment algorithm as a score
function. This can be used to find the best parameters."""
if normalize == True:
return self.hsic_value / self.Zx_norm / self.Zy_norm
elif normalize == False:
if self.bias:
self.hsic_bias = 1 / (self.n_samples ** 2)
else:
self.hsic_bias = 1 / (self.n_samples - 1) ** 2
return self.hsic_bias * self.hsic_value
else:
raise ValueError(f"Unrecognized normalize argument: {normalize}")
def scotts_factor(X: np.ndarray) -> float:
"""Scotts Method to estimate the length scale of the
rbf kernel.
factor = n**(-1./(d+4))
Parameters
----------
X : np.ndarry
Input array
Returns
-------
factor : float
the length scale estimated
"""
n_samples, n_features = X.shape
return np.power(n_samples, -1 / (n_features + 4.0))
def silvermans_factor(X: np.ndarray) -> float:
"""Silvermans method used to estimate the length scale
of the rbf kernel.
factor = (n * (d + 2) / 4.)**(-1. / (d + 4)).
Parameters
----------
X : np.ndarray,
Input array
Returns
-------
factor : float
the length scale estimated
"""
n_samples, n_features = X.shape
base = (n_samples * (n_features + 2.0)) / 4.0
return np.power(base, -1 / (n_features + 4.0))
def kth_distance(dists: np.ndarray, percent: float) -> np.ndarray:
if isinstance(percent, float):
percent /= 100
# kth distance calculation (50%)
kth_sample = int(percent * dists.shape[0])
# take the Kth neighbours of that distance
k_dist = dists[:, kth_sample]
return k_dist
def sigma_estimate(
X: np.ndarray,
method: str = "median",
percent: Optional[int] = None,
heuristic: bool = False,
) -> float:
# get the squared euclidean distances
if method == "silverman":
return silvermans_factor(X)
elif method == "scott":
return scotts_factor(X)
elif percent is not None:
kth_sample = int((percent / 100) * X.shape[0])
dists = np.sort(squareform(pdist(X, "sqeuclidean")))[:, kth_sample]
else:
dists = np.sort(pdist(X, "sqeuclidean"))
if method == "median":
sigma = np.median(dists)
elif method == "mean":
sigma = np.mean(dists)
else:
raise ValueError(f"Unrecognized distance measure: {method}")
if heuristic:
sigma = np.sqrt(sigma / 2)
return sigma
def subset_indices(
X: np.ndarray, subsample: Optional[int] = None, random_state: int = 123,
) -> Tuple[np.ndarray, np.ndarray]:
if subsample is not None and subsample < X.shape[0]:
rng = check_random_state(random_state)
indices = np.arange(X.shape[0])
subset_indices = rng.permutation(indices)[:subsample]
X = X[subset_indices, :]
return X
```
#### File: src/models/kernel.py
```python
from typing import Optional
import numpy as np
from scipy import stats
from scipy.spatial.distance import pdist, squareform
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.utils import check_array, check_random_state
class RandomFourierFeatures(BaseEstimator, TransformerMixin):
"""Random Fourier Features Kernel Matrix Approximation
Author: <NAME>
Email : <EMAIL>
<EMAIL>
Date : 3rd - August, 2018
"""
def __init__(self, n_components=50, gamma=None, random_state=None):
self.gamma = gamma
# Dimensionality D (number of MonteCarlo samples)
self.n_components = n_components
self.rng = check_random_state(random_state)
self.fitted = False
def fit(self, X, y=None):
""" Generates MonteCarlo random samples """
X = check_array(X, ensure_2d=True, accept_sparse="csr")
n_features = X.shape[1]
# Generate D iid samples from p(w)
self.weights = (2 * self.gamma) * self.rng.normal(
size=(n_features, self.n_components)
)
# Generate D iid samples from Uniform(0,2*pi)
self.bias = 2 * np.pi * self.rng.rand(self.n_components)
# set fitted flag
self.fitted = True
return self
def transform(self, X):
""" Transforms the data X (n_samples, n_features) to the new map space Z(X) (n_samples, n_components)"""
if not self.fitted:
raise NotFittedError(
"RBF_MonteCarlo must be fitted beform computing the feature map Z"
)
# Compute feature map Z(x):
Z = np.dot(X, self.weights) + self.bias[np.newaxis, :]
np.cos(Z, out=Z)
Z *= np.sqrt(2 / self.n_components)
return Z
def compute_kernel(self, X):
""" Computes the approximated kernel matrix K """
if not self.fitted:
raise NotFittedError(
"RBF_MonteCarlo must be fitted beform computing the kernel matrix"
)
Z = self.transform(X)
return np.dot(Z, Z.T)
def get_param_grid(
init_sigma: float = 1.0,
factor: int = 2,
n_grid_points: int = 20,
estimate_params: Optional[dict] = None,
) -> dict:
if init_sigma is None:
init_sigma = 1.0
# create bounds for search space (logscale)
init_space = 10 ** (-factor)
end_space = 10 ** (factor)
# create param grid
param_grid = np.logspace(
np.log10(init_sigma * init_space),
np.log10(init_sigma * end_space),
n_grid_points,
)
return param_grid
def estimate_sigma(
X: np.ndarray,
subsample: Optional[int] = None,
method: str = "median",
percent: Optional[float] = 0.15,
scale: float = 1.0,
random_state: Optional[int] = None,
) -> float:
"""A function to provide a reasonable estimate of the sigma values
for the RBF kernel using different methods.
Parameters
----------
X : array, (n_samples, d_dimensions)
The data matrix to be estimated.
method : str, default: 'median'
different methods used to estimate the sigma for the rbf kernel
matrix.
* Mean
* Median
* Silverman
* Scott - very common for density estimation
percent : float, default=0.15
The kth percentage of distance chosen
scale : float, default=None
Option to scale the sigma chosen. Typically used with the
median or mean method as they are data dependent.
random_state : int, (default: None)
controls the seed for the subsamples drawn to represent
the data distribution
Returns
-------
sigma : float
The estimated sigma value
Resources
---------
- Original MATLAB function: https://goo.gl/xYoJce
Information
-----------
Author : <NAME>
Email : <EMAIL>
: <EMAIL>
Date : 6 - July - 2018
"""
X = check_array(X, ensure_2d=True)
rng = check_random_state(random_state)
# subsampling
[n_samples, d_dimensions] = X.shape
if subsample is not None:
X = rng.permutation(X)[:subsample, :]
# print(method, percent)
if method == "mean" and percent is None:
sigma = np.mean(pdist(X))
elif method == "mean" and percent is not None:
kth_sample = int(percent * n_samples)
sigma = np.mean(np.sort(squareform(pdist(X)))[:, kth_sample])
elif method == "median" and percent is None:
sigma = np.median(pdist(X))
elif method == "median" and percent is not None:
kth_sample = int(percent * n_samples)
sigma = np.median(np.sort(squareform(pdist(X)))[:, kth_sample])
elif method == "silverman":
sigma = np.power(
n_samples * (d_dimensions + 2.0) / 4.0, -1.0 / (d_dimensions + 4)
)
elif method == "scott":
sigma = np.power(n_samples, -1.0 / (d_dimensions + 4))
else:
raise ValueError('Unrecognized mode "{}".'.format(method))
# scale the sigma by a factor
if scale is not None:
sigma *= scale
# return sigma
return sigma
def gamma_to_sigma(gamma: float) -> float:
"""Transforms the gamma parameter into sigma using the
following relationship:
1
sigma = -----------------
sqrt( 2 * gamma )
"""
return 1 / np.sqrt(2 * gamma)
def sigma_to_gamma(sigma: float) -> float:
"""Transforms the sigma parameter into gamma using the
following relationship:
1
gamma = -----------
2 * sigma^2
"""
return 1 / (2 * sigma ** 2)
def demo():
n_samples = 1000
n_features = 50
n_components = 1000
gamma = 2
X = np.random.randn(n_samples, n_features)
# actual RBF Kernel
K = rbf_kernel(X, gamma=gamma)
# approximate kernel
clf_rff = RandomFourierFeatures(
n_components=n_components, gamma=gamma, random_state=123
)
clf_rff.fit(X)
K_approx = clf_rff.compute_kernel(X)
# compute difference
err = ((K - K_approx) ** 2).mean()
print(
f"MSE: {err:.6f}\n...with {n_components} random features, good enough approximation..."
)
if __name__ == "__main__":
demo()
```
|
{
"source": "jejjohnson/jax-flows",
"score": 2
}
|
#### File: jax-flows/tests/test_bijections.py
```python
import unittest
import jax.numpy as np
from jax import random
from jax.experimental import stax
import flows
def is_bijective(
test, init_fun, inputs=random.uniform(random.PRNGKey(0), (20, 4), minval=-10.0, maxval=10.0), tol=1e-3
):
input_dim = inputs.shape[1]
params, direct_fun, inverse_fun = init_fun(random.PRNGKey(0), input_dim)
mapped_inputs = direct_fun(params, inputs)[0]
reconstructed_inputs = inverse_fun(params, mapped_inputs)[0]
test.assertTrue(np.allclose(inputs, reconstructed_inputs, atol=tol))
def returns_correct_shape(
test, init_fun, inputs=random.uniform(random.PRNGKey(0), (20, 4), minval=-10.0, maxval=10.0)
):
input_dim = inputs.shape[1]
params, direct_fun, inverse_fun = init_fun(random.PRNGKey(0), input_dim)
mapped_inputs, log_det_jacobian = direct_fun(params, inputs)
test.assertTrue(inputs.shape == mapped_inputs.shape)
test.assertTrue((inputs.shape[0],) == log_det_jacobian.shape)
mapped_inputs, log_det_jacobian = inverse_fun(params, inputs)
test.assertTrue(inputs.shape == mapped_inputs.shape)
test.assertTrue((inputs.shape[0],) == log_det_jacobian.shape)
class Tests(unittest.TestCase):
def test_shuffle(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.Shuffle())
def test_reverse(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.Reverse())
def test_affine_coupling(self):
def transform(rng, input_dim, output_dim, hidden_dim=64, act=stax.Relu):
init_fun, apply_fun = stax.serial(
stax.Dense(hidden_dim), act, stax.Dense(hidden_dim), act, stax.Dense(output_dim),
)
_, params = init_fun(rng, (input_dim,))
return params, apply_fun
inputs = random.uniform(random.PRNGKey(0), (20, 5), minval=-10.0, maxval=10.0)
init_fun = flows.AffineCoupling(transform)
for test in (returns_correct_shape, is_bijective):
test(self, init_fun, inputs)
init_fun = flows.AffineCouplingSplit(transform, transform)
for test in (returns_correct_shape, is_bijective):
test(self, init_fun, inputs)
def test_made(self):
def get_masks(input_dim, hidden_dim=64, num_hidden=1):
masks = []
input_degrees = np.arange(input_dim)
degrees = [input_degrees]
for n_h in range(num_hidden + 1):
degrees += [np.arange(hidden_dim) % (input_dim - 1)]
degrees += [input_degrees % input_dim - 1]
for (d0, d1) in zip(degrees[:-1], degrees[1:]):
masks += [np.transpose(np.expand_dims(d1, -1) >= np.expand_dims(d0, 0)).astype(np.float32)]
return masks
def masked_transform(rng, input_dim):
masks = get_masks(input_dim, hidden_dim=64, num_hidden=1)
act = stax.Relu
init_fun, apply_fun = stax.serial(
flows.MaskedDense(masks[0]),
act,
flows.MaskedDense(masks[1]),
act,
flows.MaskedDense(masks[2].tile(2)),
)
_, params = init_fun(rng, (input_dim,))
return params, apply_fun
for test in (returns_correct_shape, is_bijective):
test(self, flows.MADE(masked_transform))
def test_actnorm(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.ActNorm())
# Test data-dependent initialization
inputs = random.uniform(random.PRNGKey(0), (20, 3), minval=-10.0, maxval=10.0)
input_dim = inputs.shape[1]
init_fun = flows.Serial(flows.ActNorm())
params, direct_fun, inverse_fun = init_fun(random.PRNGKey(0), inputs.shape[1:], init_inputs=inputs)
mapped_inputs, _ = direct_fun(params, inputs)
self.assertFalse((np.abs(mapped_inputs.mean(0)) > 1e6).any())
self.assertTrue(np.allclose(np.ones(input_dim), mapped_inputs.std(0)))
def test_invertible_linear(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.InvertibleLinear())
def test_fixed_invertible_linear(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.FixedInvertibleLinear())
def test_sigmoid(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.Sigmoid())
def test_logit(self):
inputs = random.uniform(random.PRNGKey(0), (20, 3))
for test in (returns_correct_shape, is_bijective):
test(self, flows.Logit(), inputs)
def test_serial(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.Serial(flows.Shuffle(), flows.Shuffle()))
def test_batchnorm(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.BatchNorm())
def test_neural_spline(self):
for test in (returns_correct_shape, is_bijective):
test(self, flows.NeuralSplineCoupling())
```
#### File: jax-flows/tests/test_distributions.py
```python
import unittest
import jax.numpy as np
from jax import random
from jax.scipy.stats import multivariate_normal
from sklearn import datasets, mixture
import flows
def returns_correct_shape(
test, init_fun, inputs=random.uniform(random.PRNGKey(0), (20, 4), minval=-10.0, maxval=10.0)
):
num_inputs, input_dim = inputs.shape
init_key, sample_key = random.split(random.PRNGKey(0))
params, log_pdf, sample = init_fun(init_key, input_dim)
log_pdfs = log_pdf(params, inputs)
samples = sample(sample_key, params, num_inputs)
test.assertTrue(log_pdfs.shape == (num_inputs,))
test.assertTrue(samples.shape == inputs.shape)
class Tests(unittest.TestCase):
def test_normal(self):
inputs = random.uniform(random.PRNGKey(0), (20, 2), minval=-3.0, maxval=3.0)
input_dim = inputs.shape[1]
init_key, sample_key = random.split(random.PRNGKey(0))
init_fun = flows.Normal()
params, log_pdf, sample = init_fun(init_key, input_dim)
log_pdfs = log_pdf(params, inputs)
mean = np.zeros(input_dim)
covariance = np.eye(input_dim)
true_log_pdfs = multivariate_normal.logpdf(inputs, mean, covariance)
self.assertTrue(np.allclose(log_pdfs, true_log_pdfs))
for test in (returns_correct_shape,):
test(self, flows.Normal())
def test_gmm(self):
inputs = datasets.make_blobs()[0]
input_dim = inputs.shape[1]
init_key, sample_key = random.split(random.PRNGKey(0))
gmm = mixture.GaussianMixture(3)
gmm.fit(inputs)
init_fun = flows.GMM(gmm.means_, gmm.covariances_, gmm.weights_)
params, log_pdf, sample = init_fun(init_key, input_dim)
log_pdfs = log_pdf(params, inputs)
self.assertTrue(np.allclose(log_pdfs, gmm.score_samples(inputs)))
for test in (returns_correct_shape,):
test(self, init_fun, inputs)
def test_flow(self):
for test in (returns_correct_shape,):
test(self, flows.Flow(flows.Reverse(), flows.Normal()))
```
|
{
"source": "jejjohnson/kernellib",
"score": 4
}
|
#### File: kernels/derivative_functions/numba_derivative.py
```python
from numba import jit
import numpy as np
@jit
def rbf_derivative_numba(x_train, x_function, weights, kernel_mat,
n_derivative=1, gamma=1.0):
"""This function calculates the rbf derivative
Parameters
----------
x_train : array, [N x D]
The training data used to find the kernel model.
x_function : array, [M x D]
The test points (or vector) to use.
weights : array, [N x D]
The weights found from the kernel model
y = K * weights
kernel_mat: array, [N x M], default: None
The rbf kernel matrix with the similarities between the test
points and the training points.
n_derivative : int, (default = 1) {1, 2}
chooses which nth derivative to calculate
gamma : float, default: None
the parameter for the rbf_kernel matrix function
Returns
-------
derivative : array, [M x D]
returns the derivative with respect to training points used in
the kernel model and the test points.
Information
-----------
Author: <NAME>
Email : <EMAIL>
<EMAIL>
"""
# initialize rbf kernel
derivative = np.zeros(np.shape(x_function))
# consolidate the parameters
theta = 2 * gamma
# 1st derivative
if n_derivative == 1:
# loop through dimensions
for dim in np.arange(0, np.shape(x_function)[1]):
# loop through the number of test points
for iTest in np.arange(0, np.shape(x_function)[0]):
# loop through the number of test points
for iTrain in np.arange(0, np.shape(x_train)[0]):
# calculate the derivative for the test points
derivative[iTest, dim] += theta * weights[iTrain] * \
(x_train[iTrain, dim] -
x_function[iTest, dim]) * \
kernel_mat[iTrain, iTest]
# 2nd derivative
elif n_derivative == 2:
# loop through dimensions
for dim in np.arange(0, np.shape(x_function)[1]):
# loop through the number of test points
for iTest in np.arange(0, np.shape(x_function)[0]):
# loop through the number of test points
for iTrain in np.arange(0, np.shape(x_train)[0]):
derivative[iTest, dim] += weights[iTrain] * \
(theta ** 2 *
(x_train[iTrain, dim] - x_function[iTest, dim]) ** 2
- theta) * \
kernel_mat[iTrain, iTest]
return derivative
```
#### File: kernellib/utils/visualization.py
```python
import matplotlib.pyplot as plt
def plot_gp(xtest, predictions, std=None, xtrain=None, ytrain=None, title=None, save_name=None):
xtest, predictions = xtest.squeeze(), predictions.squeeze()
fig, ax = plt.subplots()
# Plot the training data
if (xtrain is not None) and (ytrain is not None):
xtrain, ytrain = xtrain.squeeze(), ytrain.squeeze()
ax.scatter(xtrain, ytrain, s=100, color='r', label='Training Data')
# plot the testing data
ax.plot(xtest, predictions, linewidth=5,
color='k', label='Predictions')
# plot the confidence interval
if std is not None:
std = std.squeeze()
upper_bound = predictions + 1.960 * std
lower_bound = predictions - 1.960 * std
ax.fill_between(xtest, upper_bound, lower_bound,
color='red', alpha=0.2, label='95% Condidence Interval')
# ax.legend()
if title is not None:
ax.set_title(title)
ax.tick_params(
axis='both',
which='both',
bottom=False,
top=False,
left=False,
labelleft=False,
labelbottom=False)
if save_name:
fig.savefig(save_name)
else:
plt.show()
return fig
```
#### File: kernellib/tests/test_schroedinger.py
```python
# Tests for the kwargs
# TODO: test adjacency_kwargs
# TODO: test embedding_kwargs
# TODO: test eigensolver_kwargs
# TODO: test potential_kwargs
# TODO: Test fit vs fit_transform
# TODO: Test bad arguments
# TODO: make estimator checks pass
# def test_estimator_checks():
# from sklearn.utils.estimator_checks import check_estimator
# for Embeddings in Embeddings:
# yield check_estimator, embedding
```
|
{
"source": "jejjohnson/pysim",
"score": 2
}
|
#### File: pysim/information/kde.py
```python
from typing import Optional, Union, Dict, List
import numpy as np
import statsmodels.api as sm
from sklearn.utils import check_array
def kde_entropy_uni(X: np.ndarray, **kwargs):
# check input array
X = check_array(X, ensure_2d=True)
# initialize KDE
kde_density = sm.nonparametric.KDEUnivariate(X)
kde_density.fit(**kwargs)
return kde_density.entropy
```
|
{
"source": "jejjohnson/rbig",
"score": 3
}
|
#### File: rbig/model/_rbig.py
```python
from typing import Dict, Tuple, Optional
import numpy as np
from sklearn.utils import check_random_state, check_array
from sklearn.base import BaseEstimator, TransformerMixin
from scipy import stats
from scipy.stats import norm, uniform, ortho_group, entropy as sci_entropy
from scipy.interpolate import interp1d
from rbig.information.total_corr import information_reduction
from rbig.information.entropy import entropy_marginal
from rbig.utils import make_cdf_monotonic
from sklearn.decomposition import PCA
import sys
import logging
from rbig.transform.gaussian import (
gaussian_transform,
gaussian_fit_transform,
gaussian_inverse_transform,
gaussian_transform_jacobian,
)
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout,
format="%(asctime)s: %(levelname)s: %(message)s",
)
logger = logging.getLogger()
# logger.setLevel(logging.INFO)
class RBIG(BaseEstimator, TransformerMixin):
""" Rotation-Based Iterative Gaussian-ization (RBIG). This algorithm transforms
any multidimensional data to a Gaussian. It also provides a sampling mechanism
whereby you can provide multidimensional gaussian data and it will generate
multidimensional data in the original domain. You can calculate the probabilities
as well as have access to a few information theoretic measures like total
correlation and entropy.
Parameters
----------
n_layers : int, optional (default 1000)
The number of steps to run the sequence of marginal gaussianization
and then rotation
rotation_type : {'PCA', 'random'}
The rotation applied to the marginally Gaussian-ized data at each iteration.
- 'pca' : a principal components analysis rotation (PCA)
- 'random' : random rotations
- 'ica' : independent components analysis (ICA)
pdf_resolution : int, optional (default 1000)
The number of points at which to compute the gaussianized marginal pdfs.
The functions that map from original data to gaussianized data at each
iteration have to be stored so that we can invert them later - if working
with high-dimensional data consider reducing this resolution to shorten
computation time.
method : str, default='custom'
pdf_extension : int, optional (default 0.1)
The fraction by which to extend the support of the Gaussian-ized marginal
pdf compared to the empirical marginal PDF.
verbose : int, optional
If specified, report the RBIG iteration number every
progress_report_interval iterations.
zero_tolerance : int, optional (default=60)
The number of layers where the total correlation should not change
between RBIG iterations. If there is no zero_tolerance, then the
method will stop iterating regardless of how many the user sets as
the n_layers.
rotation_kwargs : dict, optional (default=None)
Any extra keyword arguments that you want to pass into the rotation
algorithms (i.e. ICA or PCA). See the respective algorithms on
scikit-learn for more details.
random_state : int, optional (default=None)
Control the seed for any randomization that occurs in this algorithm.
entropy_correction : bool, optional (default=True)
Implements the shannon-millow correction to the entropy algorithm
Attributes
----------
gauss_data : array, (n_samples x d_dimensions)
The gaussianized data after the RBIG transformation
residual_info : array, (n_layers)
The cumulative amount of information between layers. It should exhibit
a curve with a plateau to indicate convergence.
rotation_matrix = dict, (n_layers)
A rotation matrix that was calculated and saved for each layer.
gauss_params = dict, (n_layers)
The cdf and pdf for the gaussianization parameters used for each layer.
References
----------
* Original Paper : Iterative Gaussianization: from ICA to Random Rotations
https://arxiv.org/abs/1602.00229
* Original MATLAB Implementation
http://isp.uv.es/rbig.html
* Original Python Implementation
https://github.com/spencerkent/pyRBIG
"""
def __init__(
self,
n_layers: int = 1_000,
rotation_type: str = "PCA",
method: str = "custom",
pdf_resolution: int = 1_000,
pdf_extension: int = 10,
random_state: Optional[int] = None,
verbose: int = 0,
tolerance: int = None,
zero_tolerance: int = 60,
entropy_correction: bool = True,
rotation_kwargs: Dict = {},
base="gauss",
n_quantiles: int = 1_000,
) -> None:
self.n_layers = n_layers
self.rotation_type = rotation_type
self.method = method
self.pdf_resolution = pdf_resolution
self.pdf_extension = pdf_extension
self.random_state = random_state
self.verbose = verbose
self.tolerance = tolerance
self.zero_tolerance = zero_tolerance
self.entropy_correction = entropy_correction
self.rotation_kwargs = rotation_kwargs
self.base = base
self.n_quantiles = n_quantiles
def fit(self, X):
""" Fit the model with X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
self : object
Returns the instance itself.
"""
X = check_array(X, ensure_2d=True)
self._fit(X)
return self
def _fit(self, data):
""" Fit the model with data.
Parameters
----------
data : array-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
self : object
Returns the instance itself.
"""
data = check_array(data, ensure_2d=True)
if self.pdf_extension is None:
self.pdf_extension = 10
if self.pdf_resolution is None:
self.pdf_resolution = 2 * np.round(np.sqrt(data.shape[0]))
self.X_fit_ = data
gauss_data = np.copy(data)
n_samples, n_dimensions = np.shape(data)
if self.zero_tolerance is None:
self.zero_tolerance = self.n_layers + 1
if self.tolerance is None:
self.tolerance = self._get_information_tolerance(n_samples)
logging.debug("Data (shape): {}".format(np.shape(gauss_data)))
# Initialize stopping criteria (residual information)
self.residual_info = list()
self.gauss_params = list()
self.rotation_matrix = list()
# Loop through the layers
logging.debug("Running: Looping through the layers...")
for layer in range(self.n_layers):
if self.verbose > 2:
print("Completed {} iterations of RBIG.".format(layer + 1))
# ------------------
# Gaussian(-ization)
# ------------------
layer_params = list()
for idim in range(n_dimensions):
gauss_data[:, idim], params = gaussian_fit_transform(
gauss_data[:, idim],
method=self.method,
params={
"support_extension": self.pdf_extension,
"n_quantiles": self.n_quantiles,
},
)
# gauss_data[:, idim], params = self.univariate_make_normal(
# gauss_data[:, idim], self.pdf_extension, self.pdf_resolution
# )
if self.verbose > 2:
logging.info(
f"Gauss Data (After Marginal): {gauss_data.min()}, {gauss_data.max()}"
)
# append the parameters
layer_params.append(params)
self.gauss_params.append(layer_params)
gauss_data_prerotation = gauss_data.copy()
if self.verbose > 2:
logging.info(
f"Gauss Data (prerotation): {gauss_data.min()}, {gauss_data.max()}"
)
# --------
# Rotation
# --------
if self.rotation_type == "random":
rand_ortho_matrix = ortho_group.rvs(n_dimensions)
gauss_data = np.dot(gauss_data, rand_ortho_matrix)
self.rotation_matrix.append(rand_ortho_matrix)
elif self.rotation_type.lower() == "pca":
# Initialize PCA model
pca_model = PCA(random_state=self.random_state, **self.rotation_kwargs)
logging.debug("Size of gauss_data: {}".format(gauss_data.shape))
gauss_data = pca_model.fit_transform(gauss_data)
self.rotation_matrix.append(pca_model.components_.T)
else:
raise ValueError(
f"Rotation type '{self.rotation_type}' not recognized."
)
# --------------------------------
# Information Reduction
# --------------------------------
self.residual_info.append(
information_reduction(
gauss_data, gauss_data_prerotation, self.tolerance
)
)
# --------------------------------
# Stopping Criteria
# --------------------------------
if self._stopping_criteria(layer):
break
else:
pass
self.residual_info = np.array(self.residual_info)
self.gauss_data = gauss_data
self.mutual_information = np.sum(self.residual_info)
self.n_layers = len(self.gauss_params)
return self
def _stopping_criteria(self, layer):
"""Stopping criteria for the the RBIG algorithm.
Parameter
---------
layer : int
Returns
-------
verdict =
"""
stop_ = False
if layer > self.zero_tolerance:
aux_residual = np.array(self.residual_info)
if np.abs(aux_residual[-self.zero_tolerance :]).sum() == 0:
logging.debug("Done! aux: {}".format(aux_residual))
# delete the last 50 layers for saved parameters
self.rotation_matrix = self.rotation_matrix[:-50]
self.gauss_params = self.gauss_params[:-50]
stop_ = True
else:
stop_ = False
return stop_
def transform(self, X):
"""Complete transformation of X given the learned Gaussianization parameters.
This assumes that the data follows a similar distribution as the data that
was original used to fit the RBIG Gaussian-ization parameters.
Parameters
----------
X : array, (n_samples, n_dimensions)
The data to be transformed (Gaussianized)
Returns
-------
X_transformed : array, (n_samples, n_dimensions)
The new transformed data in the Gaussian domain
"""
X = check_array(X, ensure_2d=True, copy=True)
for igauss, irotation in zip(self.gauss_params, self.rotation_matrix):
# ----------------------------
# Marginal Gaussianization
# ----------------------------
for idim in range(X.shape[1]):
X[:, idim] = gaussian_transform(X[:, idim], igauss[idim])
# ----------------------
# Rotation
# ----------------------
X = np.dot(X, irotation)
return X
def inverse_transform(self, X):
"""Complete transformation of X in the given the learned Gaussianization parameters.
Parameters
----------
X : array, (n_samples, n_dimensions)
The X that follows a Gaussian distribution to be transformed
to data in the original input space.
Returns
-------
X_input_domain : array, (n_samples, n_dimensions)
The new transformed X in the original input space.
"""
X = check_array(X, ensure_2d=True, copy=True)
for igauss, irotation in zip(
self.gauss_params[::-1], self.rotation_matrix[::-1]
):
# ----------------------
# Rotation
# ----------------------
X = np.dot(X, irotation.T)
# ----------------------------
# Marginal Gaussianization
# ----------------------------
for idim in range(X.shape[1]):
X[:, idim] = gaussian_inverse_transform(X[:, idim], igauss[idim])
return X
def _get_information_tolerance(self, n_samples):
"""Precompute some tolerances for the tails."""
xxx = np.logspace(2, 8, 7)
yyy = [0.1571, 0.0468, 0.0145, 0.0046, 0.0014, 0.0001, 0.00001]
return interp1d(xxx, yyy)(n_samples)
def jacobian(self, X: np.ndarray):
"""Calculates the jacobian matrix of the X.
Parameters
----------
X : array, (n_samples, n_features)
The input array to calculate the jacobian using the Gaussianization params.
return_X_transform : bool, default: False
Determines whether to return the transformed Data. This is computed along
with the Jacobian to save time with the iterations
Returns
-------
jacobian : array, (n_samples, n_features, n_features)
The jacobian of the data w.r.t. each component for each direction
X_transformed : array, (n_samples, n_features) (optional)
The transformed data in the Gaussianized space
"""
X = check_array(X, ensure_2d=True, copy=True)
n_samples, n_components = X.shape
X_logdetjacobian = np.zeros((n_samples, n_components, self.n_layers))
for ilayer, (igauss, irotation) in enumerate(
zip(self.gauss_params, self.rotation_matrix)
):
# ----------------------------
# Marginal Gaussianization
# ----------------------------
for idim in range(X.shape[1]):
# marginal gaussian transformation
(
X[:, idim],
X_logdetjacobian[:, idim, ilayer],
) = gaussian_transform_jacobian(X[:, idim], igauss[idim])
# ----------------------
# Rotation
# ----------------------
X = np.dot(X, irotation)
return X, X_logdetjacobian
def log_det_jacobian(self, X: np.ndarray):
"""Calculates the jacobian matrix of the X.
Parameters
----------
X : array, (n_samples, n_features)
The input array to calculate the jacobian using the Gaussianization params.
return_X_transform : bool, default: False
Determines whether to return the transformed Data. This is computed along
with the Jacobian to save time with the iterations
Returns
-------
jacobian : array, (n_samples, n_features, n_features)
The jacobian of the data w.r.t. each component for each direction
X_transformed : array, (n_samples, n_features) (optional)
The transformed data in the Gaussianized space
"""
X = check_array(X, ensure_2d=True, copy=True)
X += 1e-1 * np.random.rand(X.shape[0], X.shape[1])
n_samples, n_components = X.shape
X_logdetjacobian = np.zeros((n_samples, n_components))
X_ldj = np.zeros((n_samples, n_components))
self.jacs_ = list()
self.jacs_sum_ = list()
for ilayer, (igauss, irotation) in enumerate(
zip(self.gauss_params, self.rotation_matrix)
):
# ----------------------------
# Marginal Gaussianization
# ----------------------------
for idim in range(X.shape[1]):
# marginal gaussian transformation
(X[:, idim], X_ldj[:, idim],) = gaussian_transform_jacobian(
X[:, idim], igauss[idim]
)
# print(
# X_logdetjacobian[:, idim].min(),
# X_logdetjacobian[:, idim].max(),
# X_ldj.min(),
# X_ldj.max(),
# )
msg = f"X: {np.min(X[:, idim]):.5f}, {np.max(X[:, idim]):.5f}"
msg += f"\nLayer: {ilayer, idim}"
assert not np.isinf(X_logdetjacobian).any(), msg
# X_ldj = np.clip(X_ldj, -2, 2)
# ----------------------
# Rotation
# ----------------------
X_logdetjacobian += X_ldj.copy()
# X_logdetjacobian = np.clip(X_logdetjacobian, -10, 10)
self.jacs_.append(np.percentile(X_ldj, [0, 5, 10, 50, 90, 95, 100]))
self.jacs_sum_.append(
np.percentile(X_logdetjacobian, [0, 5, 10, 50, 90, 95, 100])
)
X = np.dot(X, irotation)
return X, X_logdetjacobian
def predict_proba(self, X):
""" Computes the probability of the original data under the generative RBIG
model.
Parameters
----------
X : array, (n_samples x n_components)
The points that the pdf is evaluated
n_trials : int, (default : 1)
The number of times that the jacobian is evaluated and averaged
TODO: make sure n_trials is an int
TODO: make sure n_trials is 1 or more
chunksize : int, (default: 2000)
The batchsize to calculate the jacobian matrix.
TODO: make sure chunksize is an int
TODO: make sure chunk size is greater than 0
domain : {'input', 'gauss', 'both'}
The domain to calculate the PDF.
- 'input' : returns the original domain (default)
- 'gauss' : returns the gaussian domain
- 'both' : returns both the input and gauss domain
Returns
-------
prob_data_input_domain : array, (n_samples, 1)
The probability
"""
X = check_array(X, ensure_2d=True, copy=True)
# get transformation and jacobian
Z, X_ldj = self.log_det_jacobian(X)
logging.debug(f"Z: {np.percentile(Z, [0, 5, 50, 95, 100])}")
# calculate the probability
Z_logprob = stats.norm.logpdf(Z)
logging.debug(f"Z_logprob: {np.percentile(Z_logprob, [0, 5, 50, 95, 100])}")
logging.debug(f"X_ldj: {np.percentile(X_ldj, [0, 5, 50, 95, 100])}")
# calculate total probability
X_logprob = (Z_logprob + X_ldj).sum(-1)
logging.debug(f"X_logprob: {np.percentile(X_logprob, [0, 5, 50, 95, 100])}")
X_prob = np.exp(X_logprob)
logging.debug(f"XProb: {np.percentile(X_prob, [0, 5, 50, 95, 100])}")
return X_prob.reshape(-1, 1)
def entropy(self, correction=None):
# TODO check fit
if (correction is None) or (correction is False):
correction = self.entropy_correction
return (
entropy_marginal(self.X_fit_, correction=correction).sum()
- self.mutual_information
)
def total_correlation(self):
# TODO check fit
return self.residual_info.sum()
```
|
{
"source": "jejjohnson/survae_flows_lib",
"score": 3
}
|
#### File: datasets/tabular/bsds300.py
```python
from os import path
from typing import Optional, Tuple
import h5py
import torch
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader, Dataset
import numpy as np
from pathlib import Path
from survae.datasets.tabular.utils import get_data_path
import os
from survae.datasets.tabular.uci_datamodule import UCIDataModule
class BSDS300DataModule(UCIDataModule):
"""
Example of LightningDataModule for MNIST dataset.
A DataModule implements 5 key methods:
- prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)
- setup (things to do on every accelerator in distributed mode)
- train_dataloader (the training dataloader)
- val_dataloader (the validation dataloader(s))
- test_dataloader (the test dataloader(s))
This allows you to share a full dataset without explaining how to download,
split, transform and process the data.
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html
"""
url = "https://zenodo.org/record/1161203/files/data.tar.gz?download=1"
folder = "uci_maf"
download_file = "data.tar.gz"
raw_folder = "uci_maf/data/BSDS300"
raw_file = "BSDS300.hdf5"
# data statistics
num_features = 63
num_train = 1_000_000
num_valid = 50_000
num_test = 250_000
def __init__(
self,
data_dir: str = get_data_path(),
batch_size: int = 64,
num_workers: int = 0,
pin_memory: bool = False,
download_data: bool = True,
):
super().__init__(data_dir=data_dir, download_data=download_data)
self.batch_size = batch_size
self.num_workers = num_workers
self.pin_memory = pin_memory
self.transforms = None
self.data_train: Optional[Dataset] = None
self.data_val: Optional[Dataset] = None
self.data_test: Optional[Dataset] = None
def setup(self, stage: Optional[str] = None):
def load_data(split):
# Taken from https://github.com/bayesiains/nsf/blob/master/data/bsds300.py
file = h5py.File(self.raw_data_path, "r")
return np.array(file[split]).astype(np.float32)
if self.data_train is None or self.data_val is None or self.data_test is None:
data_train, data_val, data_test = (
load_data("train"),
load_data("validation"),
load_data("test"),
)
self.data_train = data_train # Dataset(data_train)
self.data_val = data_val # Dataset(data_val)
self.data_test = data_test # Dataset(data_test)
assert data_train.shape == (self.num_train, self.num_features)
assert data_val.shape == (self.num_valid, self.num_features)
assert data_test.shape == (self.num_test, self.num_features)
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
This method is called by lightning separately when using `trainer.fit()` and `trainer.test()`!
The `stage` can be used to differentiate whether the `setup()` is called before trainer.fit()` or `trainer.test()`."""
def train_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_train),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=True,
)
def val_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_val),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=False,
)
def test_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_test),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=False,
)
```
#### File: datasets/tabular/hepmass.py
```python
from os import path
from typing import Optional, Tuple
import torch
from pytorch_lightning import LightningDataModule
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
from torchvision.datasets import MNIST
from torchvision.transforms import transforms
import numpy as np
import pandas as pd
from pathlib import Path
from .utils import get_data_path
import os
from collections import Counter
from survae.datasets.tabular.uci_datamodule import UCIDataModule
class HEPMASSDataModule(UCIDataModule):
"""
Example of LightningDataModule for MNIST dataset.
A DataModule implements 5 key methods:
- prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)
- setup (things to do on every accelerator in distributed mode)
- train_dataloader (the training dataloader)
- val_dataloader (the validation dataloader(s))
- test_dataloader (the test dataloader(s))
This allows you to share a full dataset without explaining how to download,
split, transform and process the data.
Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html
"""
url = "https://zenodo.org/record/1161203/files/data.tar.gz?download=1"
folder = "uci_maf"
download_file = "data.tar.gz"
raw_folder = "uci_maf/data/hepmass"
raw_file = ""
num_features = 21
num_train = 315_123
num_valid = 35_013
num_test = 174_987
def __init__(
self,
data_dir: str = get_data_path(),
batch_size: int = 64,
num_workers: int = 0,
pin_memory: bool = False,
download_data: bool = True,
):
super().__init__(data_dir=data_dir, download_data=download_data)
self.batch_size = batch_size
self.num_workers = num_workers
self.pin_memory = pin_memory
self.transforms = None
# self.dims is returned when you call datamodule.size()
# self.dims is returned when you call datamodule.size()
self.data_train: Optional[Dataset] = None
self.data_val: Optional[Dataset] = None
self.data_test: Optional[Dataset] = None
def setup(self, stage: Optional[str] = None):
def load_data(path):
data_train = pd.read_csv(
filepath_or_buffer=os.path.join(path, "1000_train.csv"), index_col=False
)
data_test = pd.read_csv(
filepath_or_buffer=os.path.join(path, "1000_test.csv"), index_col=False
)
return data_train, data_test
def load_data_no_discrete(path):
"""Loads the positive class examples from the first 10% of the dataset."""
data_train, data_test = load_data(path)
# Gets rid of any background noise examples i.e. class label 0.
data_train = data_train[data_train[data_train.columns[0]] == 1]
data_train = data_train.drop(data_train.columns[0], axis=1)
data_test = data_test[data_test[data_test.columns[0]] == 1]
data_test = data_test.drop(data_test.columns[0], axis=1)
# Because the data_ set is messed up!
data_test = data_test.drop(data_test.columns[-1], axis=1)
return data_train, data_test
def load_data_no_discrete_normalised(path):
data_train, data_test = load_data_no_discrete(path)
mu = data_train.mean()
s = data_train.std()
data_train = (data_train - mu) / s
data_test = (data_test - mu) / s
return data_train, data_test
def load_data_no_discrete_normalised_as_array(path):
data_train, data_test = load_data_no_discrete_normalised(path)
data_train, data_test = data_train.values, data_test.values
i = 0
# Remove any features that have too many re-occurring real values.
features_to_remove = []
for feature in data_train.T:
c = Counter(feature)
max_count = np.array([v for k, v in sorted(c.items())])[0]
if max_count > 5:
features_to_remove.append(i)
i += 1
data_train = data_train[
:,
np.array(
[
i
for i in range(data_train.shape[1])
if i not in features_to_remove
]
),
]
data_test = data_test[
:,
np.array(
[
i
for i in range(data_test.shape[1])
if i not in features_to_remove
]
),
]
N = data_train.shape[0]
N_validate = int(N * 0.1)
data_validate = data_train[-N_validate:]
data_train = data_train[0:-N_validate]
return data_train, data_validate, data_test
if self.data_train is None or self.data_val is None or self.data_test is None:
data_train, data_val, data_test = load_data_no_discrete_normalised_as_array(
self.raw_data_path
)
self.data_train = data_train # Dataset(data_train)
self.data_val = data_val # Dataset(data_val)
self.data_test = data_test # Dataset(data_test)
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
This method is called by lightning separately when using `trainer.fit()` and `trainer.test()`!
The `stage` can be used to differentiate whether the `setup()` is called before trainer.fit()` or `trainer.test()`."""
def train_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_train),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=True,
)
def val_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_val),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=False,
)
def test_dataloader(self):
return DataLoader(
dataset=torch.FloatTensor(self.data_test),
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
shuffle=False,
)
```
#### File: datasets/tabular/utils.py
```python
from pyprojroot import here
from pathlib import Path
# spyder up to find the root
# root = here(project_files=[""])
import os
import importlib
def get_survae_path():
init_path = importlib.util.find_spec("survae").origin
path = os.path.dirname(os.path.dirname(init_path))
return path
# def get_data_path_file():
# path = get_survae_path()
# file = os.path.join(path, 'data_path')
# return file
DATA_PATH = Path(get_survae_path()).joinpath("data")
# makedir
DATA_PATH.mkdir(parents=True, exist_ok=True)
def get_data_path():
return str(DATA_PATH)
```
|
{
"source": "J-E-J-S/aaRS-Pipeline",
"score": 2
}
|
#### File: aaRS-Pipeline/bin/queryResults.py
```python
import json
import os
import sys
from shutil import copyfile
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.Polypeptide import PPBuilder
mutantQn = int(sys.argv[1])
rmsdCutOff = float(sys.argv[2])
resultsJSON = sys.argv[3]
def outputDir(mutantQn, rmsdCutOff, resultsJSON):
'''Filters mutants based on an RMSD cut off and compiled a results directory '''
filteredMutants = {} # Results dictionary filtered on RMSD cut-off
with open(resultsJSON) as json_file:
data = json.load(json_file)
# Filter by RMSD cut-off value
for mutant in data:
if data[mutant]['RMSD'][0] <= rmsdCutOff:
filteredMutants[mutant] = data[mutant]
# Rank mutants based on delta values
deltaDic = {}
for mutant in filteredMutants:
deltaDic[mutant] = filteredMutants[mutant]['Delta'][0]
rankedMutants = sorted(deltaDic, reverse=True) # lower delta = better
outputFolder = './../output/' + str(mutantQn) + '_rankedResults'
os.mkdir(outputFolder)
if len(rankedMutants) < mutantQn:
mutantQn = len(rankedMutants) # To stay in index range in event of few mutants
count = 0
while count < mutantQn:
mutantDir = outputFolder + '/' + str(count+1)
os.mkdir(mutantDir)
structurePath = filteredMutants[rankedMutants[count]]['structurePath']
dockingPath = filteredMutants[rankedMutants[count]]['dockingPath']
copyfile(structurePath, mutantDir + '/' + rankedMutants[count] + '.pdb')
copyfile(dockingPath, mutantDir + '/' + rankedMutants[count] + '_docking.mol2')
f = open(mutantDir + '/' + rankedMutants[count] + '.fasta', 'a+')
f.write('>' + rankedMutants[count] + ' | rank=' + str(count+1) + ' | delta=' + str(filteredMutants[rankedMutants[count]]['Delta'][0]) + ' kcal/mol | dockScore=' + str(filteredMutants[rankedMutants[count]]['exogenousScores'][0]) + ' kcal/mol' + ' | RMSD=' + str(filteredMutants[rankedMutants[count]]['RMSD'][0]) + ' Å\n' )
structure = PDBParser().get_structure('mutant', structurePath)
ppb = PPBuilder()
seq = [] # If dimers then only 1 included (1 polypeptide)
for pp in ppb.build_peptides(structure):
seq.append(str(pp.get_sequence()))
f.write(seq[0] + '\n')
f.close()
count += 1
return outputFolder
def createSummaryFasta(outputFolder):
''' Collates all the fasta files into one '''
f = open(outputFolder + '/rankedResults.fasta', 'a+')
for root, dirs, files in os.walk(outputFolder):
for file in files:
if file.endswith('.fasta'):
mutantFile = open(os.path.join(root, file), 'r')
f.write(mutantFile.read())
mutantFile.close()
f.close()
def main():
outputFolder = outputDir(mutantQn, rmsdCutOff, resultsJSON)
createSummaryFasta(outputFolder)
main()
```
#### File: Crypto/PublicKey/pubkey.py
```python
__revision__ = "$Id$"
import types, warnings
from Crypto.Util.number import *
# Basic public key class
class pubkey:
def __init__(self):
pass
def __getstate__(self):
"""To keep key objects platform-independent, the key data is
converted to standard Python long integers before being
written out. It will then be reconverted as necessary on
restoration."""
d=self.__dict__
for key in self.keydata:
if d.has_key(key): d[key]=long(d[key])
return d
def __setstate__(self, d):
"""On unpickling a key object, the key data is converted to the big
number representation being used, whether that is Python long
integers, MPZ objects, or whatever."""
for key in self.keydata:
if d.has_key(key): self.__dict__[key]=bignum(d[key])
def encrypt(self, plaintext, K):
"""encrypt(plaintext:string|long, K:string|long) : tuple
Encrypt the string or integer plaintext. K is a random
parameter required by some algorithms.
"""
wasString=0
if isinstance(plaintext, types.StringType):
plaintext=bytes_to_long(plaintext) ; wasString=1
if isinstance(K, types.StringType):
K=bytes_to_long(K)
ciphertext=self._encrypt(plaintext, K)
if wasString: return tuple(map(long_to_bytes, ciphertext))
else: return ciphertext
def decrypt(self, ciphertext):
"""decrypt(ciphertext:tuple|string|long): string
Decrypt 'ciphertext' using this key.
"""
wasString=0
if not isinstance(ciphertext, types.TupleType):
ciphertext=(ciphertext,)
if isinstance(ciphertext[0], types.StringType):
ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
plaintext=self._decrypt(ciphertext)
if wasString: return long_to_bytes(plaintext)
else: return plaintext
def sign(self, M, K):
"""sign(M : string|long, K:string|long) : tuple
Return a tuple containing the signature for the message M.
K is a random parameter required by some algorithms.
"""
if (not self.has_private()):
raise TypeError('Private key not available in this object')
if isinstance(M, types.StringType): M=bytes_to_long(M)
if isinstance(K, types.StringType): K=bytes_to_long(K)
return self._sign(M, K)
def verify (self, M, signature):
"""verify(M:string|long, signature:tuple) : bool
Verify that the signature is valid for the message M;
returns true if the signature checks out.
"""
if isinstance(M, types.StringType): M=bytes_to_long(M)
return self._verify(M, signature)
# alias to compensate for the old validate() name
def validate (self, M, signature):
warnings.warn("validate() method name is obsolete; use verify()",
DeprecationWarning)
def blind(self, M, B):
"""blind(M : string|long, B : string|long) : string|long
Blind message M using blinding factor B.
"""
wasString=0
if isinstance(M, types.StringType):
M=bytes_to_long(M) ; wasString=1
if isinstance(B, types.StringType): B=bytes_to_long(B)
blindedmessage=self._blind(M, B)
if wasString: return long_to_bytes(blindedmessage)
else: return blindedmessage
def unblind(self, M, B):
"""unblind(M : string|long, B : string|long) : string|long
Unblind message M using blinding factor B.
"""
wasString=0
if isinstance(M, types.StringType):
M=bytes_to_long(M) ; wasString=1
if isinstance(B, types.StringType): B=bytes_to_long(B)
unblindedmessage=self._unblind(M, B)
if wasString: return long_to_bytes(unblindedmessage)
else: return unblindedmessage
# The following methods will usually be left alone, except for
# signature-only algorithms. They both return Boolean values
# recording whether this key's algorithm can sign and encrypt.
def can_sign (self):
"""can_sign() : bool
Return a Boolean value recording whether this algorithm can
generate signatures. (This does not imply that this
particular key object has the private information required to
to generate a signature.)
"""
return 1
def can_encrypt (self):
"""can_encrypt() : bool
Return a Boolean value recording whether this algorithm can
encrypt data. (This does not imply that this
particular key object has the private information required to
to decrypt a message.)
"""
return 1
def can_blind (self):
"""can_blind() : bool
Return a Boolean value recording whether this algorithm can
blind data. (This does not imply that this
particular key object has the private information required to
to blind a message.)
"""
return 0
# The following methods will certainly be overridden by
# subclasses.
def size (self):
"""size() : int
Return the maximum number of bits that can be handled by this key.
"""
return 0
def has_private (self):
"""has_private() : bool
Return a Boolean denoting whether the object contains
private components.
"""
return 0
def publickey (self):
"""publickey(): object
Return a new key object containing only the public information.
"""
return self
def __eq__ (self, other):
"""__eq__(other): 0, 1
Compare us to other for equality.
"""
return self.__getstate__() == other.__getstate__()
def __ne__ (self, other):
"""__ne__(other): 0, 1
Compare us to other for inequality.
"""
return not self.__eq__(other)
```
#### File: matplotlib/backends/backend_mixed.py
```python
from matplotlib._image import frombuffer
from matplotlib.backends.backend_agg import RendererAgg
class MixedModeRenderer(object):
"""
A helper class to implement a renderer that switches between
vector and raster drawing. An example may be a PDF writer, where
most things are drawn with PDF vector commands, but some very
complex objects, such as quad meshes, are rasterised and then
output as images.
"""
def __init__(self, width, height, dpi, vector_renderer, raster_renderer_class=None):
"""
width: The width of the canvas in logical units
height: The height of the canvas in logical units
dpi: The dpi of the canvas
vector_renderer: An instance of a subclass of RendererBase
that will be used for the vector drawing.
raster_renderer_class: The renderer class to use for the
raster drawing. If not provided, this will use the Agg
backend (which is currently the only viable option anyway.)
"""
if raster_renderer_class is None:
raster_renderer_class = RendererAgg
self._raster_renderer_class = raster_renderer_class
self._width = width
self._height = height
self.dpi = dpi
assert not vector_renderer.option_image_nocomposite()
self._vector_renderer = vector_renderer
self._raster_renderer = None
self._rasterizing = 0
self._set_current_renderer(vector_renderer)
_methods = """
close_group draw_image draw_markers draw_path
draw_path_collection draw_quad_mesh draw_tex draw_text
finalize flipy get_canvas_width_height get_image_magnification
get_texmanager get_text_width_height_descent new_gc open_group
option_image_nocomposite points_to_pixels strip_math
""".split()
def _set_current_renderer(self, renderer):
self._renderer = renderer
for method in self._methods:
if hasattr(renderer, method):
setattr(self, method, getattr(renderer, method))
renderer.start_rasterizing = self.start_rasterizing
renderer.stop_rasterizing = self.stop_rasterizing
def start_rasterizing(self):
"""
Enter "raster" mode. All subsequent drawing commands (until
stop_rasterizing is called) will be drawn with the raster
backend.
If start_rasterizing is called multiple times before
stop_rasterizing is called, this method has no effect.
"""
if self._rasterizing == 0:
self._raster_renderer = self._raster_renderer_class(
self._width*self.dpi, self._height*self.dpi, self.dpi)
self._set_current_renderer(self._raster_renderer)
self._rasterizing += 1
def stop_rasterizing(self):
"""
Exit "raster" mode. All of the drawing that was done since
the last start_rasterizing command will be copied to the
vector backend by calling draw_image.
If stop_rasterizing is called multiple times before
start_rasterizing is called, this method has no effect.
"""
self._rasterizing -= 1
if self._rasterizing == 0:
self._set_current_renderer(self._vector_renderer)
width, height = self._width * self.dpi, self._height * self.dpi
buffer, bounds = self._raster_renderer.tostring_rgba_minimized()
l, b, w, h = bounds
if w > 0 and h > 0:
image = frombuffer(buffer, w, h, True)
image.is_grayscale = False
image.flipud_out()
self._renderer.draw_image(l, height - b - h, image, None)
self._raster_renderer = None
self._rasterizing = False
```
#### File: site-packages/matplotlib/path.py
```python
import math
from weakref import WeakValueDictionary
import numpy as np
from numpy import ma
from matplotlib._path import point_in_path, get_path_extents, \
point_in_path_collection, get_path_collection_extents, \
path_in_path, path_intersects_path, convert_path_to_polygons
from matplotlib.cbook import simple_linear_interpolation
class Path(object):
"""
Path represents a series of possibly disconnected, possibly
closed, line and curve segments.
The underlying storage is made up of two parallel numpy arrays:
- *vertices*: an Nx2 float array of vertices
- *codes*: an N-length uint8 array of vertex types
These two arrays always have the same length in the first
dimension. For example, to represent a cubic curve, you must
provide three vertices as well as three codes ``CURVE3``.
The code types are:
- ``STOP`` : 1 vertex (ignored)
A marker for the end of the entire path (currently not
required and ignored)
- ``MOVETO`` : 1 vertex
Pick up the pen and move to the given vertex.
- ``LINETO`` : 1 vertex
Draw a line from the current position to the given vertex.
- ``CURVE3`` : 1 control point, 1 endpoint
Draw a quadratic Bezier curve from the current position,
with the given control point, to the given end point.
- ``CURVE4`` : 2 control points, 1 endpoint
Draw a cubic Bezier curve from the current position, with
the given control points, to the given end point.
- ``CLOSEPOLY`` : 1 vertex (ignored)
Draw a line segment to the start point of the current
polyline.
Users of Path objects should not access the vertices and codes
arrays directly. Instead, they should use :meth:`iter_segments`
to get the vertex/code pairs. This is important, since many
:class:`Path` objects, as an optimization, do not store a *codes*
at all, but have a default one provided for them by
:meth:`iter_segments`.
"""
# Path codes
STOP = 0 # 1 vertex
MOVETO = 1 # 1 vertex
LINETO = 2 # 1 vertex
CURVE3 = 3 # 2 vertices
CURVE4 = 4 # 3 vertices
CLOSEPOLY = 5 # 1 vertex
NUM_VERTICES = [1, 1, 1, 2, 3, 1]
code_type = np.uint8
def __init__(self, vertices, codes=None):
"""
Create a new path with the given vertices and codes.
*vertices* is an Nx2 numpy float array, masked array or Python
sequence.
*codes* is an N-length numpy array or Python sequence of type
:attr:`matplotlib.path.Path.code_type`.
These two arrays must have the same length in the first
dimension.
If *codes* is None, *vertices* will be treated as a series of
line segments. If *vertices* contains masked values, the
resulting path will be compressed, with ``MOVETO`` codes
inserted in the correct places to jump over the masked
regions.
"""
if ma.isMaskedArray(vertices):
is_mask = True
mask = ma.getmask(vertices)
else:
is_mask = False
vertices = np.asarray(vertices, np.float_)
mask = ma.nomask
if codes is not None:
codes = np.asarray(codes, self.code_type)
assert codes.ndim == 1
assert len(codes) == len(vertices)
# The path being passed in may have masked values. However,
# the backends (and any affine transformations in matplotlib
# itself), are not expected to deal with masked arrays, so we
# must remove them from the array (using compressed), and add
# MOVETO commands to the codes array accordingly.
if is_mask:
if mask is not ma.nomask:
mask1d = np.logical_or.reduce(mask, axis=1)
gmask1d = np.invert(mask1d)
if codes is None:
codes = np.empty((len(vertices)), self.code_type)
codes.fill(self.LINETO)
codes[0] = self.MOVETO
vertices = vertices[gmask1d].filled() # ndarray
codes[np.roll(mask1d, 1)] = self.MOVETO
codes = codes[gmask1d] # np.compress is much slower
else:
vertices = np.asarray(vertices, np.float_)
assert vertices.ndim == 2
assert vertices.shape[1] == 2
self.codes = codes
self.vertices = vertices
#@staticmethod
def make_compound_path(*args):
"""
(staticmethod) Make a compound path from a list of Path
objects. Only polygons (not curves) are supported.
"""
for p in args:
assert p.codes is None
lengths = [len(x) for x in args]
total_length = sum(lengths)
vertices = np.vstack([x.vertices for x in args])
vertices.reshape((total_length, 2))
codes = Path.LINETO * np.ones(total_length)
i = 0
for length in lengths:
codes[i] = Path.MOVETO
i += length
return Path(vertices, codes)
make_compound_path = staticmethod(make_compound_path)
def __repr__(self):
return "Path(%s, %s)" % (self.vertices, self.codes)
def __len__(self):
return len(self.vertices)
def iter_segments(self):
"""
Iterates over all of the curve segments in the path. Each
iteration returns a 2-tuple (*vertices*, *code*), where
*vertices* is a sequence of 1 - 3 coordinate pairs, and *code* is
one of the :class:`Path` codes.
"""
vertices = self.vertices
if not len(vertices):
return
codes = self.codes
len_vertices = len(vertices)
isnan = np.isnan
any = np.any
NUM_VERTICES = self.NUM_VERTICES
MOVETO = self.MOVETO
LINETO = self.LINETO
CLOSEPOLY = self.CLOSEPOLY
STOP = self.STOP
if codes is None:
next_code = MOVETO
for v in vertices:
if any(isnan(v)):
next_code = MOVETO
else:
yield v, next_code
next_code = LINETO
else:
i = 0
was_nan = False
while i < len_vertices:
code = codes[i]
if code == CLOSEPOLY:
yield [], code
i += 1
elif code == STOP:
return
else:
num_vertices = NUM_VERTICES[int(code)]
curr_vertices = vertices[i:i+num_vertices].flatten()
if any(isnan(curr_vertices)):
was_nan = True
elif was_nan:
yield curr_vertices[-2:], MOVETO
was_nan = False
else:
yield curr_vertices, code
i += num_vertices
def transformed(self, transform):
"""
Return a transformed copy of the path.
See :class:`matplotlib.transforms.TransformedPath` for a path
that will cache the transformed result and automatically
update when the transform changes.
"""
return Path(transform.transform(self.vertices), self.codes)
def contains_point(self, point, transform=None):
"""
Returns *True* if the path contains the given point.
If *transform* is not *None*, the path will be transformed
before performing the test.
"""
if transform is not None:
transform = transform.frozen()
return point_in_path(point[0], point[1], self, transform)
def contains_path(self, path, transform=None):
"""
Returns *True* if this path completely contains the given path.
If *transform* is not *None*, the path will be transformed
before performing the test.
"""
if transform is not None:
transform = transform.frozen()
return path_in_path(self, None, path, transform)
def get_extents(self, transform=None):
"""
Returns the extents (*xmin*, *ymin*, *xmax*, *ymax*) of the
path.
Unlike computing the extents on the *vertices* alone, this
algorithm will take into account the curves and deal with
control points appropriately.
"""
from transforms import Bbox
if transform is not None:
transform = transform.frozen()
return Bbox(get_path_extents(self, transform))
def intersects_path(self, other):
"""
Returns *True* if this path intersects another given path.
"""
return path_intersects_path(self, other)
def intersects_bbox(self, bbox):
"""
Returns *True* if this path intersects a given
:class:`~matplotlib.transforms.Bbox`.
"""
from transforms import BboxTransformTo
rectangle = self.unit_rectangle().transformed(
BboxTransformTo(bbox))
result = self.intersects_path(rectangle)
return result
def interpolated(self, steps):
"""
Returns a new path resampled to length N x steps. Does not
currently handle interpolating curves.
"""
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = Path.LINETO * np.ones(((len(codes) - 1) * steps + 1, ))
new_codes[0::steps] = codes
else:
new_codes = None
return Path(vertices, new_codes)
def to_polygons(self, transform=None, width=0, height=0):
"""
Convert this path to a list of polygons. Each polygon is an
Nx2 array of vertices. In other words, each polygon has no
``MOVETO`` instructions or curves. This is useful for
displaying in backends that do not support compound paths or
Bezier curves, such as GDK.
If *width* and *height* are both non-zero then the lines will
be simplified so that vertices outside of (0, 0), (width,
height) will be clipped.
"""
if len(self.vertices) == 0:
return []
if transform is not None:
transform = transform.frozen()
if self.codes is None and (width == 0 or height == 0):
if transform is None:
return [self.vertices]
else:
return [transform.transform(self.vertices)]
# Deal with the case where there are curves and/or multiple
# subpaths (using extension code)
return convert_path_to_polygons(self, transform, width, height)
_unit_rectangle = None
#@classmethod
def unit_rectangle(cls):
"""
(staticmethod) Returns a :class:`Path` of the unit rectangle
from (0, 0) to (1, 1).
"""
if cls._unit_rectangle is None:
cls._unit_rectangle = \
Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]])
return cls._unit_rectangle
unit_rectangle = classmethod(unit_rectangle)
_unit_regular_polygons = WeakValueDictionary()
#@classmethod
def unit_regular_polygon(cls, numVertices):
"""
(staticmethod) Returns a :class:`Path` for a unit regular
polygon with the given *numVertices* and radius of 1.0,
centered at (0, 0).
"""
if numVertices <= 16:
path = cls._unit_regular_polygons.get(numVertices)
else:
path = None
if path is None:
theta = (2*np.pi/numVertices *
np.arange(numVertices + 1).reshape((numVertices + 1, 1)))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
verts = np.concatenate((np.cos(theta), np.sin(theta)), 1)
path = Path(verts)
cls._unit_regular_polygons[numVertices] = path
return path
unit_regular_polygon = classmethod(unit_regular_polygon)
_unit_regular_stars = WeakValueDictionary()
#@classmethod
def unit_regular_star(cls, numVertices, innerCircle=0.5):
"""
(staticmethod) Returns a :class:`Path` for a unit regular star
with the given numVertices and radius of 1.0, centered at (0,
0).
"""
if numVertices <= 16:
path = cls._unit_regular_stars.get((numVertices, innerCircle))
else:
path = None
if path is None:
ns2 = numVertices * 2
theta = (2*np.pi/ns2 * np.arange(ns2 + 1))
# This initial rotation is to make sure the polygon always
# "points-up"
theta += np.pi / 2.0
r = np.ones(ns2 + 1)
r[1::2] = innerCircle
verts = np.vstack((r*np.cos(theta), r*np.sin(theta))).transpose()
path = Path(verts)
cls._unit_regular_polygons[(numVertices, innerCircle)] = path
return path
unit_regular_star = classmethod(unit_regular_star)
#@classmethod
def unit_regular_asterisk(cls, numVertices):
"""
(staticmethod) Returns a :class:`Path` for a unit regular
asterisk with the given numVertices and radius of 1.0,
centered at (0, 0).
"""
return cls.unit_regular_star(numVertices, 0.0)
unit_regular_asterisk = classmethod(unit_regular_asterisk)
_unit_circle = None
#@classmethod
def unit_circle(cls):
"""
(staticmethod) Returns a :class:`Path` of the unit circle.
The circle is approximated using cubic Bezier curves. This
uses 8 splines around the circle using the approach presented
here:
<NAME>. `Approximating a Circle or an Ellipse Using Four
Bezier Cubic Splines <http://www.tinaja.com/glib/ellipse4.pdf>`_.
"""
if cls._unit_circle is None:
MAGIC = 0.2652031
SQRTHALF = np.sqrt(0.5)
MAGIC45 = np.sqrt((MAGIC*MAGIC) / 2.0)
vertices = np.array(
[[0.0, -1.0],
[MAGIC, -1.0],
[SQRTHALF-MAGIC45, -SQRTHALF-MAGIC45],
[SQRTHALF, -SQRTHALF],
[SQRTHALF+MAGIC45, -SQRTHALF+MAGIC45],
[1.0, -MAGIC],
[1.0, 0.0],
[1.0, MAGIC],
[SQRTHALF+MAGIC45, SQRTHALF-MAGIC45],
[SQRTHALF, SQRTHALF],
[SQRTHALF-MAGIC45, SQRTHALF+MAGIC45],
[MAGIC, 1.0],
[0.0, 1.0],
[-MAGIC, 1.0],
[-SQRTHALF+MAGIC45, SQRTHALF+MAGIC45],
[-SQRTHALF, SQRTHALF],
[-SQRTHALF-MAGIC45, SQRTHALF-MAGIC45],
[-1.0, MAGIC],
[-1.0, 0.0],
[-1.0, -MAGIC],
[-SQRTHALF-MAGIC45, -SQRTHALF+MAGIC45],
[-SQRTHALF, -SQRTHALF],
[-SQRTHALF+MAGIC45, -SQRTHALF-MAGIC45],
[-MAGIC, -1.0],
[0.0, -1.0],
[0.0, -1.0]],
np.float_)
codes = cls.CURVE4 * np.ones(26)
codes[0] = cls.MOVETO
codes[-1] = cls.CLOSEPOLY
cls._unit_circle = Path(vertices, codes)
return cls._unit_circle
unit_circle = classmethod(unit_circle)
#@classmethod
def arc(cls, theta1, theta2, n=None, is_wedge=False):
"""
(staticmethod) Returns an arc on the unit circle from angle
*theta1* to angle *theta2* (in degrees).
If *n* is provided, it is the number of spline segments to make.
If *n* is not provided, the number of spline segments is
determined based on the delta between *theta1* and *theta2*.
<NAME>. 2003. `Drawing an elliptical arc using
polylines, quadratic or cubic Bezier curves
<http://www.spaceroots.org/documents/ellipse/index.html>`_.
"""
# degrees to radians
theta1 *= np.pi / 180.0
theta2 *= np.pi / 180.0
twopi = np.pi * 2.0
halfpi = np.pi * 0.5
eta1 = np.arctan2(np.sin(theta1), np.cos(theta1))
eta2 = np.arctan2(np.sin(theta2), np.cos(theta2))
eta2 -= twopi * np.floor((eta2 - eta1) / twopi)
if (theta2 - theta1 > np.pi) and (eta2 - eta1 < np.pi):
eta2 += twopi
# number of curve segments to make
if n is None:
n = int(2 ** np.ceil((eta2 - eta1) / halfpi))
if n < 1:
raise ValueError("n must be >= 1 or None")
deta = (eta2 - eta1) / n
t = np.tan(0.5 * deta)
alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0
steps = np.linspace(eta1, eta2, n + 1, True)
cos_eta = np.cos(steps)
sin_eta = np.sin(steps)
xA = cos_eta[:-1]
yA = sin_eta[:-1]
xA_dot = -yA
yA_dot = xA
xB = cos_eta[1:]
yB = sin_eta[1:]
xB_dot = -yB
yB_dot = xB
if is_wedge:
length = n * 3 + 4
vertices = np.zeros((length, 2), np.float_)
codes = Path.CURVE4 * np.ones((length, ), Path.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [Path.MOVETO, Path.LINETO]
codes[-2:] = [Path.LINETO, Path.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.zeros((length, 2), np.float_)
codes = Path.CURVE4 * np.ones((length, ), Path.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = Path.MOVETO
vertex_offset = 1
end = length
vertices[vertex_offset :end:3, 0] = xA + alpha * xA_dot
vertices[vertex_offset :end:3, 1] = yA + alpha * yA_dot
vertices[vertex_offset+1:end:3, 0] = xB - alpha * xB_dot
vertices[vertex_offset+1:end:3, 1] = yB - alpha * yB_dot
vertices[vertex_offset+2:end:3, 0] = xB
vertices[vertex_offset+2:end:3, 1] = yB
return Path(vertices, codes)
arc = classmethod(arc)
#@classmethod
def wedge(cls, theta1, theta2, n=None):
"""
(staticmethod) Returns a wedge of the unit circle from angle
*theta1* to angle *theta2* (in degrees).
If *n* is provided, it is the number of spline segments to make.
If *n* is not provided, the number of spline segments is
determined based on the delta between *theta1* and *theta2*.
"""
return cls.arc(theta1, theta2, n, True)
wedge = classmethod(wedge)
_get_path_collection_extents = get_path_collection_extents
def get_path_collection_extents(*args):
"""
Given a sequence of :class:`Path` objects, returns the bounding
box that encapsulates all of them.
"""
from transforms import Bbox
if len(args[1]) == 0:
raise ValueError("No paths provided")
return Bbox.from_extents(*_get_path_collection_extents(*args))
```
#### File: site-packages/matplotlib/_pylab_helpers.py
```python
import sys, gc
def error_msg(msg):
print >>sys.stderr, msgs
class Gcf(object):
_activeQue = []
figs = {}
def get_fig_manager(num):
figManager = Gcf.figs.get(num, None)
if figManager is not None: Gcf.set_active(figManager)
return figManager
get_fig_manager = staticmethod(get_fig_manager)
def destroy(num):
if not Gcf.has_fignum(num): return
figManager = Gcf.figs[num]
oldQue = Gcf._activeQue[:]
Gcf._activeQue = []
for f in oldQue:
if f != figManager: Gcf._activeQue.append(f)
del Gcf.figs[num]
#print len(Gcf.figs.keys()), len(Gcf._activeQue)
figManager.destroy()
gc.collect()
destroy = staticmethod(destroy)
def has_fignum(num):
return Gcf.figs.has_key(num)
has_fignum = staticmethod(has_fignum)
def get_all_fig_managers():
return Gcf.figs.values()
get_all_fig_managers = staticmethod(get_all_fig_managers)
def get_num_fig_managers():
return len(Gcf.figs.values())
get_num_fig_managers = staticmethod(get_num_fig_managers)
def get_active():
if len(Gcf._activeQue)==0:
return None
else: return Gcf._activeQue[-1]
get_active = staticmethod(get_active)
def set_active(manager):
oldQue = Gcf._activeQue[:]
Gcf._activeQue = []
for m in oldQue:
if m != manager: Gcf._activeQue.append(m)
Gcf._activeQue.append(manager)
Gcf.figs[manager.num] = manager
set_active = staticmethod(set_active)
```
#### File: site-packages/matplotlib/type1font.py
```python
import struct
class Type1Font(object):
def __init__(self, filename):
file = open(filename, 'rb')
try:
data = self._read(file)
finally:
file.close()
self.parts = self._split(data)
def _read(self, file):
rawdata = file.read()
if not rawdata.startswith(chr(128)):
return rawdata
data = ''
while len(rawdata) > 0:
if not rawdata.startswith(chr(128)):
raise RuntimeError, \
'Broken pfb file (expected byte 128, got %d)' % \
ord(rawdata[0])
type = ord(rawdata[1])
if type in (1,2):
length, = struct.unpack('<i', rawdata[2:6])
segment = rawdata[6:6+length]
rawdata = rawdata[6+length:]
if type == 1: # ASCII text: include verbatim
data += segment
elif type == 2: # binary data: encode in hexadecimal
data += ''.join(['%02x' % ord(char)
for char in segment])
elif type == 3: # end of file
break
else:
raise RuntimeError, \
'Unknown segment type %d in pfb file' % type
return data
def _split(self, data):
"""
Split the Type 1 font into its three main parts.
The three parts are: (1) the cleartext part, which ends in a
eexec operator; (2) the encrypted part; (3) the fixed part,
which contains 512 ASCII zeros possibly divided on various
lines, a cleartomark operator, and possibly something else.
"""
# Cleartext part: just find the eexec and skip whitespace
idx = data.index('eexec')
idx += len('eexec')
while data[idx] in ' \t\r\n':
idx += 1
len1 = idx
# Encrypted part: find the cleartomark operator and count
# zeros backward
idx = data.rindex('cleartomark') - 1
zeros = 512
while zeros and data[idx] in ('0', '\n', '\r'):
if data[idx] == '0':
zeros -= 1
idx -= 1
if zeros:
raise RuntimeError, 'Insufficiently many zeros in Type 1 font'
# Convert encrypted part to binary (if we read a pfb file, we
# may end up converting binary to hexadecimal to binary again;
# but if we read a pfa file, this part is already in hex, and
# I am not quite sure if even the pfb format guarantees that
# it will be in binary).
binary = ''.join([chr(int(data[i:i+2], 16))
for i in range(len1, idx, 2)])
return data[:len1], binary, data[idx:]
if __name__ == '__main__':
import sys
font = Type1Font(sys.argv[1])
parts = font.parts
print len(parts[0]), len(parts[1]), len(parts[2])
```
#### File: numpy/core/__init__.py
```python
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import defchararray as char
import records as rec
from records import *
from memmap import *
from defchararray import *
import scalarmath
del nt
from fromnumeric import amax as max, amin as min, \
round_ as round
from numeric import absolute as abs
__all__ = ['char','rec','memmap']
__all__ += numeric.__all__
__all__ += fromnumeric.__all__
__all__ += defmatrix.__all__
__all__ += rec.__all__
__all__ += char.__all__
def test(level=1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
```
#### File: numpy/core/memmap.py
```python
__all__ = ['memmap']
import mmap
import warnings
from numeric import uint8, ndarray, dtype
dtypedescr = dtype
valid_filemodes = ["r", "c", "r+", "w+"]
writeable_filemodes = ["r+","w+"]
mode_equivalents = {
"readonly":"r",
"copyonwrite":"c",
"readwrite":"r+",
"write":"w+"
}
class memmap(ndarray):
"""Create a memory-map to an array stored in a file on disk.
Memory-mapped files are used for accessing small segments of large files
on disk, without reading the entire file into memory. Numpy's memmaps are
array-like objects. This differs from python's mmap module which are
file-like objects.
Parameters
----------
filename : string or file-like object
The file name or file object to be used as the array data
buffer.
dtype : data-type, optional
The data-type used to interpret the file contents.
Default is uint8
mode : {'r', 'r+', 'w+', 'c'}, optional
The mode to open the file.
'r', open existing file for read-only
'r+', open existing file for read-write
'w+', create or overwrite existing file and open for read-write
'c', copy-on-write, assignments effect data in memory, but changes
are not saved to disk. File on disk is read-only.
Default is 'r+'
offset : integer, optional
Byte offset into the file to start the array data. Should be a
multiple of the data-type of the data. Requires shape=None.
Default is 0
shape : tuple, optional
The desired shape of the array. If None, the returned array will be 1-D
with the number of elements determined by file size and data-type.
Default is None
order : {'C', 'F'}, optional
Specify the order of the N-D array, C or Fortran ordered. This only
has an effect if the shape is greater than 2-D.
Default is 'C'
Methods
-------
close : close the memmap file
flush : flush any changes in memory to file on disk
When you delete a memmap object, flush is called first to write
changes to disk before removing the object.
Returns
-------
memmap : array-like memmap object
The memmap object can be used anywhere an ndarray is accepted.
If fp is a memmap, isinstance(fp, numpy.ndarray) will return True.
Examples
--------
>>> import numpy as np
>>> data = np.arange(12, dtype='float32')
>>> data.resize((3,4))
>>> # Using a tempfile so doctest doesn't write files to your directory.
>>> # You would use a 'normal' filename.
>>> from tempfile import mkdtemp
>>> import os.path as path
>>> filename = path.join(mkdtemp(), 'newfile.dat')
>>> # Create a memmap with dtype and shape that matches our data
>>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
>>> fp
memmap([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)
>>> # Write data to memmap array
>>> fp[:] = data[:]
>>> fp
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> # Deletion flushes memory changes to disk before removing the object.
>>> del fp
>>> # Load the memmap and verify data was stored
>>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
>>> newfp
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> # read-only memmap
>>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
>>> fpr.flags.writeable
False
>>> # Cannot assign to read-only, obviously
>>> fpr[0, 3] = 56
Traceback (most recent call last):
...
RuntimeError: array is not writeable
>>> # copy-on-write memmap
>>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
>>> fpc.flags.writeable
True
>>> # Can assign to copy-on-write array, but values are only written
>>> # into the memory copy of the array, and not written to disk.
>>> fpc
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> fpc[0,:] = 0
>>> fpc
memmap([[ 0., 0., 0., 0.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> # file on disk is unchanged
>>> fpr
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> # offset into a memmap
>>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
>>> fpo
memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
"""
__array_priority__ = -100.0
def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
shape=None, order='C'):
try:
mode = mode_equivalents[mode]
except KeyError:
if mode not in valid_filemodes:
raise ValueError("mode must be one of %s" % \
(valid_filemodes + mode_equivalents.keys()))
if hasattr(filename,'read'):
fid = filename
else:
fid = file(filename, (mode == 'c' and 'r' or mode)+'b')
if (mode == 'w+') and shape is None:
raise ValueError, "shape must be given"
fid.seek(0,2)
flen = fid.tell()
descr = dtypedescr(dtype)
_dbytes = descr.itemsize
if shape is None:
bytes = flen-offset
if (bytes % _dbytes):
fid.close()
raise ValueError, "Size of available data is not a "\
"multiple of data-type size."
size = bytes // _dbytes
shape = (size,)
else:
if not isinstance(shape, tuple):
shape = (shape,)
size = 1
for k in shape:
size *= k
bytes = long(offset + size*_dbytes)
if mode == 'w+' or (mode == 'r+' and flen < bytes):
fid.seek(bytes-1,0)
fid.write(chr(0))
fid.flush()
if mode == 'c':
acc = mmap.ACCESS_COPY
elif mode == 'r':
acc = mmap.ACCESS_READ
else:
acc = mmap.ACCESS_WRITE
mm = mmap.mmap(fid.fileno(), bytes, access=acc)
self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm,
offset=offset, order=order)
self._mmap = mm
self._offset = offset
self._mode = mode
self._size = size
self._name = filename
return self
def __array_finalize__(self, obj):
if hasattr(obj, '_mmap'):
self._mmap = obj._mmap
else:
self._mmap = None
def flush(self):
"""Flush any changes in the array to the file on disk."""
if self._mmap is not None:
self._mmap.flush()
def sync(self):
"""Flush any changes in the array to the file on disk."""
warnings.warn("Use ``flush``.", DeprecationWarning)
self.flush()
def _close(self):
"""Close the memmap file. Only do this when deleting the object."""
if self.base is self._mmap:
self._mmap.close()
self._mmap = None
# DEV NOTE: This error is raised on the deletion of each row
# in a view of this memmap. Python traps exceptions in
# __del__ and prints them to stderr. Suppressing this for now
# until memmap code is cleaned up and and better tested for
# numpy v1.1 Objects that do not have a python mmap instance
# as their base data array, should not do anything in the
# close anyway.
#elif self._mmap is not None:
#raise ValueError, "Cannot close a memmap that is being used " \
# "by another object."
def close(self):
"""Close the memmap file. Does nothing."""
warnings.warn("``close`` is deprecated on memmap arrays. Use del",
DeprecationWarning)
def __del__(self):
if self._mmap is not None:
try:
# First run tell() to see whether file is open
self._mmap.tell()
except ValueError:
pass
else:
# flush any changes to disk, even if it's a view
self.flush()
self._close()
```
#### File: distutils/command/install_data.py
```python
from distutils.command.install_data import install_data as old_install_data
#data installer with improved intelligence over distutils
#data files are copied into the project directory instead
#of willy-nilly
class install_data (old_install_data):
def finalize_options (self):
self.set_undefined_options('install',
('install_lib', 'install_dir'),
('root', 'root'),
('force', 'force'),
)
```
#### File: distutils/command/install.py
```python
import sys
if 'setuptools' in sys.modules:
import setuptools.command.install as old_install_mod
else:
import distutils.command.install as old_install_mod
old_install = old_install_mod.install
from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
def run(self):
r = old_install.run(self)
if self.record:
# bdist_rpm fails when INSTALLED_FILES contains
# paths with spaces. Such paths must be enclosed
# with double-quotes.
f = open(self.record,'r')
lines = []
need_rewrite = False
for l in f.readlines():
l = l.rstrip()
if ' ' in l:
need_rewrite = True
l = '"%s"' % (l)
lines.append(l)
f.close()
if need_rewrite:
self.execute(write_file,
(self.record, lines),
"re-writing list of installed files to '%s'" %
self.record)
return r
```
#### File: distutils/fcompiler/g95.py
```python
from numpy.distutils.fcompiler import FCompiler
compilers = ['G95FCompiler']
class G95FCompiler(FCompiler):
compiler_type = 'g95'
description = 'G95 Fortran Compiler'
# version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95!\) (?P<version>.*)\).*'
# $ g95 --version
# G95 (GCC 4.0.3 (g95!) May 22 2006)
version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95 (?P<version>.*)!\) (?P<date>.*)\).*'
# $ g95 --version
# G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006)
executables = {
'version_cmd' : ["<F90>", "--version"],
'compiler_f77' : ["g95", "-ffixed-form"],
'compiler_fix' : ["g95", "-ffixed-form"],
'compiler_f90' : ["g95"],
'linker_so' : ["<F90>","-shared"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
pic_flags = ['-fpic']
module_dir_switch = '-fmod='
module_include_switch = '-I'
def get_flags(self):
return ['-fno-second-underscore']
def get_flags_opt(self):
return ['-O']
def get_flags_debug(self):
return ['-g']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
compiler = G95FCompiler()
compiler.customize()
print compiler.get_version()
```
#### File: site-packages/numpy/_import_tools.py
```python
import os
import sys
import imp
from glob import glob
__all__ = ['PackageLoader']
class PackageLoader:
def __init__(self, verbose=False, infunc=False):
""" Manages loading packages.
"""
if infunc:
_level = 2
else:
_level = 1
self.parent_frame = frame = sys._getframe(_level)
self.parent_name = eval('__name__',frame.f_globals,frame.f_locals)
parent_path = eval('__path__',frame.f_globals,frame.f_locals)
if isinstance(parent_path, str):
parent_path = [parent_path]
self.parent_path = parent_path
if '__all__' not in frame.f_locals:
exec('__all__ = []',frame.f_globals,frame.f_locals)
self.parent_export_names = eval('__all__',frame.f_globals,frame.f_locals)
self.info_modules = {}
self.imported_packages = []
self.verbose = None
def _get_info_files(self, package_dir, parent_path, parent_package=None):
""" Return list of (package name,info.py file) from parent_path subdirectories.
"""
from glob import glob
files = glob(os.path.join(parent_path,package_dir,'info.py'))
for info_file in glob(os.path.join(parent_path,package_dir,'info.pyc')):
if info_file[:-1] not in files:
files.append(info_file)
info_files = []
for info_file in files:
package_name = os.path.dirname(info_file[len(parent_path)+1:])\
.replace(os.sep,'.')
if parent_package:
package_name = parent_package + '.' + package_name
info_files.append((package_name,info_file))
info_files.extend(self._get_info_files('*',
os.path.dirname(info_file),
package_name))
return info_files
def _init_info_modules(self, packages=None):
"""Initialize info_modules = {<package_name>: <package info.py module>}.
"""
import imp
info_files = []
info_modules = self.info_modules
if packages is None:
for path in self.parent_path:
info_files.extend(self._get_info_files('*',path))
else:
for package_name in packages:
package_dir = os.path.join(*package_name.split('.'))
for path in self.parent_path:
names_files = self._get_info_files(package_dir, path)
if names_files:
info_files.extend(names_files)
break
else:
try:
exec 'import %s.info as info' % (package_name)
info_modules[package_name] = info
except ImportError, msg:
self.warn('No scipy-style subpackage %r found in %s. '\
'Ignoring: %s'\
% (package_name,':'.join(self.parent_path), msg))
for package_name,info_file in info_files:
if package_name in info_modules:
continue
fullname = self.parent_name +'.'+ package_name
if info_file[-1]=='c':
filedescriptor = ('.pyc','rb',2)
else:
filedescriptor = ('.py','U',1)
try:
info_module = imp.load_module(fullname+'.info',
open(info_file,filedescriptor[1]),
info_file,
filedescriptor)
except Exception,msg:
self.error(msg)
info_module = None
if info_module is None or getattr(info_module,'ignore',False):
info_modules.pop(package_name,None)
else:
self._init_info_modules(getattr(info_module,'depends',[]))
info_modules[package_name] = info_module
return
def _get_sorted_names(self):
""" Return package names sorted in the order as they should be
imported due to dependence relations between packages.
"""
depend_dict = {}
for name,info_module in self.info_modules.items():
depend_dict[name] = getattr(info_module,'depends',[])
package_names = []
for name in depend_dict.keys():
if not depend_dict[name]:
package_names.append(name)
del depend_dict[name]
while depend_dict:
for name, lst in depend_dict.items():
new_lst = [n for n in lst if n in depend_dict]
if not new_lst:
package_names.append(name)
del depend_dict[name]
else:
depend_dict[name] = new_lst
return package_names
def __call__(self,*packages, **options):
"""Load one or more packages into parent package top-level namespace.
This function is intended to shorten the need to import many
subpackages, say of scipy, constantly with statements such as
import scipy.linalg, scipy.fftpack, scipy.etc...
Instead, you can say:
import scipy
scipy.pkgload('linalg','fftpack',...)
or
scipy.pkgload()
to load all of them in one call.
If a name which doesn't exist in scipy's namespace is
given, a warning is shown.
Parameters
----------
*packges : arg-tuple
the names (one or more strings) of all the modules one
wishes to load into the top-level namespace.
verbose= : integer
verbosity level [default: -1].
verbose=-1 will suspend also warnings.
force= : bool
when True, force reloading loaded packages [default: False].
postpone= : bool
when True, don't load packages [default: False]
"""
frame = self.parent_frame
self.info_modules = {}
if options.get('force',False):
self.imported_packages = []
self.verbose = verbose = options.get('verbose',-1)
postpone = options.get('postpone',None)
self._init_info_modules(packages or None)
self.log('Imports to %r namespace\n----------------------------'\
% self.parent_name)
for package_name in self._get_sorted_names():
if package_name in self.imported_packages:
continue
info_module = self.info_modules[package_name]
global_symbols = getattr(info_module,'global_symbols',[])
postpone_import = getattr(info_module,'postpone_import',False)
if (postpone and not global_symbols) \
or (postpone_import and postpone is not None):
self.log('__all__.append(%r)' % (package_name))
if '.' not in package_name:
self.parent_export_names.append(package_name)
continue
old_object = frame.f_locals.get(package_name,None)
cmdstr = 'import '+package_name
if self._execcmd(cmdstr):
continue
self.imported_packages.append(package_name)
if verbose!=-1:
new_object = frame.f_locals.get(package_name)
if old_object is not None and old_object is not new_object:
self.warn('Overwriting %s=%s (was %s)' \
% (package_name,self._obj2repr(new_object),
self._obj2repr(old_object)))
if '.' not in package_name:
self.parent_export_names.append(package_name)
for symbol in global_symbols:
if symbol=='*':
symbols = eval('getattr(%s,"__all__",None)'\
% (package_name),
frame.f_globals,frame.f_locals)
if symbols is None:
symbols = eval('dir(%s)' % (package_name),
frame.f_globals,frame.f_locals)
symbols = filter(lambda s:not s.startswith('_'),symbols)
else:
symbols = [symbol]
if verbose!=-1:
old_objects = {}
for s in symbols:
if s in frame.f_locals:
old_objects[s] = frame.f_locals[s]
cmdstr = 'from '+package_name+' import '+symbol
if self._execcmd(cmdstr):
continue
if verbose!=-1:
for s,old_object in old_objects.items():
new_object = frame.f_locals[s]
if new_object is not old_object:
self.warn('Overwriting %s=%s (was %s)' \
% (s,self._obj2repr(new_object),
self._obj2repr(old_object)))
if symbol=='*':
self.parent_export_names.extend(symbols)
else:
self.parent_export_names.append(symbol)
return
def _execcmd(self,cmdstr):
""" Execute command in parent_frame."""
frame = self.parent_frame
try:
exec (cmdstr, frame.f_globals,frame.f_locals)
except Exception,msg:
self.error('%s -> failed: %s' % (cmdstr,msg))
return True
else:
self.log('%s -> success' % (cmdstr))
return
def _obj2repr(self,obj):
""" Return repr(obj) with"""
module = getattr(obj,'__module__',None)
file = getattr(obj,'__file__',None)
if module is not None:
return repr(obj) + ' from ' + module
if file is not None:
return repr(obj) + ' from ' + file
return repr(obj)
def log(self,mess):
if self.verbose>1:
print >> sys.stderr, str(mess)
def warn(self,mess):
if self.verbose>=0:
print >> sys.stderr, str(mess)
def error(self,mess):
if self.verbose!=-1:
print >> sys.stderr, str(mess)
def _get_doc_title(self, info_module):
""" Get the title from a package info.py file.
"""
title = getattr(info_module,'__doc_title__',None)
if title is not None:
return title
title = getattr(info_module,'__doc__',None)
if title is not None:
title = title.lstrip().split('\n',1)[0]
return title
return '* Not Available *'
def _format_titles(self,titles,colsep='---'):
display_window_width = 70 # How to determine the correct value in runtime??
lengths = [len(name)-name.find('.')-1 for (name,title) in titles]+[0]
max_length = max(lengths)
lines = []
for (name,title) in titles:
name = name[name.find('.')+1:]
w = max_length - len(name)
words = title.split()
line = '%s%s %s' % (name,w*' ',colsep)
tab = len(line) * ' '
while words:
word = words.pop(0)
if len(line)+len(word)>display_window_width:
lines.append(line)
line = tab
line += ' ' + word
else:
lines.append(line)
return '\n'.join(lines)
def get_pkgdocs(self):
""" Return documentation summary of subpackages.
"""
import sys
self.info_modules = {}
self._init_info_modules(None)
titles = []
symbols = []
for package_name, info_module in self.info_modules.items():
global_symbols = getattr(info_module,'global_symbols',[])
fullname = self.parent_name +'.'+ package_name
note = ''
if fullname not in sys.modules:
note = ' [*]'
titles.append((fullname,self._get_doc_title(info_module) + note))
if global_symbols:
symbols.append((package_name,', '.join(global_symbols)))
retstr = self._format_titles(titles) +\
'\n [*] - using a package requires explicit import (see pkgload)'
if symbols:
retstr += """\n\nGlobal symbols from subpackages"""\
"""\n-------------------------------\n""" +\
self._format_titles(symbols,'-->')
return retstr
class PackageLoaderDebug(PackageLoader):
def _execcmd(self,cmdstr):
""" Execute command in parent_frame."""
frame = self.parent_frame
print 'Executing',`cmdstr`,'...',
sys.stdout.flush()
exec (cmdstr, frame.f_globals,frame.f_locals)
print 'ok'
sys.stdout.flush()
return
if int(os.environ.get('NUMPY_IMPORT_DEBUG','0')):
PackageLoader = PackageLoaderDebug
```
#### File: numpy/lib/arraysetops.py
```python
__all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d',
'setmember1d', 'union1d', 'setdiff1d']
import time
import numpy as nm
def ediff1d(ary, to_end=None, to_begin=None):
"""The differences between consecutive elements of an array, possibly with
prefixed and/or appended values.
Parameters
----------
ary : array
This array will be flattened before the difference is taken.
to_end : number, optional
If provided, this number will be tacked onto the end of the returned
differences.
to_begin : number, optional
If provided, this number will be taked onto the beginning of the
returned differences.
Returns
-------
ed : array
The differences. Loosely, this will be (ary[1:] - ary[:-1]).
"""
ary = nm.asarray(ary).flat
ed = ary[1:] - ary[:-1]
arrays = [ed]
if to_begin is not None:
arrays.insert(0, to_begin)
if to_end is not None:
arrays.append(to_end)
if len(arrays) != 1:
# We'll save ourselves a copy of a potentially large array in the common
# case where neither to_begin or to_end was given.
ed = nm.hstack(arrays)
return ed
def unique1d(ar1, return_index=False):
"""Find the unique elements of 1D array.
Most of the other array set operations operate on the unique arrays
generated by this function.
Parameters
----------
ar1 : array
This array will be flattened if it is not already 1D.
return_index : bool, optional
If True, also return the indices against ar1 that result in the unique
array.
Returns
-------
unique : array
The unique values.
unique_indices : int array, optional
The indices of the unique values. Only provided if return_index is True.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions
for performing set operations on arrays.
"""
ar = nm.asarray(ar1).flatten()
if ar.size == 0:
if return_index: return nm.empty(0, nm.bool), ar
else: return ar
if return_index:
perm = ar.argsort()
aux = ar[perm]
flag = nm.concatenate( ([True], aux[1:] != aux[:-1]) )
return perm[flag], aux[flag]
else:
ar.sort()
flag = nm.concatenate( ([True], ar[1:] != ar[:-1]) )
return ar[flag]
def intersect1d(ar1, ar2):
"""Intersection of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as inputs
to this function. Alternatively, use intersect1d_nu() which will find the
unique values for you.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
intersection : array
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
aux = nm.concatenate((ar1,ar2))
aux.sort()
return aux[aux[1:] == aux[:-1]]
def intersect1d_nu(ar1, ar2):
"""Intersection of 1D arrays with any elements.
The input arrays do not have unique elements like intersect1d() requires.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
intersection : array
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
# Might be faster than unique1d( intersect1d( ar1, ar2 ) )?
aux = nm.concatenate((unique1d(ar1), unique1d(ar2)))
aux.sort()
return aux[aux[1:] == aux[:-1]]
def setxor1d(ar1, ar2):
"""Set exclusive-or of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
xor : array
The values that are only in one, but not both, of the input arrays.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
aux = nm.concatenate((ar1, ar2))
if aux.size == 0:
return aux
aux.sort()
# flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
flag = nm.concatenate( ([True], aux[1:] != aux[:-1], [True] ) )
# flag2 = ediff1d( flag ) == 0
flag2 = flag[1:] == flag[:-1]
return aux[flag2]
def setmember1d(ar1, ar2):
"""Return a boolean array of shape of ar1 containing True where the elements
of ar1 are in ar2 and False otherwise.
Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
mask : bool array
The values ar1[mask] are in ar2.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
ar1 = nm.asarray( ar1 )
ar2 = nm.asarray( ar2 )
ar = nm.concatenate( (ar1, ar2 ) )
b1 = nm.zeros( ar1.shape, dtype = nm.int8 )
b2 = nm.ones( ar2.shape, dtype = nm.int8 )
tt = nm.concatenate( (b1, b2) )
# We need this to be a stable sort, so always use 'mergesort' here. The
# values from the first array should always come before the values from the
# second array.
perm = ar.argsort(kind='mergesort')
aux = ar[perm]
aux2 = tt[perm]
# flag = ediff1d( aux, 1 ) == 0
flag = nm.concatenate( (aux[1:] == aux[:-1], [False] ) )
ii = nm.where( flag * aux2 )[0]
aux = perm[ii+1]
perm[ii+1] = perm[ii]
perm[ii] = aux
indx = perm.argsort(kind='mergesort')[:len( ar1 )]
return flag[indx]
def union1d(ar1, ar2):
"""
Union of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
union : array
See also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
return unique1d( nm.concatenate( (ar1, ar2) ) )
def setdiff1d(ar1, ar2):
"""Set difference of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.
Parameters
----------
ar1 : array
ar2 : array
Returns
-------
difference : array
The values in ar1 that are not in ar2.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
"""
aux = setmember1d(ar1,ar2)
if aux.size == 0:
return aux
else:
return nm.asarray(ar1)[aux == 0]
def _test_unique1d_speed( plot_results = False ):
# exponents = nm.linspace( 2, 7, 9 )
exponents = nm.linspace( 2, 7, 9 )
ratios = []
nItems = []
dt1s = []
dt2s = []
for ii in exponents:
nItem = 10 ** ii
print 'using %d items:' % nItem
a = nm.fix( nItem / 10 * nm.random.random( nItem ) )
print 'unique:'
tt = time.clock()
b = nm.unique( a )
dt1 = time.clock() - tt
print dt1
print 'unique1d:'
tt = time.clock()
c = unique1d( a )
dt2 = time.clock() - tt
print dt2
if dt1 < 1e-8:
ratio = 'ND'
else:
ratio = dt2 / dt1
print 'ratio:', ratio
print 'nUnique: %d == %d\n' % (len( b ), len( c ))
nItems.append( nItem )
ratios.append( ratio )
dt1s.append( dt1 )
dt2s.append( dt2 )
assert nm.alltrue( b == c )
print nItems
print dt1s
print dt2s
print ratios
if plot_results:
import pylab
def plotMe( fig, fun, nItems, dt1s, dt2s ):
pylab.figure( fig )
fun( nItems, dt1s, 'g-o', linewidth = 2, markersize = 8 )
fun( nItems, dt2s, 'b-x', linewidth = 2, markersize = 8 )
pylab.legend( ('unique', 'unique1d' ) )
pylab.xlabel( 'nItem' )
pylab.ylabel( 'time [s]' )
plotMe( 1, pylab.loglog, nItems, dt1s, dt2s )
plotMe( 2, pylab.plot, nItems, dt1s, dt2s )
pylab.show()
if (__name__ == '__main__'):
_test_unique1d_speed( plot_results = True )
```
#### File: numpy/lib/function_base.py
```python
__docformat__ = "restructuredtext en"
__all__ = ['logspace', 'linspace',
'select', 'piecewise', 'trim_zeros',
'copy', 'iterable',
'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp',
'unique', 'extract', 'place', 'nansum', 'nanmax', 'nanargmax',
'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average',
'histogram', 'histogramdd', 'bincount', 'digitize', 'cov',
'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning',
'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc',
'add_docstring', 'meshgrid', 'delete', 'insert', 'append',
'interp'
]
import warnings
import types
import numpy.core.numeric as _nx
from numpy.core.numeric import ones, zeros, arange, concatenate, array, \
asarray, asanyarray, empty, empty_like, ndarray, around
from numpy.core.numeric import ScalarType, dot, where, newaxis, intp, \
integer, isscalar
from numpy.core.umath import pi, multiply, add, arctan2, \
frompyfunc, isnan, cos, less_equal, sqrt, sin, mod, exp, log10
from numpy.core.fromnumeric import ravel, nonzero, choose, sort, mean
from numpy.core.numerictypes import typecodes, number
from numpy.lib.shape_base import atleast_1d, atleast_2d
from numpy.lib.twodim_base import diag
from _compiled_base import _insert, add_docstring
from _compiled_base import digitize, bincount, interp as compiled_interp
from arraysetops import setdiff1d
import numpy as np
#end Fernando's utilities
def linspace(start, stop, num=50, endpoint=True, retstep=False):
"""Return evenly spaced numbers.
Return num evenly spaced samples from start to stop. If
endpoint is True, the last sample is stop. If retstep is
True then return (seq, step_value), where step_value used.
Parameters
----------
start : {float}
The value the sequence starts at.
stop : {float}
The value the sequence stops at. If ``endpoint`` is false, then
this is not included in the sequence. Otherwise it is
guaranteed to be the last value.
num : {integer}
Number of samples to generate. Default is 50.
endpoint : {boolean}
If true, ``stop`` is the last sample. Otherwise, it is not
included. Default is true.
retstep : {boolean}
If true, return ``(samples, step)``, where ``step`` is the
spacing used in generating the samples.
Returns
-------
samples : {array}
``num`` equally spaced samples from the range [start, stop]
or [start, stop).
step : {float} (Only if ``retstep`` is true)
Size of spacing between samples.
See Also
--------
arange : Similiar to linspace, however, when used with
a float endpoint, that endpoint may or may not be included.
logspace
"""
num = int(num)
if num <= 0:
return array([], float)
if endpoint:
if num == 1:
return array([float(start)])
step = (stop-start)/float((num-1))
y = _nx.arange(0, num) * step + start
y[-1] = stop
else:
step = (stop-start)/float(num)
y = _nx.arange(0, num) * step + start
if retstep:
return y, step
else:
return y
def logspace(start,stop,num=50,endpoint=True,base=10.0):
"""Evenly spaced numbers on a logarithmic scale.
Computes int(num) evenly spaced exponents from base**start to
base**stop. If endpoint=True, then last number is base**stop
"""
y = linspace(start,stop,num=num,endpoint=endpoint)
return _nx.power(base,y)
def iterable(y):
try: iter(y)
except: return 0
return 1
def histogram(a, bins=10, range=None, normed=False, weights=None, new=False):
"""Compute the histogram from a set of data.
Parameters
----------
a : array
The data to histogram.
bins : int or sequence
If an int, then the number of equal-width bins in the given
range. If new=True, bins can also be the bin edges, allowing
for non-constant bin widths.
range : (float, float)
The lower and upper range of the bins. If not provided, range
is simply (a.min(), a.max()). Using new=False, lower than
range are ignored, and values higher than range are tallied in
the rightmost bin. Using new=True, both lower and upper
outliers are ignored.
normed : bool
If False, the result array will contain the number of samples
in each bin. If True, the result array is the value of the
probability *density* function at the bin normalized such that
the *integral* over the range is 1. Note that the sum of all
of the histogram values will not usually be 1; it is not a
probability *mass* function.
weights : array
An array of weights, the same shape as a. If normed is False,
the histogram is computed by summing the weights of the values
falling into each bin. If normed is True, the weights are
normalized, so that the integral of the density over the range
is 1. This option is only available with new=True.
new : bool
Compatibility argument to transition from the old version
(v1.1) to the new version (v1.2).
Returns
-------
hist : array
The values of the histogram. See `normed` and `weights` for a
description of the possible semantics.
bin_edges : float array
With new=False, return the left bin edges (length(hist)).
With new=True, return the bin edges (length(hist)+1).
See Also
--------
histogramdd
"""
# Old behavior
if new is False:
warnings.warn("""
The semantics of histogram will be modified in
release 1.2 to improve outlier handling. The new behavior can be
obtained using new=True. Note that the new version accepts/returns
the bin edges instead of the left bin edges.
Please read the docstring for more information.""", FutureWarning)
a = asarray(a).ravel()
if (range is not None):
mn, mx = range
if (mn > mx):
raise AttributeError, \
'max must be larger than min in range parameter.'
if not iterable(bins):
if range is None:
range = (a.min(), a.max())
else:
warnings.warn("""
Outliers handling will change in version 1.2.
Please read the docstring for details.""", FutureWarning)
mn, mx = [mi+0.0 for mi in range]
if mn == mx:
mn -= 0.5
mx += 0.5
bins = linspace(mn, mx, bins, endpoint=False)
else:
if normed:
raise ValueError, 'Use new=True to pass bin edges explicitly.'
warnings.warn("""
The semantic for bins will change in version 1.2.
The bins will become the bin edges, instead of the left bin edges.
""", FutureWarning)
bins = asarray(bins)
if (np.diff(bins) < 0).any():
raise AttributeError, 'bins must increase monotonically.'
if weights is not None:
raise ValueError, 'weights are only available with new=True.'
# best block size probably depends on processor cache size
block = 65536
n = sort(a[:block]).searchsorted(bins)
for i in xrange(block, a.size, block):
n += sort(a[i:i+block]).searchsorted(bins)
n = concatenate([n, [len(a)]])
n = n[1:]-n[:-1]
if normed:
db = bins[1] - bins[0]
return 1.0/(a.size*db) * n, bins
else:
return n, bins
# New behavior
elif new is True:
a = asarray(a)
if weights is not None:
weights = asarray(weights)
if np.any(weights.shape != a.shape):
raise ValueError, 'weights should have the same shape as a.'
weights = weights.ravel()
a = a.ravel()
if (range is not None):
mn, mx = range
if (mn > mx):
raise AttributeError, \
'max must be larger than min in range parameter.'
if not iterable(bins):
if range is None:
range = (a.min(), a.max())
mn, mx = [mi+0.0 for mi in range]
if mn == mx:
mn -= 0.5
mx += 0.5
bins = linspace(mn, mx, bins+1, endpoint=True)
else:
bins = asarray(bins)
if (np.diff(bins) < 0).any():
raise AttributeError, 'bins must increase monotonically.'
# Histogram is an integer or a float array depending on the weights.
if weights is None:
ntype = int
else:
ntype = weights.dtype
n = np.zeros(bins.shape, ntype)
block = 65536
if weights is None:
for i in arange(0, len(a), block):
sa = sort(a[i:i+block])
n += np.r_[sa.searchsorted(bins[:-1], 'left'), \
sa.searchsorted(bins[-1], 'right')]
else:
zero = array(0, dtype=ntype)
for i in arange(0, len(a), block):
tmp_a = a[i:i+block]
tmp_w = weights[i:i+block]
sorting_index = np.argsort(tmp_a)
sa = tmp_a[sorting_index]
sw = tmp_w[sorting_index]
cw = np.concatenate(([zero,], sw.cumsum()))
bin_index = np.r_[sa.searchsorted(bins[:-1], 'left'), \
sa.searchsorted(bins[-1], 'right')]
n += cw[bin_index]
n = np.diff(n)
if normed is False:
return n, bins
elif normed is True:
db = array(np.diff(bins), float)
return n/(n*db).sum(), bins
def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
"""histogramdd(sample, bins=10, range=None, normed=False, weights=None)
Return the N-dimensional histogram of the sample.
Parameters
----------
sample : sequence or array
A sequence containing N arrays or an NxM array. Input data.
bins : sequence or scalar
A sequence of edge arrays, a sequence of bin counts, or a scalar
which is the bin count for all dimensions. Default is 10.
range : sequence
A sequence of lower and upper bin edges. Default is [min, max].
normed : boolean
If False, return the number of samples in each bin, if True,
returns the density.
weights : array
Array of weights. The weights are normed only if normed is True.
Should the sum of the weights not equal N, the total bin count will
not be equal to the number of samples.
Returns
-------
hist : array
Histogram array.
edges : list
List of arrays defining the lower bin edges.
See Also
--------
histogram
Examples
--------
>>> x = random.randn(100,3)
>>> hist3d, edges = histogramdd(x, bins = (5, 6, 7))
"""
try:
# Sample is an ND-array.
N, D = sample.shape
except (AttributeError, ValueError):
# Sample is a sequence of 1D arrays.
sample = atleast_2d(sample).T
N, D = sample.shape
nbin = empty(D, int)
edges = D*[None]
dedges = D*[None]
if weights is not None:
weights = asarray(weights)
try:
M = len(bins)
if M != D:
raise AttributeError, 'The dimension of bins must be equal ' \
'to the dimension of the sample x.'
except TypeError:
bins = D*[bins]
# Select range for each dimension
# Used only if number of bins is given.
if range is None:
smin = atleast_1d(array(sample.min(0), float))
smax = atleast_1d(array(sample.max(0), float))
else:
smin = zeros(D)
smax = zeros(D)
for i in arange(D):
smin[i], smax[i] = range[i]
# Make sure the bins have a finite width.
for i in arange(len(smin)):
if smin[i] == smax[i]:
smin[i] = smin[i] - .5
smax[i] = smax[i] + .5
# Create edge arrays
for i in arange(D):
if isscalar(bins[i]):
nbin[i] = bins[i] + 2 # +2 for outlier bins
edges[i] = linspace(smin[i], smax[i], nbin[i]-1)
else:
edges[i] = asarray(bins[i], float)
nbin[i] = len(edges[i])+1 # +1 for outlier bins
dedges[i] = diff(edges[i])
nbin = asarray(nbin)
# Compute the bin number each sample falls into.
Ncount = {}
for i in arange(D):
Ncount[i] = digitize(sample[:,i], edges[i])
# Using digitize, values that fall on an edge are put in the right bin.
# For the rightmost bin, we want values equal to the right
# edge to be counted in the last bin, and not as an outlier.
outliers = zeros(N, int)
for i in arange(D):
# Rounding precision
decimal = int(-log10(dedges[i].min())) +6
# Find which points are on the rightmost edge.
on_edge = where(around(sample[:,i], decimal) == around(edges[i][-1],
decimal))[0]
# Shift these points one bin to the left.
Ncount[i][on_edge] -= 1
# Flattened histogram matrix (1D)
hist = zeros(nbin.prod(), float)
# Compute the sample indices in the flattened histogram matrix.
ni = nbin.argsort()
shape = []
xy = zeros(N, int)
for i in arange(0, D-1):
xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod()
xy += Ncount[ni[-1]]
# Compute the number of repetitions in xy and assign it to the
# flattened histmat.
if len(xy) == 0:
return zeros(nbin-2, int), edges
flatcount = bincount(xy, weights)
a = arange(len(flatcount))
hist[a] = flatcount
# Shape into a proper matrix
hist = hist.reshape(sort(nbin))
for i in arange(nbin.size):
j = ni.argsort()[i]
hist = hist.swapaxes(i,j)
ni[i],ni[j] = ni[j],ni[i]
# Remove outliers (indices 0 and -1 for each dimension).
core = D*[slice(1,-1)]
hist = hist[core]
# Normalize if normed is True
if normed:
s = hist.sum()
for i in arange(D):
shape = ones(D, int)
shape[i] = nbin[i]-2
hist = hist / dedges[i].reshape(shape)
hist /= s
if (hist.shape != nbin-2).any():
raise 'Internal Shape Error'
return hist, edges
def average(a, axis=None, weights=None, returned=False):
"""Return the weighted average of array a over the given axis.
Parameters
----------
a : array_like
Data to be averaged.
axis : {None, integer}, optional
Axis along which to average a. If None, averaging is done over the
entire array irrespective of its shape.
weights : {None, array_like}, optional
The importance each datum has in the computation of the
average. The weights array can either be 1D, in which case its length
must be the size of a along the given axis, or of the same shape as a.
If weights=None, all data are assumed to have weight equal to one.
returned :{False, boolean}, optional
If True, the tuple (average, sum_of_weights) is returned,
otherwise only the average is returmed. Note that if weights=None, then
the sum of the weights is also the number of elements averaged over.
Returns
-------
average, [sum_of_weights] : {array_type, double}
Return the average along the specified axis. When returned is True,
return a tuple with the average as the first element and the sum
of the weights as the second element. The return type is Float if a is
of integer type, otherwise it is of the same type as a.
sum_of_weights is has the same type as the average.
Examples
--------
>>> average(range(1,11), weights=range(10,0,-1))
4.0
Raises
------
ZeroDivisionError
When all weights along axis are zero. See numpy.ma.average for a
version robust to this type of error.
TypeError
When the length of 1D weights is not the same as the shape of a
along axis.
"""
if not isinstance(a, np.matrix) :
a = np.asarray(a)
if weights is None :
avg = a.mean(axis)
scl = avg.dtype.type(a.size/avg.size)
else :
a = a + 0.0
wgt = np.array(weights, dtype=a.dtype, copy=0)
# Sanity checks
if a.shape != wgt.shape :
if axis is None :
raise TypeError, "Axis must be specified when shapes of a and weights differ."
if wgt.ndim != 1 :
raise TypeError, "1D weights expected when shapes of a and weights differ."
if wgt.shape[0] != a.shape[axis] :
raise ValueError, "Length of weights not compatible with specified axis."
# setup wgt to broadcast along axis
wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1,axis)
scl = wgt.sum(axis=axis)
if (scl == 0.0).any():
raise ZeroDivisionError, "Weights sum to zero, can't be normalized"
avg = np.multiply(a,wgt).sum(axis)/scl
if returned:
scl = np.multiply(avg,0) + scl
return avg, scl
else:
return avg
def asarray_chkfinite(a):
"""Like asarray, but check that no NaNs or Infs are present.
"""
a = asarray(a)
if (a.dtype.char in typecodes['AllFloat']) \
and (_nx.isnan(a).any() or _nx.isinf(a).any()):
raise ValueError, "array must not contain infs or NaNs"
return a
def piecewise(x, condlist, funclist, *args, **kw):
"""Return a piecewise-defined function.
x is the domain
condlist is a list of boolean arrays or a single boolean array
The length of the condition list must be n2 or n2-1 where n2
is the length of the function list. If len(condlist)==n2-1, then
an 'otherwise' condition is formed by |'ing all the conditions
and inverting.
funclist is a list of functions to call of length (n2).
Each function should return an array output for an array input
Each function can take (the same set) of extra arguments and
keyword arguments which are passed in after the function list.
A constant may be used in funclist for a function that returns a
constant (e.g. val and lambda x: val are equivalent in a funclist).
The output is the same shape and type as x and is found by
calling the functions on the appropriate portions of x.
Note: This is similar to choose or select, except
the the functions are only evaluated on elements of x
that satisfy the corresponding condition.
The result is
|--
| f1(x) for condition1
y = --| f2(x) for condition2
| ...
| fn(x) for conditionn
|--
"""
x = asanyarray(x)
n2 = len(funclist)
if isscalar(condlist) or \
not (isinstance(condlist[0], list) or
isinstance(condlist[0], ndarray)):
condlist = [condlist]
condlist = [asarray(c, dtype=bool) for c in condlist]
n = len(condlist)
if n == n2-1: # compute the "otherwise" condition.
totlist = condlist[0]
for k in range(1, n):
totlist |= condlist[k]
condlist.append(~totlist)
n += 1
if (n != n2):
raise ValueError, "function list and condition list " \
"must be the same"
zerod = False
# This is a hack to work around problems with NumPy's
# handling of 0-d arrays and boolean indexing with
# numpy.bool_ scalars
if x.ndim == 0:
x = x[None]
zerod = True
newcondlist = []
for k in range(n):
if condlist[k].ndim == 0:
condition = condlist[k][None]
else:
condition = condlist[k]
newcondlist.append(condition)
condlist = newcondlist
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not callable(item):
y[condlist[k]] = item
else:
y[condlist[k]] = item(x[condlist[k]], *args, **kw)
return y
def select(condlist, choicelist, default=0):
"""Return an array composed of different elements in choicelist,
depending on the list of conditions.
:Parameters:
condlist : list of N boolean arrays of length M
The conditions C_0 through C_(N-1) which determine
from which vector the output elements are taken.
choicelist : list of N arrays of length M
Th vectors V_0 through V_(N-1), from which the output
elements are chosen.
:Returns:
output : 1-dimensional array of length M
The output at position m is the m-th element of the first
vector V_n for which C_n[m] is non-zero. Note that the
output depends on the order of conditions, since the
first satisfied condition is used.
Equivalent to:
output = []
for m in range(M):
output += [V[m] for V,C in zip(values,cond) if C[m]]
or [default]
"""
n = len(condlist)
n2 = len(choicelist)
if n2 != n:
raise ValueError, "list of cases must be same length as list of conditions"
choicelist = [default] + choicelist
S = 0
pfac = 1
for k in range(1, n+1):
S += k * pfac * asarray(condlist[k-1])
if k < n:
pfac *= (1-asarray(condlist[k-1]))
# handle special case of a 1-element condition but
# a multi-element choice
if type(S) in ScalarType or max(asarray(S).shape)==1:
pfac = asarray(1)
for k in range(n2+1):
pfac = pfac + asarray(choicelist[k])
if type(S) in ScalarType:
S = S*ones(asarray(pfac).shape, type(S))
else:
S = S*ones(asarray(pfac).shape, S.dtype)
return choose(S, tuple(choicelist))
def _asarray1d(arr, copy=False):
"""Ensure 1D array for one array.
"""
if copy:
return asarray(arr).flatten()
else:
return asarray(arr).ravel()
def copy(a):
"""Return an array copy of the given object.
"""
return array(a, copy=True)
# Basic operations
def gradient(f, *varargs):
"""Calculate the gradient of an N-dimensional scalar function.
Uses central differences on the interior and first differences on boundaries
to give the same shape.
Inputs:
f -- An N-dimensional array giving samples of a scalar function
varargs -- 0, 1, or N scalars giving the sample distances in each direction
Outputs:
N arrays of the same shape as f giving the derivative of f with respect
to each dimension.
"""
N = len(f.shape) # number of dimensions
n = len(varargs)
if n == 0:
dx = [1.0]*N
elif n == 1:
dx = [varargs[0]]*N
elif n == N:
dx = list(varargs)
else:
raise SyntaxError, "invalid number of arguments"
# use central differences on interior and first differences on endpoints
outvals = []
# create slice objects --- initially all are [:, :, ..., :]
slice1 = [slice(None)]*N
slice2 = [slice(None)]*N
slice3 = [slice(None)]*N
otype = f.dtype.char
if otype not in ['f', 'd', 'F', 'D']:
otype = 'd'
for axis in range(N):
# select out appropriate parts for this dimension
out = zeros(f.shape, f.dtype.char)
slice1[axis] = slice(1, -1)
slice2[axis] = slice(2, None)
slice3[axis] = slice(None, -2)
# 1D equivalent -- out[1:-1] = (f[2:] - f[:-2])/2.0
out[slice1] = (f[slice2] - f[slice3])/2.0
slice1[axis] = 0
slice2[axis] = 1
slice3[axis] = 0
# 1D equivalent -- out[0] = (f[1] - f[0])
out[slice1] = (f[slice2] - f[slice3])
slice1[axis] = -1
slice2[axis] = -1
slice3[axis] = -2
# 1D equivalent -- out[-1] = (f[-1] - f[-2])
out[slice1] = (f[slice2] - f[slice3])
# divide by step size
outvals.append(out / dx[axis])
# reset the slice object in this dimension to ":"
slice1[axis] = slice(None)
slice2[axis] = slice(None)
slice3[axis] = slice(None)
if N == 1:
return outvals[0]
else:
return outvals
def diff(a, n=1, axis=-1):
"""Calculate the nth order discrete difference along given axis.
"""
if n == 0:
return a
if n < 0:
raise ValueError, 'order must be non-negative but got ' + repr(n)
a = asanyarray(a)
nd = len(a.shape)
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
if n > 1:
return diff(a[slice1]-a[slice2], n-1, axis=axis)
else:
return a[slice1]-a[slice2]
try:
add_docstring(digitize,
r"""digitize(x,bins)
Return the index of the bin to which each value of x belongs.
Each index i returned is such that bins[i-1] <= x < bins[i] if
bins is monotonically increasing, or bins [i-1] > x >= bins[i] if
bins is monotonically decreasing.
Beyond the bounds of the bins 0 or len(bins) is returned as appropriate.
""")
except RuntimeError:
pass
try:
add_docstring(bincount,
r"""bincount(x,weights=None)
Return the number of occurrences of each value in x.
x must be a list of non-negative integers. The output, b[i],
represents the number of times that i is found in x. If weights
is specified, every occurrence of i at a position p contributes
weights[p] instead of 1.
See also: histogram, digitize, unique.
""")
except RuntimeError:
pass
try:
add_docstring(add_docstring,
r"""docstring(obj, docstring)
Add a docstring to a built-in obj if possible.
If the obj already has a docstring raise a RuntimeError
If this routine does not know how to add a docstring to the object
raise a TypeError
""")
except RuntimeError:
pass
def interp(x, xp, fp, left=None, right=None):
"""Return the value of a piecewise-linear function at each value in x.
The piecewise-linear function, f, is defined by the known data-points
fp=f(xp). The xp points must be sorted in increasing order but this is
not checked.
For values of x < xp[0] return the value given by left. If left is None,
then return fp[0].
For values of x > xp[-1] return the value given by right. If right is
None, then return fp[-1].
"""
if isinstance(x, (float, int, number)):
return compiled_interp([x], xp, fp, left, right).item()
else:
return compiled_interp(x, xp, fp, left, right)
def angle(z, deg=0):
"""
Return the angle of the complex argument z.
Examples
--------
>>> numpy.angle(1+1j) # in radians
0.78539816339744828
>>> numpy.angle(1+1j,deg=True) # in degrees
45.0
"""
if deg:
fact = 180/pi
else:
fact = 1.0
z = asarray(z)
if (issubclass(z.dtype.type, _nx.complexfloating)):
zimag = z.imag
zreal = z.real
else:
zimag = 0
zreal = z
return arctan2(zimag, zreal) * fact
def unwrap(p, discont=pi, axis=-1):
"""Unwrap radian phase p by changing absolute jumps greater than
'discont' to their 2*pi complement along the given axis.
"""
p = asarray(p)
nd = len(p.shape)
dd = diff(p, axis=axis)
slice1 = [slice(None, None)]*nd # full slices
slice1[axis] = slice(1, None)
ddmod = mod(dd+pi, 2*pi)-pi
_nx.putmask(ddmod, (ddmod==-pi) & (dd > 0), pi)
ph_correct = ddmod - dd;
_nx.putmask(ph_correct, abs(dd)<discont, 0)
up = array(p, copy=True, dtype='d')
up[slice1] = p[slice1] + ph_correct.cumsum(axis)
return up
def sort_complex(a):
""" Sort 'a' as a complex array using the real part first and then
the imaginary part if the real part is equal (the default sort order
for complex arrays). This function is a wrapper ensuring a complex
return type.
"""
b = array(a,copy=True)
b.sort()
if not issubclass(b.dtype.type, _nx.complexfloating):
if b.dtype.char in 'bhBH':
return b.astype('F')
elif b.dtype.char == 'g':
return b.astype('G')
else:
return b.astype('D')
else:
return b
def trim_zeros(filt, trim='fb'):
""" Trim the leading and trailing zeros from a 1D array.
Examples
--------
>>> import numpy
>>> a = array((0, 0, 0, 1, 2, 3, 2, 1, 0))
>>> numpy.trim_zeros(a)
array([1, 2, 3, 2, 1])
"""
first = 0
trim = trim.upper()
if 'F' in trim:
for i in filt:
if i != 0.: break
else: first = first + 1
last = len(filt)
if 'B' in trim:
for i in filt[::-1]:
if i != 0.: break
else: last = last - 1
return filt[first:last]
import sys
if sys.hexversion < 0x2040000:
from sets import Set as set
def unique(x):
"""
Return sorted unique items from an array or sequence.
Examples
--------
>>> numpy.unique([5,2,4,0,4,4,2,2,1])
array([0, 1, 2, 4, 5])
"""
try:
tmp = x.flatten()
if tmp.size == 0:
return tmp
tmp.sort()
idx = concatenate(([True],tmp[1:]!=tmp[:-1]))
return tmp[idx]
except AttributeError:
items = list(set(x))
items.sort()
return asarray(items)
def extract(condition, arr):
"""Return the elements of ravel(arr) where ravel(condition) is True
(in 1D).
Equivalent to compress(ravel(condition), ravel(arr)).
"""
return _nx.take(ravel(arr), nonzero(ravel(condition))[0])
def place(arr, mask, vals):
"""Similar to putmask arr[mask] = vals but the 1D array vals has the
same number of elements as the non-zero values of mask. Inverse of
extract.
"""
return _insert(arr, mask, vals)
def nansum(a, axis=None):
"""Sum the array over the given axis, treating NaNs as 0.
"""
y = array(a,subok=True)
if not issubclass(y.dtype.type, _nx.integer):
y[isnan(a)] = 0
return y.sum(axis)
def nanmin(a, axis=None):
"""Find the minimium over the given axis, ignoring NaNs.
"""
y = array(a,subok=True)
if not issubclass(y.dtype.type, _nx.integer):
y[isnan(a)] = _nx.inf
return y.min(axis)
def nanargmin(a, axis=None):
"""Find the indices of the minimium over the given axis ignoring NaNs.
"""
y = array(a, subok=True)
if not issubclass(y.dtype.type, _nx.integer):
y[isnan(a)] = _nx.inf
return y.argmin(axis)
def nanmax(a, axis=None):
"""Find the maximum over the given axis ignoring NaNs.
"""
y = array(a, subok=True)
if not issubclass(y.dtype.type, _nx.integer):
y[isnan(a)] = -_nx.inf
return y.max(axis)
def nanargmax(a, axis=None):
"""Find the maximum over the given axis ignoring NaNs.
"""
y = array(a,subok=True)
if not issubclass(y.dtype.type, _nx.integer):
y[isnan(a)] = -_nx.inf
return y.argmax(axis)
def disp(mesg, device=None, linefeed=True):
"""Display a message to the given device (default is sys.stdout)
with or without a linefeed.
"""
if device is None:
import sys
device = sys.stdout
if linefeed:
device.write('%s\n' % mesg)
else:
device.write('%s' % mesg)
device.flush()
return
# return number of input arguments and
# number of default arguments
import re
def _get_nargs(obj):
if not callable(obj):
raise TypeError, "Object is not callable."
if hasattr(obj,'func_code'):
fcode = obj.func_code
nargs = fcode.co_argcount
if obj.func_defaults is not None:
ndefaults = len(obj.func_defaults)
else:
ndefaults = 0
if isinstance(obj, types.MethodType):
nargs -= 1
return nargs, ndefaults
terr = re.compile(r'.*? takes exactly (?P<exargs>\d+) argument(s|) \((?P<gargs>\d+) given\)')
try:
obj()
return 0, 0
except TypeError, msg:
m = terr.match(str(msg))
if m:
nargs = int(m.group('exargs'))
ndefaults = int(m.group('gargs'))
if isinstance(obj, types.MethodType):
nargs -= 1
return nargs, ndefaults
raise ValueError, 'failed to determine the number of arguments for %s' % (obj)
class vectorize(object):
"""
vectorize(somefunction, otypes=None, doc=None)
Generalized function class.
Define a vectorized function which takes nested sequence
of objects or numpy arrays as inputs and returns a
numpy array as output, evaluating the function over successive
tuples of the input arrays like the python map function except it uses
the broadcasting rules of numpy.
Data-type of output of vectorized is determined by calling the function
with the first element of the input. This can be avoided by specifying
the otypes argument as either a string of typecode characters or a list
of data-types specifiers. There should be one data-type specifier for
each output.
Parameters
----------
f : callable
A Python function or method.
Examples
--------
>>> def myfunc(a, b):
... if a > b:
... return a-b
... else:
... return a+b
>>> vfunc = vectorize(myfunc)
>>> vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])
"""
def __init__(self, pyfunc, otypes='', doc=None):
self.thefunc = pyfunc
self.ufunc = None
nin, ndefault = _get_nargs(pyfunc)
if nin == 0 and ndefault == 0:
self.nin = None
self.nin_wo_defaults = None
else:
self.nin = nin
self.nin_wo_defaults = nin - ndefault
self.nout = None
if doc is None:
self.__doc__ = pyfunc.__doc__
else:
self.__doc__ = doc
if isinstance(otypes, str):
self.otypes = otypes
for char in self.otypes:
if char not in typecodes['All']:
raise ValueError, "invalid otype specified"
elif iterable(otypes):
self.otypes = ''.join([_nx.dtype(x).char for x in otypes])
else:
raise ValueError, "output types must be a string of typecode characters or a list of data-types"
self.lastcallargs = 0
def __call__(self, *args):
# get number of outputs and output types by calling
# the function on the first entries of args
nargs = len(args)
if self.nin:
if (nargs > self.nin) or (nargs < self.nin_wo_defaults):
raise ValueError, "mismatch between python function inputs"\
" and received arguments"
# we need a new ufunc if this is being called with more arguments.
if (self.lastcallargs != nargs):
self.lastcallargs = nargs
self.ufunc = None
self.nout = None
if self.nout is None or self.otypes == '':
newargs = []
for arg in args:
newargs.append(asarray(arg).flat[0])
theout = self.thefunc(*newargs)
if isinstance(theout, tuple):
self.nout = len(theout)
else:
self.nout = 1
theout = (theout,)
if self.otypes == '':
otypes = []
for k in range(self.nout):
otypes.append(asarray(theout[k]).dtype.char)
self.otypes = ''.join(otypes)
# Create ufunc if not already created
if (self.ufunc is None):
self.ufunc = frompyfunc(self.thefunc, nargs, self.nout)
# Convert to object arrays first
newargs = [array(arg,copy=False,subok=True,dtype=object) for arg in args]
if self.nout == 1:
_res = array(self.ufunc(*newargs),copy=False,
subok=True,dtype=self.otypes[0])
else:
_res = tuple([array(x,copy=False,subok=True,dtype=c) \
for x, c in zip(self.ufunc(*newargs), self.otypes)])
return _res
def cov(m, y=None, rowvar=1, bias=0):
"""Estimate the covariance matrix.
If m is a vector, return the variance. For matrices return the
covariance matrix.
If y is given it is treated as an additional (set of)
variable(s).
Normalization is by (N-1) where N is the number of observations
(unbiased estimate). If bias is 1 then normalization is by N.
If rowvar is non-zero (default), then each row is a variable with
observations in the columns, otherwise each column
is a variable and the observations are in the rows.
"""
X = array(m, ndmin=2, dtype=float)
if X.shape[0] == 1:
rowvar = 1
if rowvar:
axis = 0
tup = (slice(None),newaxis)
else:
axis = 1
tup = (newaxis, slice(None))
if y is not None:
y = array(y, copy=False, ndmin=2, dtype=float)
X = concatenate((X,y),axis)
X -= X.mean(axis=1-axis)[tup]
if rowvar:
N = X.shape[1]
else:
N = X.shape[0]
if bias:
fact = N*1.0
else:
fact = N-1.0
if not rowvar:
return (dot(X.T, X.conj()) / fact).squeeze()
else:
return (dot(X, X.T.conj()) / fact).squeeze()
def corrcoef(x, y=None, rowvar=1, bias=0):
"""The correlation coefficients
"""
c = cov(x, y, rowvar, bias)
try:
d = diag(c)
except ValueError: # scalar covariance
return 1
return c/sqrt(multiply.outer(d,d))
def blackman(M):
"""blackman(M) returns the M-point Blackman window.
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0,M)
return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
def bartlett(M):
"""
Return the Bartlett window.
The Bartlett window is very similar to a triangular window, except
that the end points are at zero. It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : array
The triangular window, normalized to one (the value one
appears only if the number of samples is odd), with the first
and last samples equal to zero.
See Also
--------
blackman, hamming, hanning, kaiser
Notes
-----
The Bartlett window is defined as
.. math:: w(n) = \\frac{2}{M-1} \left(
\\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right|
\\right)
Most references to the Bartlett window come from the signal
processing literature, where it is used as one of many windowing
functions for smoothing values. Note that convolution with this
window produces linear interpolation. It is also known as an
apodization (which means"removing the foot", i.e. smoothing
discontinuities at the beginning and end of the sampled signal) or
tapering function.
References
----------
.. [1] <NAME>, "Periodogram Analysis and Continuous Spectra",
Biometrika 37, 1-16, 1950.
.. [2] <NAME> and <NAME>, "Discrete-Time Signal
Processing", Prentice-Hall, 1999, pp. 468-471.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] <NAME>, <NAME>, <NAME>, and <NAME>,
"Numerical Recipes", Cambridge University Press, 1986, page 429.
Examples
--------
>>> from numpy import bartlett
>>> bartlett(12)
array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273,
0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
0.18181818, 0. ])
Plot the window and its frequency response:
>>> from numpy import clip, log10, array, bartlett
>>> from scipy.fftpack import fft
>>> from matplotlib import pyplot as plt
>>> window = bartlett(51)
>>> plt.plot(window)
>>> plt.title("Bartlett window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.show()
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of Bartlett window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0,M)
return where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1))
def hanning(M):
"""hanning(M) returns the M-point Hanning window.
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0,M)
return 0.5-0.5*cos(2.0*pi*n/(M-1))
def hamming(M):
"""hamming(M) returns the M-point Hamming window.
"""
if M < 1:
return array([])
if M == 1:
return ones(1,float)
n = arange(0,M)
return 0.54-0.46*cos(2.0*pi*n/(M-1))
## Code from cephes for i0
_i0A = [
-4.41534164647933937950E-18,
3.33079451882223809783E-17,
-2.43127984654795469359E-16,
1.71539128555513303061E-15,
-1.16853328779934516808E-14,
7.67618549860493561688E-14,
-4.85644678311192946090E-13,
2.95505266312963983461E-12,
-1.72682629144155570723E-11,
9.67580903537323691224E-11,
-5.18979560163526290666E-10,
2.65982372468238665035E-9,
-1.30002500998624804212E-8,
6.04699502254191894932E-8,
-2.67079385394061173391E-7,
1.11738753912010371815E-6,
-4.41673835845875056359E-6,
1.64484480707288970893E-5,
-5.75419501008210370398E-5,
1.88502885095841655729E-4,
-5.76375574538582365885E-4,
1.63947561694133579842E-3,
-4.32430999505057594430E-3,
1.05464603945949983183E-2,
-2.37374148058994688156E-2,
4.93052842396707084878E-2,
-9.49010970480476444210E-2,
1.71620901522208775349E-1,
-3.04682672343198398683E-1,
6.76795274409476084995E-1]
_i0B = [
-7.23318048787475395456E-18,
-4.83050448594418207126E-18,
4.46562142029675999901E-17,
3.46122286769746109310E-17,
-2.82762398051658348494E-16,
-3.42548561967721913462E-16,
1.77256013305652638360E-15,
3.81168066935262242075E-15,
-9.55484669882830764870E-15,
-4.15056934728722208663E-14,
1.54008621752140982691E-14,
3.85277838274214270114E-13,
7.18012445138366623367E-13,
-1.79417853150680611778E-12,
-1.32158118404477131188E-11,
-3.14991652796324136454E-11,
1.18891471078464383424E-11,
4.94060238822496958910E-10,
3.39623202570838634515E-9,
2.26666899049817806459E-8,
2.04891858946906374183E-7,
2.89137052083475648297E-6,
6.88975834691682398426E-5,
3.36911647825569408990E-3,
8.04490411014108831608E-1]
def _chbevl(x, vals):
b0 = vals[0]
b1 = 0.0
for i in xrange(1,len(vals)):
b2 = b1
b1 = b0
b0 = x*b1 - b2 + vals[i]
return 0.5*(b0 - b2)
def _i0_1(x):
return exp(x) * _chbevl(x/2.0-2, _i0A)
def _i0_2(x):
return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x)
def i0(x):
x = atleast_1d(x).copy()
y = empty_like(x)
ind = (x<0)
x[ind] = -x[ind]
ind = (x<=8.0)
y[ind] = _i0_1(x[ind])
ind2 = ~ind
y[ind2] = _i0_2(x[ind2])
return y.squeeze()
## End of cephes code for i0
def kaiser(M,beta):
"""kaiser(M, beta) returns a Kaiser window of length M with shape parameter
beta.
"""
from numpy.dual import i0
n = arange(0,M)
alpha = (M-1)/2.0
return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(beta)
def sinc(x):
"""sinc(x) returns sin(pi*x)/(pi*x) at all points of array x.
"""
y = pi* where(x == 0, 1.0e-20, x)
return sin(y)/y
def msort(a):
b = array(a,subok=True,copy=True)
b.sort(0)
return b
def median(a, axis=0, out=None, overwrite_input=False):
"""Compute the median along the specified axis.
Returns the median of the array elements. The median is taken
over the first axis of the array by default, otherwise over
the specified axis.
Parameters
----------
a : array-like
Input array or object that can be converted to an array
axis : {int, None}, optional
Axis along which the medians are computed. The default is to
compute the median along the first dimension. axis=None
returns the median of the flattened array
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
overwrite_input : {False, True}, optional
If True, then allow use of memory of input array (a) for
calculations. The input array will be modified by the call to
median. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. Note that, if overwrite_input is true, and the input
is not already an ndarray, an error will be raised.
Returns
-------
median : ndarray.
A new array holding the result is returned unless out is
specified, in which case a reference to out is returned.
Return datatype is float64 for ints and floats smaller than
float64, or the input datatype otherwise.
See Also
-------
mean
Notes
-----
Given a vector V length N, the median of V is the middle value of
a sorted copy of V (Vs) - i.e. Vs[(N-1)/2], when N is odd. It is
the mean of the two middle values of Vs, when N is even.
Examples
--------
>>> import numpy as np
>>> from numpy import median
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> median(a)
array([ 6.5, 4.5, 2.5])
>>> median(a, axis=None)
3.5
>>> median(a, axis=1)
array([ 7., 2.])
>>> m = median(a)
>>> out = np.zeros_like(m)
>>> median(a, out=m)
array([ 6.5, 4.5, 2.5])
>>> m
array([ 6.5, 4.5, 2.5])
>>> b = a.copy()
>>> median(b, axis=1, overwrite_input=True)
array([ 7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> median(b, axis=None, overwrite_input=True)
3.5
>>> assert not np.all(a==b)
"""
if overwrite_input:
if axis is None:
sorted = a.ravel()
sorted.sort()
else:
a.sort(axis=axis)
sorted = a
else:
sorted = sort(a, axis=axis)
if axis is None:
axis = 0
indexer = [slice(None)] * sorted.ndim
index = int(sorted.shape[axis]/2)
if sorted.shape[axis] % 2 == 1:
# index with slice to allow mean (below) to work
indexer[axis] = slice(index, index+1)
else:
indexer[axis] = slice(index-1, index+1)
# Use mean in odd and even case to coerce data type
# and check, use out array.
return mean(sorted[indexer], axis=axis, out=out)
def trapz(y, x=None, dx=1.0, axis=-1):
"""Integrate y(x) using samples along the given axis and the composite
trapezoidal rule. If x is None, spacing given by dx is assumed.
"""
y = asarray(y)
if x is None:
d = dx
else:
d = diff(x,axis=axis)
nd = len(y.shape)
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1,None)
slice2[axis] = slice(None,-1)
return add.reduce(d * (y[slice1]+y[slice2])/2.0,axis)
#always succeed
def add_newdoc(place, obj, doc):
"""Adds documentation to obj which is in module place.
If doc is a string add it to obj as a docstring
If doc is a tuple, then the first element is interpreted as
an attribute of obj and the second as the docstring
(method, docstring)
If doc is a list, then each element of the list should be a
sequence of length two --> [(method1, docstring1),
(method2, docstring2), ...]
This routine never raises an error.
"""
try:
new = {}
exec 'from %s import %s' % (place, obj) in new
if isinstance(doc, str):
add_docstring(new[obj], doc.strip())
elif isinstance(doc, tuple):
add_docstring(getattr(new[obj], doc[0]), doc[1].strip())
elif isinstance(doc, list):
for val in doc:
add_docstring(getattr(new[obj], val[0]), val[1].strip())
except:
pass
# From matplotlib
def meshgrid(x,y):
"""
For vectors x, y with lengths Nx=len(x) and Ny=len(y), return X, Y
where X and Y are (Ny, Nx) shaped arrays with the elements of x
and y repeated to fill the matrix
EG,
[X, Y] = meshgrid([1,2,3], [4,5,6,7])
X =
1 2 3
1 2 3
1 2 3
1 2 3
Y =
4 4 4
5 5 5
6 6 6
7 7 7
"""
x = asarray(x)
y = asarray(y)
numRows, numCols = len(y), len(x) # yes, reversed
x = x.reshape(1,numCols)
X = x.repeat(numRows, axis=0)
y = y.reshape(numRows,1)
Y = y.repeat(numCols, axis=1)
return X, Y
def delete(arr, obj, axis=None):
"""Return a new array with sub-arrays along an axis deleted.
Return a new array with the sub-arrays (i.e. rows or columns)
deleted along the given axis as specified by obj
obj may be a slice_object (s_[3:5:2]) or an integer
or an array of integers indicated which sub-arrays to
remove.
If axis is None, then ravel the array first.
Examples
--------
>>> arr = [[3,4,5],
... [1,2,3],
... [6,7,8]]
>>> delete(arr, 1, 1)
array([[3, 5],
[1, 3],
[6, 8]])
>>> delete(arr, 1, 0)
array([[3, 4, 5],
[6, 7, 8]])
"""
wrap = None
if type(arr) is not ndarray:
try:
wrap = arr.__array_wrap__
except AttributeError:
pass
arr = asarray(arr)
ndim = arr.ndim
if axis is None:
if ndim != 1:
arr = arr.ravel()
ndim = arr.ndim;
axis = ndim-1;
if ndim == 0:
if wrap:
return wrap(arr)
else:
return arr.copy()
slobj = [slice(None)]*ndim
N = arr.shape[axis]
newshape = list(arr.shape)
if isinstance(obj, (int, long, integer)):
if (obj < 0): obj += N
if (obj < 0 or obj >=N):
raise ValueError, "invalid entry"
newshape[axis]-=1;
new = empty(newshape, arr.dtype, arr.flags.fnc)
slobj[axis] = slice(None, obj)
new[slobj] = arr[slobj]
slobj[axis] = slice(obj,None)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(obj+1,None)
new[slobj] = arr[slobj2]
elif isinstance(obj, slice):
start, stop, step = obj.indices(N)
numtodel = len(xrange(start, stop, step))
if numtodel <= 0:
if wrap:
return wrap(new)
else:
return arr.copy()
newshape[axis] -= numtodel
new = empty(newshape, arr.dtype, arr.flags.fnc)
# copy initial chunk
if start == 0:
pass
else:
slobj[axis] = slice(None, start)
new[slobj] = arr[slobj]
# copy end chunck
if stop == N:
pass
else:
slobj[axis] = slice(stop-numtodel,None)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(stop, None)
new[slobj] = arr[slobj2]
# copy middle pieces
if step == 1:
pass
else: # use array indexing.
obj = arange(start, stop, step, dtype=intp)
all = arange(start, stop, dtype=intp)
obj = setdiff1d(all, obj)
slobj[axis] = slice(start, stop-numtodel)
slobj2 = [slice(None)]*ndim
slobj2[axis] = obj
new[slobj] = arr[slobj2]
else: # default behavior
obj = array(obj, dtype=intp, copy=0, ndmin=1)
all = arange(N, dtype=intp)
obj = setdiff1d(all, obj)
slobj[axis] = obj
new = arr[slobj]
if wrap:
return wrap(new)
else:
return new
def insert(arr, obj, values, axis=None):
"""Return a new array with values inserted along the given axis
before the given indices
If axis is None, then ravel the array first.
The obj argument can be an integer, a slice, or a sequence of
integers.
Examples
--------
>>> a = array([[1,2,3],
... [4,5,6],
... [7,8,9]])
>>> insert(a, [1,2], [[4],[5]], axis=0)
array([[1, 2, 3],
[4, 4, 4],
[4, 5, 6],
[5, 5, 5],
[7, 8, 9]])
"""
wrap = None
if type(arr) is not ndarray:
try:
wrap = arr.__array_wrap__
except AttributeError:
pass
arr = asarray(arr)
ndim = arr.ndim
if axis is None:
if ndim != 1:
arr = arr.ravel()
ndim = arr.ndim
axis = ndim-1
if (ndim == 0):
arr = arr.copy()
arr[...] = values
if wrap:
return wrap(arr)
else:
return arr
slobj = [slice(None)]*ndim
N = arr.shape[axis]
newshape = list(arr.shape)
if isinstance(obj, (int, long, integer)):
if (obj < 0): obj += N
if obj < 0 or obj > N:
raise ValueError, "index (%d) out of range (0<=index<=%d) "\
"in dimension %d" % (obj, N, axis)
newshape[axis] += 1;
new = empty(newshape, arr.dtype, arr.flags.fnc)
slobj[axis] = slice(None, obj)
new[slobj] = arr[slobj]
slobj[axis] = obj
new[slobj] = values
slobj[axis] = slice(obj+1,None)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(obj,None)
new[slobj] = arr[slobj2]
if wrap:
return wrap(new)
return new
elif isinstance(obj, slice):
# turn it into a range object
obj = arange(*obj.indices(N),**{'dtype':intp})
# get two sets of indices
# one is the indices which will hold the new stuff
# two is the indices where arr will be copied over
obj = asarray(obj, dtype=intp)
numnew = len(obj)
index1 = obj + arange(numnew)
index2 = setdiff1d(arange(numnew+N),index1)
newshape[axis] += numnew
new = empty(newshape, arr.dtype, arr.flags.fnc)
slobj2 = [slice(None)]*ndim
slobj[axis] = index1
slobj2[axis] = index2
new[slobj] = values
new[slobj2] = arr
if wrap:
return wrap(new)
return new
def append(arr, values, axis=None):
"""Append to the end of an array along axis (ravel first if None)
"""
arr = asanyarray(arr)
if axis is None:
if arr.ndim != 1:
arr = arr.ravel()
values = ravel(values)
axis = arr.ndim-1
return concatenate((arr, values), axis=axis)
```
#### File: numpy/lib/machar.py
```python
__all__ = ['MachAr']
from numpy.core.fromnumeric import any
from numpy.core.numeric import seterr
# Need to speed this up...especially for longfloat
class MachAr(object):
"""Diagnosing machine parameters.
The following attributes are available:
ibeta - radix in which numbers are represented
it - number of base-ibeta digits in the floating point mantissa M
machep - exponent of the smallest (most negative) power of ibeta that,
added to 1.0,
gives something different from 1.0
eps - floating-point number beta**machep (floating point precision)
negep - exponent of the smallest power of ibeta that, substracted
from 1.0, gives something different from 1.0
epsneg - floating-point number beta**negep
iexp - number of bits in the exponent (including its sign and bias)
minexp - smallest (most negative) power of ibeta consistent with there
being no leading zeros in the mantissa
xmin - floating point number beta**minexp (the smallest (in
magnitude) usable floating value)
maxexp - smallest (positive) power of ibeta that causes overflow
xmax - (1-epsneg)* beta**maxexp (the largest (in magnitude)
usable floating value)
irnd - in range(6), information on what kind of rounding is done
in addition, and on how underflow is handled
ngrd - number of 'guard digits' used when truncating the product
of two mantissas to fit the representation
epsilon - same as eps
tiny - same as xmin
huge - same as xmax
precision - int(-log10(eps))
resolution - 10**(-precision)
Reference:
Numerical Recipies.
"""
def __init__(self, float_conv=float,int_conv=int,
float_to_float=float,
float_to_str = lambda v:'%24.16e' % v,
title = 'Python floating point number'):
"""
float_conv - convert integer to float (array)
int_conv - convert float (array) to integer
float_to_float - convert float array to float
float_to_str - convert array float to str
title - description of used floating point numbers
"""
# We ignore all errors here because we are purposely triggering
# underflow to detect the properties of the runninng arch.
saverrstate = seterr(under='ignore')
try:
self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)
finally:
seterr(**saverrstate)
def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title):
max_iterN = 10000
msg = "Did not converge after %d tries with %s"
one = float_conv(1)
two = one + one
zero = one - one
# Do we really need to do this? Aren't they 2 and 2.0?
# Determine ibeta and beta
a = one
for _ in xrange(max_iterN):
a = a + a
temp = a + one
temp1 = temp - a
if any(temp1 - one != zero):
break
else:
raise RuntimeError, msg % (_, one.dtype)
b = one
for _ in xrange(max_iterN):
b = b + b
temp = a + b
itemp = int_conv(temp-a)
if any(itemp != 0):
break
else:
raise RuntimeError, msg % (_, one.dtype)
ibeta = itemp
beta = float_conv(ibeta)
# Determine it and irnd
it = -1
b = one
for _ in xrange(max_iterN):
it = it + 1
b = b * beta
temp = b + one
temp1 = temp - b
if any(temp1 - one != zero):
break
else:
raise RuntimeError, msg % (_, one.dtype)
betah = beta / two
a = one
for _ in xrange(max_iterN):
a = a + a
temp = a + one
temp1 = temp - a
if any(temp1 - one != zero):
break
else:
raise RuntimeError, msg % (_, one.dtype)
temp = a + betah
irnd = 0
if any(temp-a != zero):
irnd = 1
tempa = a + beta
temp = tempa + betah
if irnd==0 and any(temp-tempa != zero):
irnd = 2
# Determine negep and epsneg
negep = it + 3
betain = one / beta
a = one
for i in range(negep):
a = a * betain
b = a
for _ in xrange(max_iterN):
temp = one - a
if any(temp-one != zero):
break
a = a * beta
negep = negep - 1
# Prevent infinite loop on PPC with gcc 4.0:
if negep < 0:
raise RuntimeError, "could not determine machine tolerance " \
"for 'negep', locals() -> %s" % (locals())
else:
raise RuntimeError, msg % (_, one.dtype)
negep = -negep
epsneg = a
# Determine machep and eps
machep = - it - 3
a = b
for _ in xrange(max_iterN):
temp = one + a
if any(temp-one != zero):
break
a = a * beta
machep = machep + 1
else:
raise RuntimeError, msg % (_, one.dtype)
eps = a
# Determine ngrd
ngrd = 0
temp = one + eps
if irnd==0 and any(temp*one - one != zero):
ngrd = 1
# Determine iexp
i = 0
k = 1
z = betain
t = one + eps
nxres = 0
for _ in xrange(max_iterN):
y = z
z = y*y
a = z*one # Check here for underflow
temp = z*t
if any(a+a == zero) or any(abs(z)>=y):
break
temp1 = temp * betain
if any(temp1*beta == z):
break
i = i + 1
k = k + k
else:
raise RuntimeError, msg % (_, one.dtype)
if ibeta != 10:
iexp = i + 1
mx = k + k
else:
iexp = 2
iz = ibeta
while k >= iz:
iz = iz * ibeta
iexp = iexp + 1
mx = iz + iz - 1
# Determine minexp and xmin
for _ in xrange(max_iterN):
xmin = y
y = y * betain
a = y * one
temp = y * t
if any(a+a != zero) and any(abs(y) < xmin):
k = k + 1
temp1 = temp * betain
if any(temp1*beta == y) and any(temp != y):
nxres = 3
xmin = y
break
else:
break
else:
raise RuntimeError, msg % (_, one.dtype)
minexp = -k
# Determine maxexp, xmax
if mx <= k + k - 3 and ibeta != 10:
mx = mx + mx
iexp = iexp + 1
maxexp = mx + minexp
irnd = irnd + nxres
if irnd >= 2:
maxexp = maxexp - 2
i = maxexp + minexp
if ibeta == 2 and not i:
maxexp = maxexp - 1
if i > 20:
maxexp = maxexp - 1
if any(a != y):
maxexp = maxexp - 2
xmax = one - epsneg
if any(xmax*one != xmax):
xmax = one - beta*epsneg
xmax = xmax / (xmin*beta*beta*beta)
i = maxexp + minexp + 3
for j in range(i):
if ibeta==2:
xmax = xmax + xmax
else:
xmax = xmax * beta
self.ibeta = ibeta
self.it = it
self.negep = negep
self.epsneg = float_to_float(epsneg)
self._str_epsneg = float_to_str(epsneg)
self.machep = machep
self.eps = float_to_float(eps)
self._str_eps = float_to_str(eps)
self.ngrd = ngrd
self.iexp = iexp
self.minexp = minexp
self.xmin = float_to_float(xmin)
self._str_xmin = float_to_str(xmin)
self.maxexp = maxexp
self.xmax = float_to_float(xmax)
self._str_xmax = float_to_str(xmax)
self.irnd = irnd
self.title = title
# Commonly used parameters
self.epsilon = self.eps
self.tiny = self.xmin
self.huge = self.xmax
import math
self.precision = int(-math.log10(float_to_float(self.eps)))
ten = two + two + two + two + two
resolution = ten ** (-self.precision)
self.resolution = float_to_float(resolution)
self._str_resolution = float_to_str(resolution)
def __str__(self):
return '''\
Machine parameters for %(title)s
---------------------------------------------------------------------
ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s
machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon)
negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg)
minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny)
maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge)
---------------------------------------------------------------------
''' % self.__dict__
if __name__ == '__main__':
print MachAr()
```
#### File: site-packages/paramiko/message.py
```python
import struct
import cStringIO
from paramiko import util
class Message (object):
"""
An SSH2 I{Message} is a stream of bytes that encodes some combination of
strings, integers, bools, and infinite-precision integers (known in python
as I{long}s). This class builds or breaks down such a byte stream.
Normally you don't need to deal with anything this low-level, but it's
exposed for people implementing custom extensions, or features that
paramiko doesn't support yet.
"""
def __init__(self, content=None):
"""
Create a new SSH2 Message.
@param content: the byte stream to use as the Message content (passed
in only when decomposing a Message).
@type content: string
"""
if content != None:
self.packet = cStringIO.StringIO(content)
else:
self.packet = cStringIO.StringIO()
def __str__(self):
"""
Return the byte stream content of this Message, as a string.
@return: the contents of this Message.
@rtype: string
"""
return self.packet.getvalue()
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
@rtype: string
"""
return 'paramiko.Message(' + repr(self.packet.getvalue()) + ')'
def rewind(self):
"""
Rewind the message to the beginning as if no items had been parsed
out of it yet.
"""
self.packet.seek(0)
def get_remainder(self):
"""
Return the bytes of this Message that haven't already been parsed and
returned.
@return: a string of the bytes not parsed yet.
@rtype: string
"""
position = self.packet.tell()
remainder = self.packet.read()
self.packet.seek(position)
return remainder
def get_so_far(self):
"""
Returns the bytes of this Message that have been parsed and returned.
The string passed into a Message's constructor can be regenerated by
concatenating C{get_so_far} and L{get_remainder}.
@return: a string of the bytes parsed so far.
@rtype: string
"""
position = self.packet.tell()
self.rewind()
return self.packet.read(position)
def get_bytes(self, n):
"""
Return the next C{n} bytes of the Message, without decomposing into
an int, string, etc. Just the raw bytes are returned.
@return: a string of the next C{n} bytes of the Message, or a string
of C{n} zero bytes, if there aren't C{n} bytes remaining.
@rtype: string
"""
b = self.packet.read(n)
if len(b) < n:
return b + '\x00' * (n - len(b))
return b
def get_byte(self):
"""
Return the next byte of the Message, without decomposing it. This
is equivalent to L{get_bytes(1)<get_bytes>}.
@return: the next byte of the Message, or C{'\000'} if there aren't
any bytes remaining.
@rtype: string
"""
return self.get_bytes(1)
def get_boolean(self):
"""
Fetch a boolean from the stream.
@return: C{True} or C{False} (from the Message).
@rtype: bool
"""
b = self.get_bytes(1)
return b != '\x00'
def get_int(self):
"""
Fetch an int from the stream.
@return: a 32-bit unsigned integer.
@rtype: int
"""
return struct.unpack('>I', self.get_bytes(4))[0]
def get_int64(self):
"""
Fetch a 64-bit int from the stream.
@return: a 64-bit unsigned integer.
@rtype: long
"""
return struct.unpack('>Q', self.get_bytes(8))[0]
def get_mpint(self):
"""
Fetch a long int (mpint) from the stream.
@return: an arbitrary-length integer.
@rtype: long
"""
return util.inflate_long(self.get_string())
def get_string(self):
"""
Fetch a string from the stream. This could be a byte string and may
contain unprintable characters. (It's not unheard of for a string to
contain another byte-stream Message.)
@return: a string.
@rtype: string
"""
return self.get_bytes(self.get_int())
def get_list(self):
"""
Fetch a list of strings from the stream. These are trivially encoded
as comma-separated values in a string.
@return: a list of strings.
@rtype: list of strings
"""
return self.get_string().split(',')
def add_bytes(self, b):
"""
Write bytes to the stream, without any formatting.
@param b: bytes to add
@type b: str
"""
self.packet.write(b)
return self
def add_byte(self, b):
"""
Write a single byte to the stream, without any formatting.
@param b: byte to add
@type b: str
"""
self.packet.write(b)
return self
def add_boolean(self, b):
"""
Add a boolean value to the stream.
@param b: boolean value to add
@type b: bool
"""
if b:
self.add_byte('\x01')
else:
self.add_byte('\x00')
return self
def add_int(self, n):
"""
Add an integer to the stream.
@param n: integer to add
@type n: int
"""
self.packet.write(struct.pack('>I', n))
return self
def add_int64(self, n):
"""
Add a 64-bit int to the stream.
@param n: long int to add
@type n: long
"""
self.packet.write(struct.pack('>Q', n))
return self
def add_mpint(self, z):
"""
Add a long int to the stream, encoded as an infinite-precision
integer. This method only works on positive numbers.
@param z: long int to add
@type z: long
"""
self.add_string(util.deflate_long(z))
return self
def add_string(self, s):
"""
Add a string to the stream.
@param s: string to add
@type s: str
"""
self.add_int(len(s))
self.packet.write(s)
return self
def add_list(self, l):
"""
Add a list of strings to the stream. They are encoded identically to
a single string of values separated by commas. (Yes, really, that's
how SSH2 does it.)
@param l: list of strings to add
@type l: list(str)
"""
self.add_string(','.join(l))
return self
def _add(self, i):
if type(i) is str:
return self.add_string(i)
elif type(i) is int:
return self.add_int(i)
elif type(i) is long:
if i > 0xffffffffL:
return self.add_mpint(i)
else:
return self.add_int(i)
elif type(i) is bool:
return self.add_boolean(i)
elif type(i) is list:
return self.add_list(i)
else:
raise Exception('Unknown type')
def add(self, *seq):
"""
Add a sequence of items to the stream. The values are encoded based
on their type: str, int, bool, list, or long.
@param seq: the sequence of items
@type seq: sequence
@bug: longs are encoded non-deterministically. Don't use this method.
"""
for item in seq:
self._add(item)
```
#### File: site-packages/PIL/FpxImagePlugin.py
```python
__version__ = "0.1"
import string
import Image, ImageFile
from OleFileIO import *
# we map from colour field tuples to (mode, rawmode) descriptors
MODES = {
# opacity
(0x00007ffe): ("A", "L"),
# monochrome
(0x00010000,): ("L", "L"),
(0x00018000, 0x00017ffe): ("RGBA", "LA"),
# photo YCC
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
(0x00028000, 0x00028001, 0x00028002, 0x00027ffe): ("RGBA", "YCCA;P"),
# standard RGB (NIFRGB)
(0x00030000, 0x00030001, 0x00030002): ("RGB","RGB"),
(0x00038000, 0x00038001, 0x00038002, 0x00037ffe): ("RGBA","RGBA"),
}
#
# --------------------------------------------------------------------
def _accept(prefix):
return prefix[:8] == MAGIC
##
# Image plugin for the FlashPix images.
class FpxImageFile(ImageFile.ImageFile):
format = "FPX"
format_description = "FlashPix"
def _open(self):
#
# read the OLE directory and see if this is a likely
# to be a FlashPix file
try:
self.ole = OleFileIO(self.fp)
except IOError:
raise SyntaxError, "not an FPX file; invalid OLE file"
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
raise SyntaxError, "not an FPX file; bad root CLSID"
self._open_index(1)
def _open_index(self, index = 1):
#
# get the Image Contents Property Set
prop = self.ole.getproperties([
"Data Object Store %06d" % index,
"\005Image Contents"
])
# size (highest resolution)
self.size = prop[0x1000002], prop[0x1000003]
size = max(self.size)
i = 1
while size > 64:
size = size / 2
i = i + 1
self.maxid = i - 1
# mode. instead of using a single field for this, flashpix
# requires you to specify the mode for each channel in each
# resolution subimage, and leaves it to the decoder to make
# sure that they all match. for now, we'll cheat and assume
# that this is always the case.
id = self.maxid << 16
s = prop[0x2000002|id]
colors = []
for i in range(i32(s, 4)):
# note: for now, we ignore the "uncalibrated" flag
colors.append(i32(s, 8+i*4) & 0x7fffffff)
self.mode, self.rawmode = MODES[tuple(colors)]
# load JPEG tables, if any
self.jpeg = {}
for i in range(256):
id = 0x3000001|(i << 16)
if prop.has_key(id):
self.jpeg[i] = prop[id]
# print len(self.jpeg), "tables loaded"
self._open_subimage(1, self.maxid)
def _open_subimage(self, index = 1, subimage = 0):
#
# setup tile descriptors for a given subimage
stream = [
"Data Object Store %06d" % index,
"Resolution %04d" % subimage,
"Subimage 0000 Header"
]
fp = self.ole.openstream(stream)
# skip prefix
p = fp.read(28)
# header stream
s = fp.read(36)
size = i32(s, 4), i32(s, 8)
tilecount = i32(s, 12)
tilesize = i32(s, 16), i32(s, 20)
channels = i32(s, 24)
offset = i32(s, 28)
length = i32(s, 32)
# print size, self.mode, self.rawmode
if size != self.size:
raise IOError, "subimage mismatch"
# get tile descriptors
fp.seek(28 + offset)
s = fp.read(i32(s, 12) * length)
x = y = 0
xsize, ysize = size
xtile, ytile = tilesize
self.tile = []
for i in range(0, len(s), length):
compression = i32(s, i+8)
if compression == 0:
self.tile.append(("raw", (x,y,x+xtile,y+ytile),
i32(s, i) + 28, (self.rawmode)))
elif compression == 1:
# FIXME: the fill decoder is not implemented
self.tile.append(("fill", (x,y,x+xtile,y+ytile),
i32(s, i) + 28, (self.rawmode, s[12:16])))
elif compression == 2:
internal_color_conversion = ord(s[14])
jpeg_tables = ord(s[15])
rawmode = self.rawmode
if internal_color_conversion:
# The image is stored as usual (usually YCbCr).
if rawmode == "RGBA":
# For "RGBA", data is stored as YCbCrA based on
# negative RGB. The following trick works around
# this problem :
jpegmode, rawmode = "YCbCrK", "CMYK"
else:
jpegmode = None # let the decoder decide
else:
# The image is stored as defined by rawmode
jpegmode = rawmode
self.tile.append(("jpeg", (x,y,x+xtile,y+ytile),
i32(s, i) + 28, (rawmode, jpegmode)))
# FIXME: jpeg tables are tile dependent; the prefix
# data must be placed in the tile descriptor itself!
if jpeg_tables:
self.tile_prefix = self.jpeg[jpeg_tables]
else:
raise IOError, "unknown/invalid compression"
x = x + xtile
if x >= xsize:
x, y = 0, y + ytile
if y >= ysize:
break # isn't really required
self.stream = stream
self.fp = None
def load(self):
if not self.fp:
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
ImageFile.ImageFile.load(self)
#
# --------------------------------------------------------------------
Image.register_open("FPX", FpxImageFile, _accept)
Image.register_extension("FPX", ".fpx")
```
#### File: site-packages/PIL/ImageSequence.py
```python
class Iterator:
##
# Create an iterator.
#
# @param im An image object.
def __init__(self, im):
if not hasattr(im, "seek"):
raise AttributeError("im must have seek method")
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
raise IndexError # end of sequence
```
#### File: site-packages/PIL/SpiderImagePlugin.py
```python
import Image, ImageFile
import os, string, struct, sys
def isInt(f):
try:
i = int(f)
if f-i == 0: return 1
else: return 0
except:
return 0
iforms = [1,3,-11,-12,-21,-22]
# There is no magic number to identify Spider files, so just check a
# series of header locations to see if they have reasonable values.
# Returns no.of bytes in the header, if it is a valid Spider header,
# otherwise returns 0
def isSpiderHeader(t):
h = (99,) + t # add 1 value so can use spider header index start=1
# header values 1,2,5,12,13,22,23 should be integers
if not isInt(h[1]): return 0
if not isInt(h[2]): return 0
if not isInt(h[5]): return 0
if not isInt(h[12]): return 0
if not isInt(h[13]): return 0
if not isInt(h[22]): return 0
if not isInt(h[23]): return 0
# check iform
iform = int(h[5])
if not iform in iforms: return 0
# check other header values
labrec = int(h[13]) # no. records in file header
labbyt = int(h[22]) # total no. of bytes in header
lenbyt = int(h[23]) # record length in bytes
#print "labrec = %d, labbyt = %d, lenbyt = %d" % (labrec,labbyt,lenbyt)
if labbyt != (labrec * lenbyt): return 0
# looks like a valid header
return labbyt
def isSpiderImage(filename):
fp = open(filename,'rb')
f = fp.read(92) # read 23 * 4 bytes
fp.close()
bigendian = 1
t = struct.unpack('>23f',f) # try big-endian first
hdrlen = isSpiderHeader(t)
if hdrlen == 0:
bigendian = 0
t = struct.unpack('<23f',f) # little-endian
hdrlen = isSpiderHeader(t)
return hdrlen
class SpiderImageFile(ImageFile.ImageFile):
format = "SPIDER"
format_description = "Spider 2D image"
def _open(self):
# check header
n = 23 * 4 # read 23 float values
f = self.fp.read(n)
try:
self.bigendian = 1
t = struct.unpack('>23f',f) # try big-endian first
hdrlen = isSpiderHeader(t)
if hdrlen == 0:
self.bigendian = 0
t = struct.unpack('<23f',f) # little-endian
hdrlen = isSpiderHeader(t)
if hdrlen == 0:
raise SyntaxError, "not a valid Spider file"
except struct.error:
raise SyntaxError, "not a valid Spider file"
# size in pixels (width, height)
h = (99,) + t # add 1 value cos' spider header index starts at 1
iform = int(h[5])
if iform != 1:
raise SyntaxError, "not a Spider 2D image"
self.size = int(h[12]), int(h[2])
if self.bigendian:
self.rawmode = "F;32BF"
else:
self.rawmode = "F;32F"
self.mode = "F"
self.tile = [("raw", (0, 0) + self.size, hdrlen,
(self.rawmode, 0, 1))]
# returns a byte image after rescaling to 0..255
def convert2byte(self, depth=255):
(min, max) = self.getextrema()
m = 1
if max != min:
m = depth / (max-min)
b = -m * min
return self.point(lambda i, m=m, b=b: i * m + b).convert("L")
# returns a ImageTk.PhotoImage object, after rescaling to 0..255
def tkPhotoImage(self):
import ImageTk
return ImageTk.PhotoImage(self.convert2byte(), palette=256)
# --------------------------------------------------------------------
# Image series
# given a list of filenames, return a list of images
def loadImageSeries(filelist=None):
" create a list of Image.images for use in montage "
if filelist == None or len(filelist) < 1:
return
imglist = []
for img in filelist:
if not os.path.exists(img):
print "unable to find %s" % img
continue
try:
im = Image.open(img).convert2byte()
except:
if not isSpiderImage(img):
print img + " is not a Spider image file"
continue
im.info['filename'] = img
imglist.append(im)
return imglist
# --------------------------------------------------------------------
Image.register_open("SPIDER", SpiderImageFile)
if __name__ == "__main__":
if not sys.argv[1:]:
print "Syntax: python SpiderImagePlugin.py imagefile"
sys.exit(1)
filename = sys.argv[1]
#Image.register_open("SPIDER", SpiderImageFile)
im = Image.open(filename)
print "image: " + str(im)
print "format: " + str(im.format)
print "size: " + str(im.size)
print "mode: " + str(im.mode)
print "max, min: ",
print im.getextrema()
```
#### File: Pmw_1_3/demos/LabeledWidget.py
```python
title = 'Pmw.LabeledWidget demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create a frame to put the LabeledWidgets into
frame = Tkinter.Frame(parent, background = 'grey90')
frame.pack(fill = 'both', expand = 1)
# Create and pack the LabeledWidgets.
column = 0
row = 0
for pos in ('n', 'nw', 'wn', 'w'):
lw = Pmw.LabeledWidget(frame,
labelpos = pos,
label_text = pos + ' label')
lw.component('hull').configure(relief='sunken', borderwidth=2)
lw.grid(column=column, row=row, padx=10, pady=10)
cw = Tkinter.Button(lw.interior(), text='child\nsite')
cw.pack(padx=10, pady=10, expand='yes', fill='both')
# Get ready for next grid position.
column = column + 1
if column == 2:
column = 0
row = row + 1
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
widget = Demo(root)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack()
root.mainloop()
```
#### File: Pmw_1_3/demos/NoteBook_2.py
```python
title = 'Pmw.NoteBook demonstration (more complex)'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent, withTabs = 1):
# Repeat random number sequence for each run.
self.rand = 12345
# Default demo is to display a tabbed notebook.
self.withTabs = withTabs
# Create a frame to put everything in
self.mainframe = Tkinter.Frame(parent)
self.mainframe.pack(fill = 'both', expand = 1)
# Find current default colors
button = Tkinter.Button()
defaultbg = button.cget('background')
defaultfg = button.cget('foreground')
button.destroy()
# Create the list of colors to cycle through
self.colorList = []
self.colorList.append((defaultbg, defaultfg))
self.colorIndex = 0
for color in Pmw.Color.spectrum(6, 1.5, 1.0, 1.0, 1):
bg = Pmw.Color.changebrightness(self.mainframe, color, 0.85)
self.colorList.append((bg, 'black'))
bg = Pmw.Color.changebrightness(self.mainframe, color, 0.55)
self.colorList.append((bg, 'white'))
# Set the color to the current default
Pmw.Color.changecolor(self.mainframe, defaultbg, foreground = defaultfg)
defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe)
Pmw.Color.setscheme(self.mainframe, defaultbg, foreground = defaultfg)
# Create the notebook, but don't pack it yet.
if self.withTabs:
tabpos = 'n'
else:
tabpos = None
self.notebook = Pmw.NoteBook(self.mainframe,
tabpos = tabpos,
createcommand = PrintOne('Create'),
lowercommand = PrintOne('Lower'),
raisecommand = PrintOne('Raise'),
hull_width = 300,
hull_height = 200,
)
# Create a buttonbox to configure the notebook and pack it first.
buttonbox = Pmw.ButtonBox(self.mainframe)
buttonbox.pack(side = 'bottom', fill = 'x')
# Add some buttons to the buttonbox to configure the notebook.
buttonbox.add('Insert\npage', command = self.insertpage)
buttonbox.add('Delete\npage', command = self.deletepage)
buttonbox.add('Add\nbutton', command = self.addbutton)
buttonbox.add('Change\ncolor', command = self.changecolor)
buttonbox.add('Natural\nsize', command =
self.notebook.setnaturalsize)
if not self.withTabs:
# Create the selection widget to select the page in the notebook.
self.optionmenu = Pmw.OptionMenu(self.mainframe,
menubutton_width = 10,
command = self.notebook.selectpage
)
self.optionmenu.pack(side = 'left', padx = 10)
# Pack the notebook last so that the buttonbox does not disappear
# when the window is made smaller.
self.notebook.pack(fill = 'both', expand = 1, padx = 5, pady = 5)
# Populate some pages of the notebook.
page = self.notebook.add('tmp')
self.notebook.delete('tmp')
page = self.notebook.add('Appearance')
if self.withTabs:
self.notebook.tab('Appearance').focus_set()
button = Tkinter.Button(page,
text = 'Welcome\nto\nthe\nAppearance\npage')
button.pack(expand = 1)
page = self.notebook.add('Fonts')
button = Tkinter.Button(page,
text = 'This is a very very very very wide Fonts page')
button.pack(expand = 1)
page = self.notebook.insert('Applications', before = 'Fonts')
button = Tkinter.Button(page, text = 'This is the Applications page')
button.pack(expand = 1)
# Initialise the first page and the initial colour.
if not self.withTabs:
self.optionmenu.setitems(self.notebook.pagenames())
apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette)
self.pageCounter = 0
def insertpage(self):
# Create a page at a random position
defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe)
bg, fg = self.colorList[self.colorIndex]
Pmw.Color.setscheme(self.mainframe, bg, foreground = fg)
self.pageCounter = self.pageCounter + 1
before = self.randomchoice(self.notebook.pagenames() + [Pmw.END])
pageName = 'page%d' % self.pageCounter
if self.pageCounter % 5 == 0:
tab_text = pageName + '\nline two'
else:
tab_text = pageName
classes = (None, Tkinter.Button, Tkinter.Label, Tkinter.Checkbutton)
cls = self.randomchoice((None,) + classes)
if cls is None:
print 'Adding', pageName, 'as a frame with a button'
if self.withTabs:
page = self.notebook.insert(pageName, before, tab_text = tab_text)
else:
page = self.notebook.insert(pageName, before)
button = Tkinter.Button(page,
text = 'This is button %d' % self.pageCounter)
button.pack(expand = 1)
else:
print 'Adding', pageName, 'using', cls
if self.withTabs:
page = self.notebook.insert(pageName, before,
tab_text = tab_text,
page_pyclass = cls,
page_text = 'This is a page using\na %s' % str(cls)
)
else:
page = self.notebook.insert(pageName, before,
page_pyclass = cls,
page_text = 'This is a page using\na %s' % str(cls)
)
if not self.withTabs:
self.optionmenu.setitems(
self.notebook.pagenames(), self.notebook.getcurselection())
apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette)
def addbutton(self):
# Add a button to a random page.
defaultPalette = Pmw.Color.getdefaultpalette(self.mainframe)
bg, fg = self.colorList[self.colorIndex]
Pmw.Color.setscheme(self.mainframe, bg, foreground = fg)
framePages = []
for pageName in self.notebook.pagenames():
page = self.notebook.page(pageName)
if page.__class__ == Tkinter.Frame:
framePages.append(pageName)
if len(framePages) == 0:
self.notebook.bell()
return
pageName = self.randomchoice(framePages)
print 'Adding extra button to', pageName
page = self.notebook.page(pageName)
button = Tkinter.Button(page, text = 'This is an extra button')
button.pack(expand = 1)
apply(Pmw.Color.setscheme, (self.mainframe,), defaultPalette)
def deletepage(self):
# Delete a random page
pageNames = self.notebook.pagenames()
if len(pageNames) == 0:
self.notebook.bell()
return
pageName = self.randomchoice(pageNames)
print 'Deleting', pageName
self.notebook.delete(pageName)
if not self.withTabs:
self.optionmenu.setitems(
self.notebook.pagenames(), self.notebook.getcurselection())
def changecolor(self):
self.colorIndex = self.colorIndex + 1
if self.colorIndex == len(self.colorList):
self.colorIndex = 0
bg, fg = self.colorList[self.colorIndex]
print 'Changing color to', bg
Pmw.Color.changecolor(self.mainframe, bg, foreground = fg)
self.notebook.recolorborders()
# Simple random number generator.
def randomchoice(self, selection):
num = len(selection)
self.rand = (self.rand * 125) % 2796203
index = self.rand % num
return selection[index]
class PrintOne:
def __init__(self, text):
self.text = text
def __call__(self, text):
print self.text, text
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
widget = Demo(root)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack()
root.mainloop()
```
#### File: Pmw_1_3/demos/OptionMenu.py
```python
title = 'Pmw.OptionMenu demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create and pack the OptionMenu megawidgets.
# The first one has a textvariable.
self.var = Tkinter.StringVar()
self.var.set('steamed')
self.method_menu = Pmw.OptionMenu(parent,
labelpos = 'w',
label_text = 'Choose method:',
menubutton_textvariable = self.var,
items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'],
menubutton_width = 10,
)
self.method_menu.pack(anchor = 'w', padx = 10, pady = 10)
self.vege_menu = Pmw.OptionMenu (parent,
labelpos = 'w',
label_text = 'Choose vegetable:',
items = ('broccoli', 'peas', 'carrots', 'pumpkin'),
menubutton_width = 10,
command = self._printOrder,
)
self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10)
self.direction_menu = Pmw.OptionMenu (parent,
labelpos = 'w',
label_text = 'Menu direction:',
items = ('flush', 'above', 'below', 'left', 'right'),
menubutton_width = 10,
command = self._changeDirection,
)
self.direction_menu.pack(anchor = 'w', padx = 10, pady = 10)
menus = (self.method_menu, self.vege_menu, self.direction_menu)
Pmw.alignlabels(menus)
def _printOrder(self, vege):
# Can use 'self.var.get()' instead of 'getcurselection()'.
print 'You have chosen %s %s.' % \
(self.method_menu.getcurselection(), vege)
def _changeDirection(self, direction):
for menu in (self.method_menu, self.vege_menu, self.direction_menu):
menu.configure(menubutton_direction = direction)
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack(side = 'bottom')
widget = Demo(root)
root.mainloop()
```
#### File: Pmw_1_3/demos/SelectionDialog.py
```python
title = 'Pmw.SelectionDialog demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create the dialog.
self.dialog = Pmw.SelectionDialog(parent,
title = 'My SelectionDialog',
buttons = ('OK', 'Cancel'),
defaultbutton = 'OK',
scrolledlist_labelpos = 'n',
label_text = 'What do you think of Pmw?',
scrolledlist_items = ('Cool man', 'Cool', 'Good', 'Bad', 'Gross'),
command = self.execute)
self.dialog.withdraw()
# Create button to launch the dialog.
w = Tkinter.Button(parent, text = 'Show selection dialog',
command = self.dialog.activate)
w.pack(padx = 8, pady = 8)
def execute(self, result):
sels = self.dialog.getcurselection()
if len(sels) == 0:
print 'You clicked on', result, '(no selection)'
else:
print 'You clicked on', result, sels[0]
self.dialog.deactivate(result)
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack(side = 'bottom')
widget = Demo(root)
root.mainloop()
```
#### File: Pmw_1_3/demos/ShowBusy.py
```python
title = 'Blt busy cursor demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent):
self.parent = parent
if Pmw.Blt.havebltbusy(parent):
text = 'Click here to show the\nbusy cursor for one second.'
else:
text = 'Sorry\n' \
'Either the BLT package has not\n' \
'been installed on this system or\n' \
'it does not support the busy command.\n' \
'Clicking on this button will pause\n' \
'for one second but will not display\n' \
'the busy cursor.'
button = Tkinter.Button(parent,
text = text,
command = Pmw.busycallback(self.sleep, parent.update))
button.pack(padx = 10, pady = 10)
entry = Tkinter.Entry(parent, width = 30)
entry.insert('end', 'Try to enter some text while busy.')
entry.pack(padx = 10, pady = 10)
def sleep(self):
self.parent.after(1000)
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack(side = 'bottom')
widget = Demo(root)
root.mainloop()
```
#### File: site-packages/TkTreectrl/MultiListbox.py
```python
from Treectrl import Treectrl
class MultiListbox(Treectrl):
'''A flexible multi column listbox widget for Tkinter.
Based on the Treectrl widget, it offers the following additional configuration options:
columns - a sequence of strings that defines the number of columns of the widget.
The strings will be used in the columnheader lines (default: (' ',)).
command - an optional command that will be executed when the user double-clicks
into the listbox or presses the Return key. The listbox index of the item
that was clicked on resp. of the currently active item is passed as argument
to the callback; if there is no item at the event coordinates resp.
no active item exists, this index will be -1 (default: None).
expandcolumns - a sequence of integers defining the columns that should expand
horizontally beyond the requested size when the widget is resized
(note that the rightmost column will always expand) (default: ()).
selectcmd - an optional callback that will be executed when the selection of the
listbox changes. A tuple containing the indices of the currently
selected items as returned by curselection() will be passed to the
callback (default: None).
selectbackground - the background color to use for the selection rectangle (default: #00008B).
selectforeground - the foreground color to use for selected text (default: white).
By default, the widget uses one pre-defined style for all columns; the widget's style()
method allows to access and configure the default style, as well as applying new
user-defined styles per column.
The default style defines two elements, "text" and "select" (which describes attributes
of the selection rectangle); these may be accessed and configured with the element() method.
Conversion between listbox indices and treectrl item descriptors can be done with the item()
and index() widget methods.
Besides this, most common operations can be done with methods identical or very similar to
those of a Tkinter.Listbox, with the exception of the selection_xxx() methods, where
the treectrl methods are kept intact; for Tkinter.Listbox alike methods, use select_xxx().
'''
def __init__(self, master=None, columns=(' ',), selectcmd=None, command=None,
expandcolumns=(), showroot=0, selectforeground='white',
selectbackground='#00008B', **kw):
Treectrl.__init__(self, master, showroot=showroot, **kw)
self._multilistbox_opts = {'selectcmd' : selectcmd,
'command' : command,
'expandcolumns' : expandcolumns,
'columns' : columns,
'selectforeground' : selectforeground,
'selectbackground' : selectbackground}
self._el_text = self.element_create(type='text',
fill=(self._multilistbox_opts['selectforeground'], 'selected'), lines=1)
self._el_select = self.element_create(type='rect', showfocus=1,
fill=(self._multilistbox_opts['selectbackground'], 'selected'))
self._defaultstyle = self.style_create()
self.style_elements(self._defaultstyle, self._el_select, self._el_text)
self.style_layout(self._defaultstyle, self._el_text, padx=4, iexpand='e', expand='ns')
self.style_layout(self._defaultstyle, self._el_select, union=(self._el_text,), ipady=1, iexpand='nsew')
self._columns = []
self._styles = []
self.configure(columns=columns, expandcolumns=expandcolumns,
selectcmd=selectcmd, command=command)
self.notify_bind('<Selection>', self._call_selectcmd)
self.bind('<Double-Button-1>', self._call_command)
self.bind('<Return>', self._call_command)
##################################################################################
## hackish implementation of configure() and friends for special widget options ##
##################################################################################
def _configure_multilistbox(self, option, value):
if option in ('selectcmd', 'command'):
if not (value is None or callable(value)):
raise ValueError, 'bad value for "%s" option: must be callable or None.' % option
elif option =='selectforeground':
self.element_configure(self._el_text, fill=(value, 'selected'))
elif option == 'selectbackground':
self.element_configure(self._el_select, fill=(value, 'selected'))
elif option == 'expandcolumns':
if not (isinstance(value, tuple) or isinstance(value, list)):
raise ValueError, 'bad value for "expandcolumns" option: must be tuple or list.'
value = tuple(value)
# the last column should always expand
expandcolumns = [x for x in value] + [len(self._columns) - 1]
for column in self._columns:
if self._columns.index(column) in expandcolumns:
self.column_config(column, expand=1)
else:
self.column_config(column, expand=0)
elif option == 'columns':
# if the number of strings in value is identical with the number
# of already existing columns, simply update the columnheader strings
# if there are more items in value, add the missing columns
# else remove the excess columns
if not isinstance(value, tuple) or isinstance(value, list):
raise ValueError, 'bad value for "columns" option: must be tuple or list.'
if not value:
raise ValueError, 'bad value for "columns" option: at least one column must be specified.'
value = tuple(value)
index = 0
while index < len(value) and index < len(self._columns):
# change title of existing columns
self.column_config(self.column(index), text=value[index])
index += 1
if len(value) != len(self._columns):
while self._columns[index:]:
# remove the no longer wanted columns
self.column_delete(self.column(index))
del self._columns[index]
del self._styles[index]
while value[index:]:
# create newly requested columns
newcol = self.column_create(text=value[index], minwidth=35)
self._styles.append(self._defaultstyle)
self._columns.append(newcol)
index += 1
# the number of columns has changed, so we need to update the
# resize and expand options for each column and update the widget's
# defaultstyle option
self.configure(defaultstyle=tuple(self._styles))
for col in self._columns[:-1]:
self.column_configure(col, resize=1)
self.column_configure(self.column('end'), resize=0)
self._configure_multilistbox('expandcolumns', self._multilistbox_opts['expandcolumns'])
# apply the new value to the option dict
self._multilistbox_opts[option] = value
def configure(self, cnf=None, **kw):
for opt in self._multilistbox_opts.keys():
if not cnf is None and cnf.has_key(opt):
self._configure_multilistbox(opt, cnf[opt])
del cnf[opt]
if kw.has_key(opt):
self._configure_multilistbox(opt, kw[opt])
del kw[opt]
return Treectrl.configure(self, cnf, **kw)
config = configure
def cget(self, key):
if key in self._multilistbox_opts.keys():
return self._multilistbox_opts[key]
return Treectrl.cget(self, key)
__getitem__ = cget
def keys(self):
keys = Treectrl.keys(self) + self._multilistbox_opts.keys()
keys.sort()
return keys
########################################################################
# miscellaneous helper methods #
########################################################################
def _call_selectcmd(self, event):
if self._multilistbox_opts['selectcmd']:
sel = self.curselection()
self._multilistbox_opts['selectcmd'](sel)
return 'break'
def _call_command(self, event):
if self._multilistbox_opts['command']:
if event.keysym == 'Return':
index = self.index('active')
else:
index = self._event_index(event)
self._multilistbox_opts['command'](index)
return 'break'
def _event_index(self, event):
'''Return the listbox index where mouse event EVENT occured, or -1 if
it occured in an empty listbox or below the last item.'''
x, y = event.x, event.y
xy = '@%d,%d' % (x, y)
return self.index(xy)
def _index2item(self, index):
if index < 0:
return None
if index == 'end':
index = self.size() - 1
items = self.item_children('root')
if not items:
return None
try:
item = items[index]
except IndexError:
item = None
return item
def _item2index(self, item):
# some treectrl methods return item descriptors as strings
# so try to convert item into an integer first
try:
item = int(item)
except ValueError:
pass
items = list(self.item_children('root'))
index = -1
if item in items:
index = items.index(item)
return index
def _get(self, index):
item = self._index2item(index)
res = []
i = 0
for column in self._columns:
t = self.itemelement_cget(item, column, self._el_text, 'text')
res.append(t)
return tuple(res)
############################################################################
# PUBLIC METHODS #
############################################################################
def column(self, index):
'''Return the column identifier for the column at INDEX.'''
if index == 'end':
index = len(self._columns) - 1
return self._columns[index]
def element(self, element):
'''Return the treectrl element corresponding to ELEMENT.
ELEMENT may be "text" or "select".'''
if element == 'text':
return self._el_text
elif element == 'select':
return self._el_select
def item(self, index):
'''Return the treectrl item descriptor for the item at INDEX.'''
return self._index2item(index)
def numcolumns(self):
'''Return the number of listbox columns.'''
return len(self._columns)
def sort(self, column=None, element=None, first=None, last=None, mode=None,
command=None, notreally=0):
'''Like item_sort(), except that the item descriptor defaults to ROOT
(which is most likely wanted) and that the FIRST and LAST options require
listbox indices instead of treectrl item descriptors.'''
if not first is None:
first = self._index2item(first)
if not last is None:
last = self._index2item(last)
self.item_sort('root', column, element, first, last, mode, command, notreally)
def style(self, index, newstyle=None):
'''If NEWSTYLE is specified, set the style for the column at INDEX to NEWSTYLE.
Return the style identifier for the column at INDEX.'''
if not newstyle is None:
self._styles[index] = newstyle
self.configure(defaultstyle=tuple(self._styles))
return self._styles[index]
############################################################################
# Standard Listbox methods #
############################################################################
def activate(self, index):
'''Like Tkinter.Listbox.activate(). Note that this overrides the activate()
method inherited from Treectrl.'''
item = self._index2item(index)
if not item is None:
Treectrl.activate(self, item)
def bbox(self, index, column=None, element=None):
'''Like item_bbox(), except that it requires a listbox index instead
of a treectrl item descriptor as argument. Note that this overrides the
bbox() method inherited from Treectrl.'''
item = self._index2item(index)
if not item is None:
return self.item_bbox(item, column, element)
def curselection(self):
'''Like Tkinter.Listbox.curselection().'''
selected = self.selection_get()
if not selected:
return ()
selected = list(selected)
if 0 in selected:
# happens if showroot == 1 and the root item is selected
selected.remove(0)
allitems = list(self.item_children('root'))
sel = []
for s in selected:
sel.append(allitems.index(s))
sel.sort()
return tuple(sel)
def delete(self, first, last=None):
'''Like Tkinter.Listbox.delete() except that an additional index descriptor
ALL may be used, so that delete(ALL) is equivalent with delete(0, END).'''
if first == 'all':
self.item_delete('all')
elif (first == 0) and (last == 'end'):
self.item_delete('all')
elif last is None:
self.item_delete(self._index2item(first))
else:
if last == 'end':
last = self.size() - 1
self.item_delete(self._index2item(first), self._index2item(last))
def get(self, first, last=None):
'''Like Tkinter.Listbox.get(), except that each element of the returned tuple
is a tuple instead of a string; each of these tuples contains the text strings
per column of a listbox item.'''
if self.size() == 0:
return ()
if last is None:
return (self._get(first),)
if last == 'end':
last = self.size() - 1
res = []
while first <= last:
res.append(self._get(first))
first += 1
return tuple(res)
def index(self, which=None, item=None):
''' Like Tkinter.Listbox.index(), except that if ITEM is specified, the
listbox index for the treectrl item descriptor ITEM is returned. '''
if not item is None:
return self._item2index(item)
items = self.item_children('root')
if items:
if which == 'active':
for item in items:
if self.itemstate_get(item, 'active'):
return self._item2index(item)
elif which == 'end':
return self.size()
elif isinstance(which, int):
return which
elif which.startswith('@'):
which = which[1:]
x, y = which.split(',')
x, y = int(x.strip()), int(y.strip())
info = self.identify(x, y)
if info and info[0] == 'item':
item = info[1]
return self._item2index(int(item))
return -1
def insert(self, index, *args):
'''Similar to Tkinter.Listbox.insert(), except that instead of one string
a number of strings equal to the number of columns must be given as arguments.
It is an error to specify more or fewer arguments than the number of columns.
Returns the ID of the newly created item, as returned by item_create().'''
olditems = self.item_children('root')
if not olditems:
newitem = self.item_create(parent='root')[0]
elif (index == 'end') or (index > self.size() - 1):
newitem = self.item_create(prevsibling=olditems[-1])[0]
else:
newitem = self.item_create(nextsibling=olditems[index])[0]
i = 0
for column in self._columns:
newtext = args[i]
self.itemelement_config(newitem, column, self._el_text, text=newtext)
i += 1
return newitem
def nearest(self, y):
'''Like Tkinter.Listbox.nearest().'''
size = self.size()
# if the listbox is empty this will always return -1
if size == 0:
return -1
# if there is only one item, always return 0
elif size == 1:
return 0
# listbox contains two or more items, find if y hits one of them exactly;
# if the x coord for identify() is in the border decoration, identify returns (),
# so we cannot use x=0 here, but have to move a few pixels further
# sometimes cget() returns TclObjects instead of strings, so do str() here first:
x = int(str(self['borderwidth'])) + int(str(self['highlightthickness'])) + 1
info = self.identify(x, y)
if info and info[0] == 'item':
return self._item2index(int(info[1]))
# y must be above the first or below the last item
x0, y0, x1, y1 = self.bbox(0)
if y <= y0:
return 0
return size - 1
def see(self, index, column=None, center=None):
'''Like Tkinter.Listbox.see(). Note that this overrides the
see() method inherited from Treectrl.'''
item = self._index2item(index)
if not item is None:
Treectrl.see(self, item, column, center)
def select_anchor(self, index=None):
'''Like Tkinter.Listbox.select_anchor(), except that it if no INDEX is specified
the current selection anchor will be returned.'''
if index is None:
anchor = self.selection_anchor()
else:
item = self._index2item(index)
anchor = self.selection_anchor(item)
if not anchor is None:
return self._item2index(anchor)
def select_clear(self, first=None, last=None):
'''Like Tkinter.Listbox.select_clear(), except that if no arguments are
specified, all items will be deleted, so that select_clear() is equivalent
with select-clear(0, END).'''
if first == 'all':
self.selection_clear('all')
if not first is None:
first = self._index2item(first)
if not last is None:
last = self._index2item(last)
self.selection_clear(first, last)
def select_includes(self, index):
'''Like Tkinter.Listbox.select_includes().'''
item = self._index2item(index)
if not item is None:
return self.selection_includes(item)
return 0
def select_set(self, first, last=None):
'''Like Tkinter.Listbox.select_set().'''
if first == 'all':
self.selection_modify(select='all')
elif (first == 0) and (last == 'end'):
self.selection_modify(select='all')
elif last is None:
self.selection_modify(select=(self._index2item(first),))
else:
if last == 'end':
last = self.size() - 1
newsel = self.item_children('root')[first:last+1]
self.selection_modify(select=newsel)
def size(self):
'''Like Tkinter.Listbox.size().'''
return len(self.item_children('root'))
```
#### File: site-packages/TkTreectrl/ScrolledTreectrl.py
```python
import Tkinter
import Treectrl
import MultiListbox
class ScrolledWidget(Tkinter.Frame):
'''Base class for Tkinter widgets with scrollbars.
The widget is a standard Tkinter.Frame with an additional configuration option
SCROLLMODE which may be one of "x", "y", "both" or "auto".
If SCROLLMODE is one of "x", "y" or "both", one or two static scrollbars will be
drawn. If SCROLLMODE is set to "auto", two automatic scrollbars that appear only
if needed will be drawn.
The Scrollbar widgets can be accessed with the hbar and vbar class attributes.
Derived classes must override the _setScrolledWidget() method, which must return
the widget that will be scrolled and should add a class attribute that allows
to access this widget, so the _setScrolledWidget() method for a ScrolledListbox
widget might look like:
def _setScrolledWidget(self):
self.listbox = Tkinter.Listbox(self)
return self.listbox
Note that although it should be possible to create scrolled widget classes for
virtually any Listbox or Canvas alike Tkinter widget you can *not* safely use
this class to add automatic scrollbars to a Text or Text alike widget.
This is because in a scrolled Text widget the value of the horizontal scrollbar
depends only on the visible part of the Text, not on it's whole contents.
Thus it may happen that it is the last visible line of text that causes the
automatic scrollbar to be mapped which then hides this last line so it will be
unmapped again, but then it is requested again and gets mapped and so on forever.
There are strategies to avoid this, but usually at the cost that there will be
situations where the horizontal scrollbar remains mapped although it is actually
not needed. In order to acomplish this with the ScrolledWidget class, at least
the _scrollXNow() and _scrollBothNow() methods must be overridden with appropriate
handlers.
'''
def __init__(self, master=None, scrollmode='auto', **kw):
if not kw.has_key('width'):
kw['width'] = 400
if not kw.has_key('height'):
kw['height'] = 300
Tkinter.Frame.__init__(self, master, **kw)
# call grid_propagate(0) so the widget will not change its size
# when the scrollbars are mapped or unmapped; that is why we need
# to specify width and height in any case
self.grid_propagate(0)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self._scrollmode = scrollmode
self._scrolledWidget = self._setScrolledWidget()
self._scrolledWidget.grid(row=0, column=0, sticky='news')
self.vbar = Tkinter.Scrollbar(self, orient='vertical', command=self._scrolledWidget.yview)
self.vbar.grid(row=0, column=1, sticky='ns')
self.hbar = Tkinter.Scrollbar(self, orient='horizontal', command=self._scrolledWidget.xview)
self.hbar.grid(row=1, column=0, sticky='ew')
# Initialise instance variables.
self._hbarOn = 1
self._vbarOn = 1
self._scrollTimer = None
self._scrollRecurse = 0
self._hbarNeeded = 0
self._vbarNeeded = 0
self._scrollMode(scrollmode)
def _setScrolledWidget(self):
'''This method must be overridden in derived classes.
It must return the widget that should be scrolled and should
add a reference to the ScrolledWidget object, so it can be accessed
by the user. For example, to create a scrolled Listbox, do:
self.listbox = Tkinter.Listbox(self)
return self.listbox'''
pass
# hack: add "scrollmode" to user configurable options
def configure(self, cnf=None, **kw):
if not cnf is None and cnf.has_key('scrollmode'):
self._scrollMode(cnf['scrollmode'])
del cnf['scrollmode']
if kw.has_key('scrollmode'):
self._scrollMode(kw['scrollmode'])
del kw['scrollmode']
return Tkinter.Frame.configure(self, cnf, **kw)
config = configure
def cget(self, key):
if key == 'scrollmode':
return self._scrollmode
return Tkinter.Frame.cget(self, key)
__getitem__ = cget
def keys(self):
keys = Tkinter.Frame.keys(self) + ['scrollmode']
keys.sort()
return keys
# methods to control the scrollbars;
# these are mainly stolen from Pmw.ScrolledListbox
def _scrollMode(self, mode):
if mode == 'both':
if not self._hbarOn:
self._toggleHbar()
if not self._vbarOn:
self._toggleVbar()
elif mode == 'auto':
if self._hbarNeeded != self._hbarOn:
self._toggleHbar()
if self._vbarNeeded != self._vbarOn:
self._toggleVbar()
elif mode == 'x':
if self._vbarOn:
self._toggleVbar()
elif mode == 'y':
if self._hbarOn:
self._toggleHbar()
else:
message = 'bad scrollmode option "%s": should be x, y, both or auto' % mode
raise ValueError, message
self._scrollmode = mode
self._configureScrollCommands()
def _configureScrollCommands(self):
# Clean up previous scroll commands to prevent memory leak.
tclCommandName = str(self._scrolledWidget.cget('xscrollcommand'))
if tclCommandName != '':
self._scrolledWidget.deletecommand(tclCommandName)
tclCommandName = str(self._scrolledWidget.cget('yscrollcommand'))
if tclCommandName != '':
self._scrolledWidget.deletecommand(tclCommandName)
# If both scrollmodes are not dynamic we can save a lot of
# time by not having to create an idle job to handle the
# scroll commands.
if self._scrollmode == 'auto':
self._scrolledWidget.configure(xscrollcommand=self._scrollBothLater,
yscrollcommand=self._scrollBothLater)
else:
self._scrolledWidget.configure(xscrollcommand=self._scrollXNow,
yscrollcommand=self._scrollYNow)
def _scrollXNow(self, first, last):
first, last = str(first), str(last)
self.hbar.set(first, last)
self._hbarNeeded = ((first, last) not in (('0', '1'), ('0.0', '1.0')))
if self._scrollmode == 'auto':
if self._hbarNeeded != self._hbarOn:
self._toggleHbar()
def _scrollYNow(self, first, last):
first, last = str(first), str(last)
self.vbar.set(first, last)
self._vbarNeeded = ((first, last) not in (('0', '1'), ('0.0', '1.0')))
if self._scrollmode == 'auto':
if self._vbarNeeded != self._vbarOn:
self._toggleVbar()
def _scrollBothLater(self, first, last):
# Called by the listbox to set the horizontal or vertical
# scrollbar when it has scrolled or changed size or contents.
if self._scrollTimer is None:
self._scrollTimer = self.after_idle(self._scrollBothNow)
def _scrollBothNow(self):
# This performs the function of _scrollXNow and _scrollYNow.
# If one is changed, the other should be updated to match.
self._scrollTimer = None
# Call update_idletasks to make sure that the containing frame
# has been resized before we attempt to set the scrollbars.
# Otherwise the scrollbars may be mapped/unmapped continuously.
self._scrollRecurse = self._scrollRecurse + 1
self.update_idletasks()
self._scrollRecurse = self._scrollRecurse - 1
if self._scrollRecurse != 0:
return
xview, yview = self._scrolledWidget.xview(), self._scrolledWidget.yview()
self.hbar.set(*xview)
self.vbar.set(*yview)
self._hbarNeeded = (xview != (0.0, 1.0))
self._vbarNeeded = (yview != (0.0, 1.0))
# If both horizontal and vertical scrollmodes are dynamic and
# currently only one scrollbar is mapped and both should be
# toggled, then unmap the mapped scrollbar. This prevents a
# continuous mapping and unmapping of the scrollbars.
if (self._scrollmode == 'auto' and self._hbarNeeded != self._hbarOn and
self._vbarNeeded != self._vbarOn and self._vbarOn != self._hbarOn):
if self._hbarOn:
self._toggleHbar()
else:
self._toggleVbar()
return
if self._scrollmode == 'auto':
if self._hbarNeeded != self._hbarOn:
self._toggleHbar()
if self._vbarNeeded != self._vbarOn:
self._toggleVbar()
def _toggleHbar(self):
self._hbarOn = not self._hbarOn
if self._hbarOn:
self.hbar.grid(row=1, column=0, sticky='ew')
else:
self.hbar.grid_forget()
def _toggleVbar(self):
self._vbarOn = not self._vbarOn
if self._vbarOn:
self.vbar.grid(row=0, column=1, sticky='ns')
else:
self.vbar.grid_forget()
def destroy(self):
if self._scrollTimer is not None:
self.after_cancel(self._scrollTimer)
self._scrollTimer = None
Tkinter.Frame.destroy(self)
################################################################################
################################################################################
class ScrolledTreectrl(ScrolledWidget):
'''Treectrl widget with one or two static or automatic scrollbars.
Subwidgets are:
treectrl - TkTreectrl.Treectrl widget
hbar - horizontal Tkinter.Scrollbar
vbar - vertical Tkinter.Scrollbar
The widget itself is a Tkinter.Frame with one additional configuration option:
scrollmode - may be one of "x", "y", "both" or "auto".'''
def __init__(self, *args, **kw):
ScrolledWidget.__init__(self, *args, **kw)
def _setScrolledWidget(self):
self.treectrl = Treectrl.Treectrl(self)
return self.treectrl
################################################################################
################################################################################
class ScrolledMultiListbox(ScrolledWidget):
'''MultiListbox widget with one or two static or automatic scrollbars.
Subwidgets are:
listbox - TkTreectrl.MultiListbox widget
hbar - horizontal Tkinter.Scrollbar
vbar - vertical Tkinter.Scrollbar
The widget itself is a Tkinter.Frame with one additional configuration option:
scrollmode - may be one of "x", "y", "both" or "auto".'''
def __init__(self, *args, **kw):
ScrolledWidget.__init__(self, *args, **kw)
def _setScrolledWidget(self):
self.listbox = MultiListbox.MultiListbox(self)
return self.listbox
```
#### File: MGLToolsPckgs/AutoDockTools/autodpf41Commands.py
```python
from ViewerFramework.VFCommand import CommandGUI
from AutoDockTools.autodpfCommands import DpfSetDpo, DpfLoadDefaults,\
Dpf4MacroSelector, Dpf4FlexResSelector, Dpf4MacroChooser,\
Dpf4InitLigand, Dpf4LigandChooser, Dpf4LigPDBQReader,\
DpfEditor, Dpf41SAWriter, Dpf41GAWriter, Dpf41LSWriter,\
Dpf41GALSWriter, Dpf41EPDBWriter, Dpf4ClusterWriter, Dpf41CONFIGWriter, SimAnneal, GA,\
LS, SetDockingRunParms, SetAutoDock4Parameters, SetAutoDock41Parameters,\
StopAutoDpf, menuText, checkHasDpo, sortKeyList, setDpoFields
DpfLoadDefaultsGUI = CommandGUI()
DpfLoadDefaultsGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'], menuText['ReadDpfMB'])
Dpf4MacroSelectorGUI=CommandGUI()
Dpf4MacroSelectorGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['ReadMacro4'], cascadeName = menuText['MacromoleculeMB'])
Dpf4FlexResSelectorGUI=CommandGUI()
Dpf4FlexResSelectorGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['ReadFlexRes4'], cascadeName = menuText['MacromoleculeMB'])
Dpf4MacroChooserGUI=CommandGUI()
Dpf4MacroChooserGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['ChooseMacro4'], cascadeName = menuText['MacromoleculeMB'])
Dpf4InitLigandGUI=CommandGUI()
Dpf4InitLigandGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['AdjustLigand4'], cascadeName = menuText['SetLigandParmsMB'])
Dpf4LigandChooserGUI=CommandGUI()
Dpf4LigandChooserGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['ChooseLigand4'], cascadeName = menuText['SetLigandParmsMB'])
Dpf4LigPDBQReaderGUI = CommandGUI()
Dpf4LigPDBQReaderGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['ReadLigand4'], cascadeName = menuText['SetLigandParmsMB'])
DpfEditorGUI=CommandGUI()
DpfEditorGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['EditDpfMB'])
Dpf41SAWriterGUI=CommandGUI()
Dpf41SAWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteSA41'], cascadeName = menuText['WriteDpfMB'])
Dpf41GAWriterGUI=CommandGUI()
Dpf41GAWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteGA41'], cascadeName = menuText['WriteDpfMB'])
Dpf41LSWriterGUI=CommandGUI()
Dpf41LSWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteLS41'], cascadeName = menuText['WriteDpfMB'])
Dpf41GALSWriterGUI=CommandGUI()
Dpf41GALSWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteGALS41'], cascadeName = menuText['WriteDpfMB'])
Dpf41EPDBWriterGUI=CommandGUI()
Dpf41EPDBWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteEPDB41'], cascadeName = menuText['WriteDpfMB'])
Dpf41CONFIGWriterGUI=CommandGUI()
Dpf41CONFIGWriterGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['WriteCONFIG41'], cascadeName = menuText['WriteDpfMB'])
SimAnnealGUI=CommandGUI()
SimAnnealGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['SA'], cascadeName = menuText['SetSearchParmsMB'])
GAGUI=CommandGUI()
GAGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],menuText['GA'],\
cascadeName = menuText['SetSearchParmsMB'])
LSGUI=CommandGUI()
LSGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],'Local Search Parameters ',\
cascadeName = menuText['SetSearchParmsMB'])
SetDockingRunParmsGUI=CommandGUI()
SetDockingRunParmsGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['SetDockingRunParmsMB'])
SetAutoDock41ParametersGUI=CommandGUI()
SetAutoDock41ParametersGUI.addMenuCommand('AutoTools41Bar', menuText['AutoDpfMB'],\
menuText['SetAutoDock41Parameters'], cascadeName = menuText['OtherOptionsMB'])
commandList = [
{'name':'AD41dpf_read','cmd':DpfLoadDefaults(),'gui':DpfLoadDefaultsGUI},
#{'name':'AD41dpf_chooseMacromolecule','cmd':Dpf4MacroChooser(),'gui':Dpf4MacroChooserGUI},
#macromolecule
{'name':'AD41dpf_readMacromolecule','cmd':Dpf4MacroSelector(),'gui':Dpf4MacroSelectorGUI},
{'name':'AD41dpf_readFlexRes','cmd':Dpf4FlexResSelector(),'gui':Dpf4FlexResSelectorGUI},
#ligand
{'name':'AD41dpf_chooseFormattedLigand','cmd':Dpf4LigandChooser(),'gui':Dpf4LigandChooserGUI},
{'name':'AD41dpf_readFormattedLigand','cmd':Dpf4LigPDBQReader(),'gui':Dpf4LigPDBQReaderGUI},
{'name':'AD41dpf_initLigand','cmd':Dpf4InitLigand(),'gui':Dpf4InitLigandGUI},
{'name':'AD41dpf_setGAparameters','cmd':GA(),'gui':GAGUI},
{'name':'AD41dpf_setSAparameters','cmd':SimAnneal(),'gui':SimAnnealGUI},
{'name':'AD41dpf_setLSparameters','cmd':LS(),'gui':LSGUI},
{'name':'AD41dpf_setDockingParameters','cmd':SetDockingRunParms(),'gui':SetDockingRunParmsGUI},
{'name':'AD41dpf_setAutoDock4Parameters','cmd':SetAutoDock41Parameters(),\
'gui':SetAutoDock41ParametersGUI},
{'name':'AD41dpf_writeGALS','cmd':Dpf41GALSWriter(),'gui':Dpf41GALSWriterGUI},
{'name':'AD41dpf_writeGA','cmd':Dpf41GAWriter(),'gui':Dpf41GAWriterGUI},
{'name':'AD41dpf_writeSA','cmd':Dpf41SAWriter(),'gui':Dpf41SAWriterGUI},
{'name':'AD41dpf_writeLS','cmd':Dpf41LSWriter(),'gui':Dpf41LSWriterGUI},
{'name':'AD41dpf_writeEPDB','cmd':Dpf41EPDBWriter(),'gui':Dpf41EPDBWriterGUI},
{'name':'AD41dpf_writeCONFIG','cmd':Dpf41CONFIGWriter(),'gui':Dpf41CONFIGWriterGUI},
{'name':'AD41dpf_edit','cmd':DpfEditor(),'gui':DpfEditorGUI},
]
def initModule(vf):
for dict in commandList:
vf.addCommand(dict['cmd'], dict['name'], dict['gui'])
if not hasattr(vf, 'ADdpf_setDpo'):
vf.addCommand(DpfSetDpo(), 'ADdpf_setDpo', None)
if vf.hasGui and 'AutoTools41Bar' in vf.GUI.menuBars.keys():
for item in vf.GUI.menuBars['AutoTools41Bar'].menubuttons.values():
item.configure(background = 'tan')
if not hasattr(vf.GUI, 'adtBar'):
vf.GUI.adtBar = vf.GUI.menuBars['AutoTools41Bar']
vf.GUI.adtFrame = vf.GUI.adtBar.menubuttons.values()[0].master
```
#### File: MGLToolsPckgs/AutoDockTools/autoflex4Commands.py
```python
from ViewerFramework.VFCommand import CommandGUI
from AutoDockTools.autoflexCommands import AF_MacroReader,\
AF_MacroChooser, AF_SelectResidues, AF_ProcessResidues,\
AF_ProcessHingeResidues, AF_EditHinge, AF_SetHinge,\
AF_SetBondRotatableFlag, AF_StepBack, AF_FlexFileWriter,\
AF_RigidFileWriter, AF_LigandDirectoryWriter, menuText
AF_MacroReaderGUI=CommandGUI()
AF_MacroReaderGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'], \
menuText['Read Macro'], cascadeName = menuText['InputMB'])
AF_MacroChooserGUI=CommandGUI()
AF_MacroChooserGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'],
menuText['Choose Macro'], cascadeName = menuText['InputMB'])
AF_SelectResiduesGUI = CommandGUI()
AF_SelectResiduesGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'],menuText['Set Residues'])
AF_ProcessResiduesGUI = CommandGUI()
AF_ProcessHingeResiduesGUI = CommandGUI()
AF_EditHingeGUI = CommandGUI()
AF_EditHingeGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'],\
menuText['Edit Hinge'])
AF_SetHingeGUI = CommandGUI()
AF_SetHingeGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'],\
menuText['Set Hinge'])
AF_StepBackGUI = CommandGUI()
AF_StepBackGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'], menuText['Step Back'])
AF_FlexFileWriterGUI = CommandGUI()
AF_FlexFileWriterGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'], \
menuText['writeFlexible'], cascadeName = menuText['WriteMB'])
AF_RigidFileWriterGUI = CommandGUI()
AF_RigidFileWriterGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'], \
menuText['writeRigid'], cascadeName = menuText['WriteMB'])
AF_LigandDirectoryWriterGUI = CommandGUI()
AF_LigandDirectoryWriterGUI.addMenuCommand('AutoTools4Bar', menuText['AutoFlexMB'], \
menuText['writeDir'], cascadeName = menuText['WriteMB'])
commandList = [
{'name':'AD4flex_readMacro','cmd':AF_MacroReader(),'gui':AF_MacroReaderGUI},
{'name':'AD4flex_chooseMacro','cmd':AF_MacroChooser(),'gui':AF_MacroChooserGUI},
{'name':'AD4flex_setResidues','cmd':AF_SelectResidues(),'gui':AF_SelectResiduesGUI},
#{'name':'AD4flex_processResidues','cmd':AF_ProcessResidues(),'gui':None},
#{'name':'AD4flex_processHingeResidues','cmd':AF_ProcessHingeResidues(),'gui':None},
#{'name':'AD4flex_setBondRotatableFlag','cmd':AF_SetBondRotatableFlag(),'gui':None},
#{'name':'AD4flex_setHinge','cmd':AF_SetHinge(),'gui':AF_SetHingeGUI},
#{'name':'AD4flex_editHinge','cmd':AF_EditHinge(),'gui':None},
{'name':'AD4flex_stepBack','cmd':AF_StepBack(),'gui':AF_StepBackGUI},
{'name':'AD4flex_writeFlexFile','cmd':AF_FlexFileWriter(),'gui':AF_FlexFileWriterGUI},
{'name':'AD4flex_writeRigidFile','cmd':AF_RigidFileWriter(),'gui':AF_RigidFileWriterGUI},
#{'name':'AD4flex_writeFlexDir','cmd':AF_LigandDirectoryWriter(),'gui':AF_LigandDirectoryWriterGUI}
]
def initModule(vf):
for dict in commandList:
vf.addCommand(dict['cmd'], dict['name'], dict['gui'])
if not hasattr(vf, 'ADflex_processResidues'):
vf.addCommand(AF_ProcessResidues(), 'ADflex_processResidues', None)
if not hasattr(vf, 'ADflex_setBondRotatableFlag'):
vf.addCommand(AF_SetBondRotatableFlag(), 'ADflex_setBondRotatableFlag', None)
vf.ADflex_setResidues = vf.AD4flex_setResidues
if vf.hasGui:
vf.GUI.menuBars['AutoTools4Bar'].menubuttons[menuText['AutoFlexMB']].config(bg='tan',underline='-1')
if not hasattr(vf.GUI, 'adtBar'):
vf.GUI.adtBar = vf.GUI.menuBars['AutoTools4Bar']
vf.GUI.adtFrame = vf.GUI.adtBar.menubuttons.values()[0].master
```
#### File: MGLToolsPckgs/AutoDockTools/EpdbParser.py
```python
import os
from string import find, join, replace, split, rfind
import re
from AutoDockTools.ResultParser import ResultParser
class EpdbParser(ResultParser):
""" reads log from a AutoDock docking and return structured data"""
keywords = ResultParser.keywords + [
'coords',
'vdw_energies',
'estat_energies',
'inhib_constant',
'intermol_energy', #(1)
'internal_energy', #(2) NB: 1+2->final docked energy
'torsional_energy', #(3) NB: 1+3->free energy of binding
]
def __init__(self, dlgFile=None):
"""selected dlgFile,ok sets which docked conformations to show"""
ResultParser.__init__(self)
self.filename = dlgFile
self.version = 4.2
self.ntors = 0
self.found_ntors= 0
if dlgFile:
self.filename = os.path.basename(dlgFile)
self.parse(dlgFile)
def parse(self, filename):
"""
uses key 'NOW IN COMMAND MODE.' to start matching:
'ATOM',
next uses 'Intermolecular Energy Analysis' to start
capturing individual energy breakdowns
finally captures '^epdb: USER' lines
after parsing:
"""
self.filename = filename
#reset
dlgptr = open(filename, 'r')
allLines = dlgptr.readlines()
self.clusterRecord = None
self._parse(allLines)
def _parse(self, allLines):
if not len(allLines):
return 'ERROR'
for item in ['ligLines','dpfLines','energyLines','epdbLines',\
'atTypes', 'vdw_energies','estat_energies','clist','clusterlines',\
'histogramlines', 'modelList','total_energies']:
setattr(self, item, [])
lineLen = len(allLines)
#print 'lineLen=', lineLen
atmCtr = self.atmCtr = 0
ligLines = self.ligLines
dpfLines = self.dpfLines
energyLines = self.energyLines
epdbLines = self.epdbLines
for i in range(lineLen):
l = allLines[i]
#while find(l, 'NOW IN COMMAND MODE')<0 and i<lineLen-1:
# continue
if find(l, 'INPUT-PDBQ: ATOM')==0:
ligLines.append(l[12:])
atmCtr = atmCtr + 1
elif find(l, 'INPUT-PDBQ: HETA')==0:
ligLines.append(l[12:])
atmCtr = atmCtr + 1
elif not self.found_ntors and find(l, 'active torsions:')>-1:
self.found_ntors = 1
self.ntors = int(l.split()[2])
elif find(l, 'INPUT-LIGAND-PDBQT: HETA')==0:
ligLines.append(l[12:])
atmCtr = atmCtr + 1
elif find(l, 'INPUT-LIGAND-PDBQT: ATOM')==0:
ligLines.append(l[12:])
atmCtr = atmCtr + 1
elif find(l, 'DPF>')==0:
dpfLines.append(l[5:-1])
elif find(l, 'Intermolecular Energy Analysis')> 0:
#elif find(l, 'Intermolecular Energy Analysis')>-1:
#print 'found Intermolecular Energy Analysis at line ', i
break
self.atmCtr = atmCtr
i = i + 5
for x in range(i,lineLen):
#process energy lines
i = i+1
l = allLines[i]
if find(l, 'Total')==0:
self.energyLines = self.energyLines[:-1]
break
self.energyLines.append(l)
for l in self.energyLines:
ll = split(l)
self.atTypes.append(int(ll[0]))
self.vdw_energies.append(float(ll[2]))
self.estat_energies.append(float(ll[3]))
self.total_energies.append(float(ll[2]) + float(ll[3]))
while find(l, 'epdb')<0:
#skip some stuff
l = allLines[i]
ll = split(l)
i = i + 1
for x in range(i-1, lineLen):
#process epdb lines
l = allLines[x]
ll = split(l)
if find(l, 'Estimated Free Energy')>0:
self.estFreeEnergy = float(ll[8])
elif find(l, 'Final Docked Energy')>0:
self.finalDockedEnergy = float(ll[6])
elif find(l, 'Final Intermolecular Energy')>0:
self.finalIntermolEnergy = float(ll[7])
elif find(l, 'Final Internal Energy')>0:
self.finalInternalEnergy = float(ll[9])
elif find(l, 'Final Total Internal Energy')>0:
self.finalTotalInternalEnergy = float(ll[8])
elif find(l, 'Torsional Free Energy')>0:
self.torsionalFreeEnergy = float(ll[7])
```
#### File: MGLToolsPckgs/AutoDockTools/InteractionDetector.py
```python
from string import strip
from numpy import oldnumeric as Numeric
from MolKit import Read
from MolKit.molecule import MoleculeSet, Atom, AtomSet, HydrogenBond, BondSet
from MolKit.protein import Residue, ResidueSet
from MolKit.distanceSelector import CloserThanVDWSelector, DistanceSelector
from MolKit.hydrogenBondBuilder import HydrogenBondBuilder
from PyBabel.cycle import RingFinder
from PyBabel.aromatic import Aromatic
from MolKit.bondSelector import AromaticCycleBondSelector
import numpy.oldnumeric as Numeric
from mglutil.math import crossProduct
class InteractionDetector:
"""
Base class for object to detect interactions between a receptor and potential ligands... such as virtual screen results
initialized with the receptor file containing entire molecule or residues of interest.
processLigand method takes as input a pdbqt file containing docked coordinates and returns a string
composed of hbondStr + macrocloseContactStr + ligcloseContactStr
If interections are found, a new pdbqt containing interaction description is also output:
"""
def __init__(self, receptor_file, percentCutoff=1., detect_pi=False, dist_cutoff=6, verbose=False,
distanceSelector=None, hydrogen_bond_builder=None, distanceSelectorWithCutoff=None,
aromatic_cycle_bond_selector=None):
self.receptor_file = receptor_file
receptor = Read(receptor_file)
assert(len(receptor)==1)
assert isinstance(receptor, MoleculeSet)
self.macro = receptor[0]
self.macro_atoms = self.macro.allAtoms
self.macro.buildBondsByDistance()
self.verbose = verbose
#??useful??
self.percentCutoff = percentCutoff
self.detect_pi = detect_pi
self.distanceSelector = distanceSelector
if self.distanceSelector is None:
self.distanceSelector = CloserThanVDWSelector(return_dist=0)
self.hydrogen_bond_builder = hydrogen_bond_builder
if self.hydrogen_bond_builder is None:
self.hydrogen_bond_builder = HydrogenBondBuilder()
self.distanceSelectorWithCutoff = distanceSelectorWithCutoff
if self.distanceSelectorWithCutoff is None:
self.distanceSelectorWithCutoff = DistanceSelector()
self.dist_cutoff=float(dist_cutoff)
self.results = d = {}
self.report_list =['lig_hb_atoms','lig_close_atoms']
self.aromatic_cycle_bond_selector = aromatic_cycle_bond_selector
if self.aromatic_cycle_bond_selector is None:
self.aromatic_cycle_bond_selector = AromaticCycleBondSelector()
if detect_pi:
self.report_list.extend(['pi_cation','pi_pi', 'cation_pi', 't_shaped'])
if self.verbose: print "self.report_list=", self.report_list
def processLigand(self, ligand_file, percentCutoff=None, output=1, outputfilename=None, comment="USER AD> ", buildHB=1, remove_modelStr=False):
#if outputfilename is not None, have to (1) update all the strings or (2) rename ligand
self.results = d = {}
ligand = Read(ligand_file)
assert isinstance(ligand, MoleculeSet)
assert(len(ligand)==1)
ligand = ligand[0]
first = ligand.name.find('_model')
last = ligand.name.rfind('_model')
if first!=last:
ligand.name = ligand.name[:last]
if remove_modelStr:
curName = ligand.name
modelIndex=curName.find("_model")
if modelIndex>-1:
curName = curName[:modelIndex]
#setup outputfilestem
ligand.name = curName
ligand.buildBondsByDistance()
if not percentCutoff:
percentCutoff = self.percentCutoff
# first detect sets of atoms forming hydrogen bonds
# hbondStr,hblist and has_hbonds added to process vina results which do not include valid hydrogen bonds
hbondStr = ""
hblist = [""]
has_hbonds = False
if buildHB:
has_hbonds = True
hbondStr = self.buildHydrogenBonds(ligand, comment=comment) #
if self.verbose: print "hbondStr=", hbondStr
hblist = hbondStr.split('\n') # hbond info
if hblist[0]=='lig_hb_atoms : 0':
has_hbonds = False
# next detect sets of atoms in close contact not forming hydrogen bonds
macrocloseContactStr, ligcloseContactStr = self.buildCloseContactAtoms(percentCutoff, ligand, comment=comment) #
self.piResults = ""
if self.detect_pi:
self.detectPiInteractions()
if self.results['pi_cation']:
self.piResults = self.get_pi_cation_result(print_ctr=1, comment=comment)
if self.verbose:
print "found pi_cation in ", ligand_file
print "set self.piResults to ", self.piResults
if self.results['pi_pi']:
self.piResults += self.get_pi_pi(print_ctr=1, comment=comment)
if self.verbose:
print "set self.piResults to ", self.piResults
macro_cclist = macrocloseContactStr.split(';')
lig_cclist = ligcloseContactStr.split(';')
if has_hbonds or len(macro_cclist):
fptr = open(ligand_file)
lines = fptr.readlines()
fptr.close()
if outputfilename is not None:
optr = open(outputfilename, 'w')
else:
optr = open(ligand_file, 'w')
for new_l in hblist:
if not(len(new_l)): #don't output empty lines
continue
if new_l.find(comment)!=0:
new_l = comment + new_l
if new_l != hblist[-1]:
optr.write(new_l+"\n")
else:
optr.write(new_l) # no newline after the last one
for new_l in macro_cclist:
if not(len(new_l)): #don't output empty lines
continue
if new_l.find(comment)!=0:
new_l = comment + new_l
if new_l != macro_cclist[-1]:
optr.write(new_l + "\n")
else:
optr.write(new_l)
for new_l in lig_cclist:
if not(len(new_l)): #don't output empty lines
continue
if new_l.find(comment)!=0:
new_l = comment + new_l
if new_l != lig_cclist[-1]:
optr.write(new_l + "\n")
else:
optr.write(new_l)
if len(self.piResults): ##???
for s in self.piResults.split("\n"):
optr.write(s+"\n")
for l in lines:
optr.write(l)
optr.close()
return hbondStr + macrocloseContactStr + ligcloseContactStr
def getResultStr(self, verbose=False):
#only write important ones: hbonds, vdw_contacts, ?pi_pi,pi_cation etc?
ss = ""
for k in self.report_list:
v = self.results[k]
#key:atom1.full_name();
if len(v):
if verbose: print "gRS: report for ", k
if verbose: print "USER: " + k + ":" + str(len(v))
if verbose: print " start ss= ", ss
ss += k + ":" + str(len(v)) + "\n"
if k=='lig_hb_atoms':
if verbose: print "@@ getResultStr lig_hb_atoms"
hbstr = ""
for lig_at in v:
for hb in lig_at.hbonds:
if hasattr(hb, 'hAt'):
hbstr += 'USER %s-%s~%s\n'%(hb.donAt.full_name(), hb.hAt.full_name(),hb.accAt.full_name())
else:
hbstr += 'USER %s~%s\n'%(hb.donAt.full_name(), hb.accAt.full_name())
if verbose: print "hbstr="
#add it to ss here
ss += hbstr
if verbose: print "with hbstr: ss=", ss
#if self.verbose:
elif k == 'pi_cation':
for res in v:
#v=[(<Atom instance> HSG1:A:ARG8:CZ, [<Atom instance> IND: : INI 20:C1])]
#res=(<Atom instance> HSG1:A:ARG8:CZ, [<Atom instance> IND: : INI 20:C1])
#res[0]=<Atom instance> HSG1:A:ARG8:CZ
#res[1]= [<Atom instance> IND: : INI 20:C1]
#res[1][0]= <Atom instance> IND: : INI 20:C1
#
ss += "USER %s~~%s\n"%(res[0].full_name(), res[1][0].full_name())
else:
for w in v:
if verbose: print "@@ getResultStr w=", w
try:
ss += 'USER ' + w.full_name()+'\n;'
except:
if verbose: print "except on ", w
ss += "USER " + str(w)
ss += "\n"
if verbose: print " end ss= ", ss
return ss
def buildHydrogenBonds(self, ligand, comment="USER AD> "):
h_pairDict = self.hydrogen_bond_builder.build(ligand.allAtoms, self.macro_atoms)
self.h_pairDict = h_pairDict
#keys should be from lig, values from macro
#sometimes are not...@@check this@@
h_results = {}
for k, v in h_pairDict.items():
h_results[k] = 1
for at in v:
h_results[at] = 1
all_hb_ats = AtomSet(h_results.keys()) #all
d = self.results
macro_hb_ats = d['macro_hb_atoms'] = all_hb_ats.get(lambda x: x.top==self.macro)
self.macro_hb_ats = macro_hb_ats
# process lig
lig_hb_ats = d['lig_hb_atoms'] = all_hb_ats.get(lambda x: x in ligand.allAtoms)
self.lig_hb_ats = lig_hb_ats
outS = comment + "lig_hb_atoms : %d\n"%(len(lig_hb_ats))
for p in self.lig_hb_ats: #intD.results['lig_hb_atoms']:
for hb in p.hbonds:
if hasattr(hb, 'used'): continue
if hb.hAt is not None:
outS += comment + "%s,%s~%s\n"%(hb.donAt.full_name(), hb.hAt.name, hb.accAt.full_name())
else:
outS += comment + "%s~%s\n"%(hb.donAt.full_name(), hb.accAt.full_name())
hb.used = 1
#hsg1V:B:ARG8:NH2,HH22~clean: : INI 20:N5
#clean: : INI 20:O4,H3~hsg1V:B:ASP29:OD2
#clean: : INI 20:O4,H3~hsg1V:B:ASP29:OD2
#clean: : INI 20:N4,H3~hsg1V:B:GLY27:O
#clean: : INI 20:O2,H2~hsg1V:B:ASP25:OD1
#macroHStr = self.macro.allAtoms.get(lambda x: hasattr(x, 'hbonds') and len(x.hbonds)).full_name()
#ligHStr = ligand.allAtoms.get(lambda x: hasattr(x, 'hbonds') and len(x.hbonds)).full_name()
#return macroHStr + '==' + ligHStr
if self.verbose:
print "buildHB returning:"
print outS
return outS
def buildCloseContactAtoms(self, percentCutoff, ligand, comment="USER AD> "):
pairDict = self.distanceSelector.select(ligand.allAtoms,
self.macro_atoms, percentCutoff=percentCutoff)
self.pairDict = pairDict
#reset here
lig_close_ats = AtomSet()
macro_close_ats = AtomSet()
cdict = {}
for k,v in pairDict.items():
if len(v):
cdict[k] = 1
for at in v:
if at not in macro_close_ats:
cdict[at] = 1
closeAtoms = AtomSet(cdict.keys())
lig_close_ats = closeAtoms.get(lambda x: x.top==ligand).uniq()
#ligClAtStr = lig_close_ats.full_name()
ligClAtStr = comment + "lig_close_ats: %d\n" %( len(lig_close_ats))
if len(lig_close_ats):
ligClAtStr += comment + "%s\n" %( lig_close_ats.full_name())
macro_close_ats = closeAtoms.get(lambda x: x in self.macro_atoms).uniq()
macroClAtStr = comment + "macro_close_ats: %d\n" %( len(macro_close_ats))
if len(macro_close_ats):
macroClAtStr += comment + "%s\n" %( macro_close_ats.full_name())
#macroClAtStr = "macro_close_ats: " + len(macro_close_ats)+"\n" +macro_close_ats.full_name()
rdict = self.results
rdict['lig_close_atoms'] = lig_close_ats
rdict['macro_close_atoms'] = macro_close_ats
if self.verbose: print "macroClAtStr=", macroClAtStr
if self.verbose: print "ligClAtStr=", ligClAtStr
if self.verbose: print "returning "+ macroClAtStr + '==' + ligClAtStr
return macroClAtStr , ligClAtStr
def getCations(self, atoms):
#select atoms in ARG and LYS residues
arg_cations = atoms.get(lambda x: (x.parent.type=='ARG' and \
x.name in ['CZ']))
lys_cations = atoms.get(lambda x: (x.parent.type=='LYS' and \
x.name in ['NZ', 'HZ1', 'HZ2', 'HZ3']))
#select any positively-charged metal ions... cannot include CA here
metal_cations = atoms.get(lambda x: x.name in ['Mn','MN', 'Mg',\
'MG', 'FE', 'Fe', 'Zn', 'ZN'])
ca_cations = atoms.get(lambda x: x.name in ['CA', 'Ca'] and x.parent.type=='CA')
cations = AtomSet()
#cations.extend(arg_cations)
for a in arg_cations:
cations.append(a)
#cations.extend(lys_cations)
for a in lys_cations:
cations.append(a)
#cations.extend(metal_cations)
for a in metal_cations:
cations.append(a)
#cations.extend(ca_cations)
for a in ca_cations:
cations.append(a)
return cations
def detectPiInteractions(self, tolerance=0.95, debug=False, use_all_cycles=False):
if debug: print "in detectPiInteractions"
self.results['pi_pi'] = [] #stacked rings...?
self.results['t_shaped'] = [] #one ring perpendicular to the other
self.results['cation_pi'] = [] #
self.results['pi_cation'] = [] #
self.results['macro_cations'] = []#
self.results['lig_cations'] = [] #
#at this point have self.results
if not len(self.results['lig_close_atoms']):
return
lig_atoms = self.results['lig_close_atoms'].parent.uniq().atoms
macro_res = self.results['macro_close_atoms'].parent.uniq()
if not len(macro_res):
return
macro_atoms = macro_res.atoms
l_rf = RingFinder()
#Ligand
l_rf.findRings2(lig_atoms, lig_atoms.bonds[0])
#rf.rings is list of dictionaries, one per ring, with keys 'bonds' and 'atoms'
if debug: print "LIG: len(l_rf.rings)=", len(l_rf.rings)
if not len(l_rf.rings):
if debug: print "no lig rings found by l_rf!"
return
acbs = self.aromatic_cycle_bond_selector
#acbs = AromaticCycleBondSelector()
lig_rings = []
for r in l_rf.rings:
ring_bnds = r['bonds']
if use_all_cycles:
lig_rings.append(ring_bnds)
else:
arom_bnds = acbs.select(ring_bnds)
if len(arom_bnds)>4:
lig_rings.append(arom_bnds)
if debug: print "LIG: len(lig_arom_rings)=", len(lig_rings)
self.results['lig_rings'] = lig_rings
self.results['lig_ring_atoms'] = AtomSet()
#only check for pi-cation if lig_rings exist
if len(lig_rings):
macro_cations = self.results['macro_cations'] = self.getCations(macro_atoms)
macro_cations = macro_cations.get(lambda x: x.element!='H')
lig_ring_atoms = AtomSet()
u = {}
for r in lig_rings:
for a in BondSet(r).getAtoms():
u[a] = 1
if len(u):
lig_ring_atoms = AtomSet(u.keys())
lig_ring_atoms.sort()
self.results['lig_ring_atoms'] = lig_ring_atoms
if len(macro_cations):
if debug: print "check distances from lig_rings to macro_cations here"
#macro cations->lig rings
pairDict2 = self.distanceSelector.select(lig_ring_atoms,macro_cations)
z = {}
for key,v in pairDict2.items():
val = v.tolist()[0]
if val in macro_cations:
z[val] = [key]
if len(z):
self.results['pi_cation'] = (z.items())
else:
self.results['pi_cation'] = []
#check the distance between the rings and the macro_cations
self.results['lig_cations'] = self.getCations(lig_atoms)
lig_cations = self.results['lig_cations']
#remove hydrogens
lig_cations = lig_cations.get(lambda x: x.element!='H')
#Macromolecule
m_rf = RingFinder()
m_rf.findRings2(macro_res.atoms, macro_res.atoms.bonds[0])
#rf.rings is list of dictionaries, one per ring, with keys 'bonds' and 'atoms'
if debug: print "MACRO: len(m_rf.rings)=", len(m_rf.rings)
if not len(m_rf.rings):
if debug: print "no macro rings found by m_rf!"
return
macro_rings = []
for r in m_rf.rings:
ring_bnds = r['bonds']
if use_all_cycles:
macro_rings.append(ring_bnds)
else:
arom_bnds = acbs.select(ring_bnds)
if len(arom_bnds)>4:
macro_rings.append(arom_bnds)
if debug: print "len(macro_arom_rings)=", len(macro_rings)
self.results['macro_rings'] = macro_rings
self.results['macro_ring_atoms'] = AtomSet()
#only check for pi-cation if macro_rings exist
if len(macro_rings):
macro_ring_atoms = AtomSet()
u = {}
for r in macro_rings:
for a in BondSet(r).getAtoms(): #new method of bondSets
u[a] = 1
if len(u):
macro_ring_atoms = AtomSet(u.keys())
macro_ring_atoms.sort()
self.results['macro_ring_atoms'] = macro_ring_atoms
if len(lig_cations):
if debug: print "check distances from macro_rings to lig_cations here"
pairDict3 = self.distanceSelector.select(macro_ring_atoms,lig_cations)
z = {}
for x in pairDict3.items():
#lig cations->macro rings
z.setdefault(x[1].tolist()[0], []).append(x[0])
if len(z):
self.results['cation_pi'] = (z.items())
else:
self.results['cation_pi'] = []
#macro_pi_atoms = AtomSet(pairDict3.keys())
#l_cations = AtomSet()
#for v in pairDict3.values():
# for x in v:
# l_cations.append(x)
#self.results['cation_pi'] = pairDict3.items()
#self.results['cation_pi'] = (l_cations, macro_pi_atoms)
#check for intermol distance <6 Angstrom (J.ComputChem 29:275-279, 2009)
#compare each lig_ring vs each macro_ring
for lig_ring_bnds in lig_rings:
lig_atoms = acbs.getAtoms(lig_ring_bnds)
lig_atoms.sort()
if debug: print "len(lig_atoms)=", len(lig_atoms)
#---------------------------------
# compute the normal to lig ring
#---------------------------------
a1 = Numeric.array(lig_atoms[0].coords)
a2 = Numeric.array(lig_atoms[2].coords)
a3 = Numeric.array(lig_atoms[4].coords)
if debug: print "a1,a2, a3=", a1.tolist(), a2.tolist(), a3.tolist()
for macro_ring_bnds in macro_rings:
macro_atoms = acbs.getAtoms(macro_ring_bnds)
macro_atoms.sort()
if debug: print "len(macro_atoms)=", len(macro_atoms)
pD_dist = self.distanceSelectorWithCutoff.select(macro_ring_atoms, lig_atoms, cutoff=self.dist_cutoff)
if not len(pD_dist[0]):
if debug:
print "skipping ligand ring ", lig_rings.index(lig_ring_bnds), " vs ",
print "macro ring", macro_rings.index(macro_ring_bnds)
continue
#---------------------------------
# compute the normal to macro ring
#---------------------------------
b1 = Numeric.array(macro_atoms[0].coords)
b2 = Numeric.array(macro_atoms[2].coords)
b3 = Numeric.array(macro_atoms[4].coords)
if debug: print "b1,b2, b3=", b1.tolist(), b2.tolist(), b3.tolist()
# check for stacking
a2_1 = a2-a1
a3_1 = a3-a1
b2_1 = b2-b1
b3_1 = b3-b1
if debug: print "a2_1 = ", a2-a1
if debug: print "a3_1 = ", a3-a1
if debug: print "b2_1 = ", b2-b1
if debug: print "b3_1 = ", b3-b1
n1 = crossProduct(a3_1,a2_1) #to get the normal for the first ring
n2 = crossProduct(b3_1,b2_1) #to get the normal for the second ring
if debug: print "n1=", n1
if debug: print "n2=", n2
n1 = Numeric.array(n1)
n2 = Numeric.array(n2)
n1_dot_n2 = Numeric.dot(n1,n2)
if debug: print "n1_dot_n2", Numeric.dot(n1,n2)
if abs(n1_dot_n2) >= 1*tolerance:
if debug: print "The rings are stacked vertically"
new_result = (acbs.getAtoms(lig_ring_bnds), acbs.getAtoms(macro_ring_bnds))
self.results['pi_pi'].append(new_result)
if abs(n1_dot_n2) <= 0.01*tolerance:
if debug: print "The rings are stacked perpendicularly"
new_result = (acbs.getAtoms(lig_ring_bnds), acbs.getAtoms(macro_ring_bnds))
self.results['t_shaped'].append(new_result)
def get_pi_pi(self, print_ctr=1, comment="USER AD> "):
#one ring parallel to another
#@@ UNTESTED! ... need test data
if not len(self.results.get( 'pi_pi')):
return ""
# self.results['pi_pi'] = [] #stacked rings...?
res = self.results['pi_pi']
ss = comment + "pi_pi: %d\n"%(len(self.results['pi_pi']))
####
#3l1m_lig_vs:A:HEM150:C4A,C3D,C1A,C2D,C4D,C2A,NA,ND,C3A,C1D : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:C3B,NB,C4A,C1A,C4B,NA,C2A,C2B,C3A,C1B : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:C3B,C1B,C3C,NB,C4C,NC,C2B,C1C,C4B,C2C : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:NC,C4C,C1C,C3C,C2C : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:C1A,NA,C2A,C3A,C4A : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:NB,C2B,C3B,C1B,C4B : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:NC,C4C,C1C,C3C,C2C : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#3l1m_lig_vs:A:HEM150:C4D,ND,C1D,C3D,C2D : 3l1m_rec:A:PHE65:CD2,CD1,CG,CZ,CE1,CE2
#
# build string for self.results['pi_pi']
for res in self.results['pi_pi']:
ss += comment + "%s~~%s\n"%(res[0].full_name(), res[1].full_name())
###ss += "USER %s~~%s\n"%(res[0].full_name(), res[1].full_name())
#ss += "USER %s~~%s\n"%(res[0].full_name(), res[1][0].full_name())
#print "returning ss=" , ss
return ss
def get_t_shaped(self, print_ctr=1, comment="USER AD> "):
#one ring perpendicular to the other
#@@ UNTESTED! ... need test data
if not len(self.results.get( 't_shaped')):
return ""
#print "in gpcr: self.results[t_shaped]=", self.results['t_shaped']
ss = comment + "t_shaped: %d\n"%(len(self.results['t_shaped']))
# build string for self.results['t_shaped']
for res in self.results['t_shaped']:
#for example:
#????
#????
#????
#
ss += comment + "%s~~%s\n"%(res[0].full_name(), res[1][0].full_name())
return ss
def get_cation_pi(self, print_ctr=1, comment="USER AD> "):
#cation near aromatic ring
#@@ UNTESTED! ... need test data
if not len(self.results.get( 'cation_pi')):
return ""
ss = comment + "cation_pi: %d\n"%(len(self.results['cation_pi']))
# build string for self.results['cation_pi']
for res in self.results['cation_pi']:
#for example:
#????
#????
#????
#
ss += comment + "%s~~%s\n"%(res[0].full_name(), res[1][0].full_name())
return ss
def get_pi_cation_result(self, print_ctr=1, comment="USER AD> "):
#aromatic ring near cation
#print "in gpcr: self.results[pi_cation]=", self.results['pi_cation']
if not len(self.results.get( 'pi_cation')):
return ""
ss = comment + "pi_cation: %d\n"%(len(self.results['pi_cation']))
# build string for self.results['pi_cation']
for res in self.results['pi_cation']:
#for example:
#v=[(<Atom instance> HSG1:A:ARG8:CZ, [<Atom instance> IND: : INI 20:C1])]
#res=(<Atom instance> HSG1:A:ARG8:CZ, [<Atom instance> IND: : INI 20:C1])
#res[0]=<Atom instance> HSG1:A:ARG8:CZ
#res[1]= [<Atom instance> IND: : INI 20:C1]
#res[1][0]= <Atom instance> IND: : INI 20:C1
#
#attempt to get names for all atoms in the whole ring:
res1_str = res[1][0].full_name()
for rr in self.results['lig_rings']:
ats = rr.getAtoms()
if res[1][0] in ats:
res1_str = ats.full_name()
break
ss += comment + "%s~~%s\n"%(res[0].full_name(), res1_str)
#ss += "USER %s~~%s\n"%(res[0].full_name(), res[1][0].full_name())
return ss
def print_ligand_residue_contacts(self, print_ctr=1):
ctr = 1
#pairDict is atom-based
#for residue-based report:
# need to build lists of unique parents of keys
# and lists of unique parents of corresponding values
res_d = {}
for at in self.pairDict.keys():
if at.parent not in res_d.keys():
res_d[at.parent] = {}
for close_at in self.pairDict[at]:
res_d[at.parent][close_at.parent] = 1
#print it out
for lig_res in res_d.keys():
if print_ctr:
print ctr, lig_res.parent.name+':'+ lig_res.name + '->',
else:
print lig_res.parent.name+':'+ lig_res.name + '->',
for macro_res in res_d[lig_res]:
print macro_res.parent.name + ':' + macro_res.name + ',',
print
ctr += 1
return res_d
def print_macro_residue_contacts(self, print_ctr=1):
ctr = 1
#pairDict is atom-based
#for residue-based report:
# need to build lists of unique parents of keys
# and lists of unique parents of corresponding values
res_d = {}
for at_key, at_list in self.pairDict.items():
for at in at_list:
if at.parent not in res_d.keys():
res_d[at.parent] = {}
res_d[at.parent][at_key.parent] = 1
#print it out
for macro_res in res_d.keys():
if print_ctr:
print ctr, macro_res.parent.name+':'+ macro_res.name + '->',
else:
print macro_res.parent.name+':'+ macro_res.name + '->',
for lig_res in res_d[macro_res]:
print lig_res.parent.name + ':' + lig_res.name + ',',
print
ctr += 1
return res_d
def print_report(self, keylist=[]):
if not len(keylist):
keylist = [
'lig_close_atoms',
'lig_hb_atoms',
'lig_hbas',
'macro_close_atoms',
'macro_hb_atoms',
]
d = self.results
if self.verbose:
for k in keylist:
print k, ':', len(d[k]), '-', d[k].__class__
def print_hb_residue(self, print_ctr=1):
ctr = 1
#pairDict is atom-based
res_d = {}
for at in self.h_pairDict.keys():
if at.parent not in res_d.keys():
res_d[at.parent] = {}
for close_at in self.h_pairDict[at]:
res_d[at.parent][close_at.parent] = 1
# print it out
# Hbond instance are define with donAt,hAt ~ accAtt (tilde)
for don_res in res_d.keys():
if print_ctr:
print ctr, don_res.top.name+':'+don_res.parent.name+':'+ don_res.name + '->',
else:
print don_res.top.name+':'+don_res.parent.name+':'+ don_res.name + '->',
for acc_res in res_d[don_res]:
print acc_res.top.name+':'+acc_res.parent.name + ':' + acc_res.name + ',',
print
ctr += 1
return res_d
```
#### File: AutoDockTools/Utilities24/compute_rms_between_conformations.py
```python
import os, glob
import numpy.oldnumeric as Numeric
from math import sqrt
from MolKit import Read
from AutoDockTools.Docking import Docking
from mglutil.math.rmsd import RMSDCalculator
def dist(coords1, coords2):
"""return distance between two atoms, a and b.
"""
npts = len(coords1)
pt1 = Numeric.add.reduce(coords1)/npts
pt2 = Numeric.add.reduce(coords2)/npts
d = Numeric.array(pt1) - Numeric.array(pt2)
return sqrt(Numeric.sum(d*d))
if __name__ == '__main__':
import sys
import getopt
def usage():
"Print helpful, accurate usage statement to stdout."
print "Usage: compute_rms_between_conformations.py -r reference"
print
print " Description of command..."
print " -f first filename"
print " -s second filename"
print " Optional parameters:"
print " [-x] omit hydrogen atoms from the calculation"
print " [-o] output filename"
print " (default is 'summary_rms_results.txt')"
print " [-v] verbose output"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'f:s:o:xvh')
except getopt.GetoptError, msg:
print 'compute_rms_between_conformations.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
#-f: first filename
first = None
#-s: second filename
second = None
#-o outputfilename
outputfilename = "summary_rms_results.txt"
# optional parameters
#-x exclude hydrogen atoms from calculation
omit_hydrogens = False
#-v detailed output
verbose = None
#'f:s:o:xvh'
for o, a in opt_list:
#print "o=", o, " a=", a
if o in ('-f', '--f'):
first = a
if verbose: print 'set first filename to ', a
if o in ('-s', '--s'):
second = a
if verbose: print 'set second filename to ', a
if o in ('-o', '--o'):
outputfilename = a
if verbose: print 'set outputfilename to ', a
if o in ('-x', '--x'):
omit_hydrogens = True
if omit_hydrogens: print 'set omit_hydrogens to ', True
if o in ('-v', '--v'):
verbose = True
if verbose: print 'set verbose to ', True
if o in ('-h', '--'):
usage()
sys.exit()
if not first:
print 'compute_rms_between_conformations: reference filename must be specified.'
usage()
sys.exit()
if not second:
print 'compute_rms_between_conformations: second filename must be specified.'
usage()
sys.exit()
#process docking in reference directory
#read the molecules
first = Read(first)[0]
second = Read(second)[0]
assert len(first.allAtoms)==len(second.allAtoms)
first_ats = first.allAtoms
second_ats = second.allAtoms
if omit_hydrogens:
first_ats = first.allAtoms.get(lambda x: x.element!='H')
second_ats = second.allAtoms.get(lambda x: x.element!='H')
#setup rmsd tool
rmsTool = RMSDCalculator(first_ats.coords)
need_to_open = not os.path.exists(outputfilename)
if need_to_open:
fptr = open(outputfilename, 'w')
ostr= "reference filename test filename\t\trms \n"
fptr.write(ostr)
else:
fptr = open(outputfilename, 'a')
ostr = "% 10s,\t% 10s, % 10.4f\n" %(first.parser.filename, second.parser.filename, rmsTool.computeRMSD(second_ats.coords))
fptr.write(ostr)
fptr.close()
# To execute this command type:
# compute_rms_between_conformations.py -f filename -s secondfilename
# -o outputfilename -v verbose
# NOTE: -f, -d and -t require arguments whereas the other, -v, sets a boolean
```
#### File: AutoDockTools/Utilities24/prepare_receptor.py
```python
import os
from MolKit import Read
import MolKit.molecule
import MolKit.protein
from AutoDockTools.MoleculePreparation import ReceptorPreparation
if __name__ == '__main__':
import sys
import getopt
def usage():
"Print helpful, accurate usage statement to stdout."
print "Usage: prepare_receptor.py -r filename"
print
print " Description of command..."
print " -r receptor_filename"
print " Optional parameters:"
print " [-v] verbose output (default is minimal output)"
print " [-o pdbqs_filename] (default is molecule_name.pdbqs)"
print " [-A] type(s) of repairs to make:"
print " 'bonds_hydrogens': build bonds and add hydrogens "
print " 'bonds': build a single bond from each atom with no bonds to its closest neighbor"
print " 'hydrogens': add hydrogens"
print " 'checkhydrogens': add hydrogens only if there are none already"
print " 'None': do not make any repairs "
print " (default is 'checkhydrogens')"
print " [-C] preserve all input charges ie do not add new charges "
print " (default is addition of Kollman charges)"
print " [-p] preserve charges on specific atom types, eg -p F -p S "
print " [-G] add Gasteiger charges (default is Kollman)"
print " [-U] cleanup type:"
print " 'nphs': merge charges and remove non-polar hydrogens"
print " 'lps': merge charges and remove lone pairs"
print " 'waters': remove water residues"
print " 'nonstdres': remove chains composed entirely of residues of"
print " types other than the standard 20 amino acids"
print " 'deleteAltB': remove XX@B atoms and rename XX@A atoms->XX"
print " (default is 'nphs_lps_waters_nonstdres') "
print " [-e] delete every nonstd residue from any chain"
print " 'True': any residue whose name is not in this list:"
print " ['CYS','ILE','SER','VAL','GLN','LYS','ASN', "
print " 'PRO','THR','PHE','ALA','HIS','GLY','ASP', "
print " will be deleted from any chain. NB: there are no "
print " nucleic acid residue names at all in the list. "
print " (default is False which means not to do this)"
print " [-M] interactive "
print " (default is 'automatic': outputfile is written with no further user input)"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'r:vo:A:Cp:GU:eM:')
except getopt.GetoptError, msg:
print 'prepare_receptor.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
#-s: receptor
receptor_filename = None
# optional parameters
verbose = None
#-A: repairs to make: add bonds and/or hydrogens or checkhydrogens
repairs = ''
# default: add Kollman charges for AD3 receptor
charges_to_add = 'Kollman'
#-C do not add charges
#-p preserve charges on specific atom types
preserve_charge_types=None
#-U: cleanup by merging nphs_lps, nphs, lps, waters, nonstdres
cleanup = "nphs_lps_waters_nonstdres"
#-o outputfilename
outputfilename = None
#-m mode
mode = 'automatic'
#-e delete every nonstd residue from each chain
delete_single_nonstd_residues = None
#'r:vo:A:Cp:GU:eMh'
for o, a in opt_list:
if o in ('-r', '--r'):
receptor_filename = a
if verbose: print 'set receptor_filename to ', a
if o in ('-v', '--v'):
verbose = True
if verbose: print 'set verbose to ', True
if o in ('-o', '--o'):
outputfilename = a
if verbose: print 'set outputfilename to ', a
if o in ('-A', '--A'):
repairs = a
if verbose: print 'set repairs to ', a
if o in ('-C', '--C'):
charges_to_add = None
if verbose: print 'do not add charges'
if o in ('-G', '--G'):
charges_to_add = 'gasteiger'
if verbose: print 'add gasteiger charges'
if o in ('-p', '--p'):
if not preserve_charge_types:
preserve_charge_types = a
else:
preserve_charge_types = preserve_charge_types + ','+ a
if verbose: print 'preserve initial charges on ', preserve_charge_types
if o in ('-U', '--U'):
cleanup = a
if verbose: print 'set cleanup to ', a
if o in ('-e', '--e'):
delete_single_nonstd_residues = True
if verbose: print 'set delete_single_nonstd_residues to True'
if o in ('-M', '--M'):
mode = a
if verbose: print 'set mode to ', a
if o in ('-h', '--'):
usage()
sys.exit()
if not receptor_filename:
print 'prepare_receptor: receptor filename must be specified.'
usage()
sys.exit()
#what about nucleic acids???
mols = Read(receptor_filename)
if verbose: print 'read ', receptor_filename
mol = mols[0]
preserved = {}
if charges_to_add is not None and preserve_charge_types is not None:
preserved_types = preserve_charge_types.split(',')
if verbose: print "preserved_types=", preserved_types
for t in preserved_types:
if verbose: print 'preserving charges on type->', t
if not len(t): continue
ats = mol.allAtoms.get(lambda x: x.autodock_element==t)
if verbose: print "preserving charges on ", ats.name
for a in ats:
if a.chargeSet is not None:
preserved[a] = [a.chargeSet, a.charge]
if len(mols)>1:
if verbose: print "more than one molecule in file"
#use the molecule with the most atoms
ctr = 1
for m in mols[1:]:
ctr += 1
if len(m.allAtoms)>len(mol.allAtoms):
mol = m
if verbose: print "mol set to ", ctr, "th molecule with", len(mol.allAtoms), "atoms"
mol.buildBondsByDistance()
if verbose:
print "setting up RPO with mode=", mode,
print "and outputfilename= ", outputfilename
print "charges_to_add=", charges_to_add
print "delete_single_nonstd_residues=", delete_single_nonstd_residues
RPO = ReceptorPreparation(mol, mode, repairs, charges_to_add,
cleanup, outputfilename=outputfilename,
preserved=preserved,
delete_single_nonstd_residues=delete_single_nonstd_residues)
if charges_to_add is not None:
#restore any previous charges
for atom, chargeList in preserved.items():
atom._charges[chargeList[0]] = chargeList[1]
atom.chargeSet = chargeList[0]
# To execute this command type:
# prepare_receptor.py -r pdb_file -o outputfilename -A checkhydrogens
```
#### File: AutoDockTools/Utilities24/write_each_cluster_LE_conf.py
```python
import os, glob
from MolKit import Read
from AutoDockTools.Docking import Docking
from mglutil.math.rmsd import RMSDCalculator
from string import strip
if __name__ == '__main__':
import sys
import getopt
def usage():
print "Usage: write_largest_cluster_ligand.py "
print " This script does the following: "
print " (1) read all the files with extension '.dlg' into one Docking"
print " (2) compute a clustering at the specified rms tolerance "
print " (3) write the ligand with the coordinates of the "
print " lowest-energy conformation in each cluster to a separate file"
print " "
print " Optional parameters:"
print " [-t] rms_tolerance (default 2.0)"
print " [-o pdbqt_filename] (default ligandstem_clust#.pdbqt)"
print " [-v] verbose output"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 't:o:vh')
except getopt.GetoptError, msg:
print 'write_each_cluster_LE_conf.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
# optional parameters
verbose = None
#-o outputfilestem
outputfilestem = None
#-t rms_tolerance
rms_tolerance = 2.0
#'t:o:vh'
for o, a in opt_list:
#print "o=", o, " a=", a
if o in ('-o', '--o'):
outputfilestem = a
if verbose: print 'set stem for outputfile to ', a
if o in ('-t', '--t'):
rms_tolerance = float(a)
if verbose: print 'set rms_tolerance to ', a
if o in ('-v', '--v'):
verbose = True
if verbose: print 'set verbose to ', True
if o in ('-h', '--'):
usage()
sys.exit()
dlg_list = glob.glob('*.dlg')
d = Docking()
for dlg in dlg_list:
d.readDlg(dlg)
d.clusterer.rmsTool = RMSDCalculator(d.ligMol.allAtoms.coords[:])
d.clusterer.make_clustering(rms_tolerance)
clustering = d.clusterer.clustering_dict[rms_tolerance]
for clust in clustering:
clustStr = str(clustering.index(clust))
if verbose: print "processing clust number ", clustStr
#update the coordinates to those of conf with lowest energy in current cluster
d.ch.set_conformation(clust[0])
parser = d.ligMol.parser
lines = []
#have to add newline character to lines read from dlg
for l in parser.allLines:
l = strip(l)
l+= '\n'
lines.append(l)
parser.allLines = lines
coords = d.ligMol.allAtoms.coords
if outputfilestem is None:
parser.write_with_new_coords(coords, d.ligMol.name + "_LE_clust"+clustStr +'.pdbqt')
else:
parser.write_with_new_coords(coords, outputfilestem + clustStr +'.pdbqt')
if verbose: print 'wrote %s' %outputfilestem
# To execute this command type:
# write_each_cluster_LE_conf.py [-t rms_tolerance, -o outputfilestem] -v
```
#### File: AutoDockTools/Utilities24/write_largest_cluster_ligand.py
```python
import os, glob
from MolKit import Read
from AutoDockTools.Docking import Docking
from mglutil.math.rmsd import RMSDCalculator
if __name__ == '__main__':
import sys
import getopt
def usage():
print "Usage: write_largest_cluster_ligand.py "
print " This script does the following: "
print " (1) read all the files with extension '.dlg' into one Docking"
print " (2) compute a clustering at the specified rms tolerance "
print " (3) write the ligand with the coordinates of the "
print " lowest-energy conformation in the largest cluster to a file"
print " "
print " Optional parameters:"
print " [-t] rms_tolerance (default 1.5)"
print " [-o pdbqt_filename] (default ligandstem_BC.pdbqt)"
print " [-v] verbose output"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 't:o:vh')
except getopt.GetoptError, msg:
print 'write_largest_cluster_ligand.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
# optional parameters
verbose = None
#-o outputfilename
outputfilename = None
#-t rms_tolerance
rms_tolerance = 1.5
#'t:o:vh'
for o, a in opt_list:
#print "o=", o, " a=", a
if o in ('-o', '--o'):
outputfilename = a
if verbose: print 'set outputfilename to ', a
if o in ('-t', '--t'):
rms_tolerance = float(a)
if verbose: print 'set rms_tolerance to ', a
if o in ('-v', '--v'):
verbose = True
if verbose: print 'set verbose to ', True
if o in ('-h', '--'):
usage()
sys.exit()
dlg_list = glob.glob('*.dlg')
d = Docking()
for dlg in dlg_list:
d.readDlg(dlg)
d.clusterer.rmsTool = RMSDCalculator(d.ligMol.allAtoms.coords[:])
d.clusterer.make_clustering(rms_tolerance)
clustering = d.clusterer.clustering_dict[rms_tolerance]
largest = clustering[0]
for clust in clustering:
if len(clust)>len(largest):
largest = clust
#update the coordinates with those of conf with lowest energy in this largest cluster
d.ch.set_conformation(largest[0])
parser = d.ligMol.parser
lines = []
#have to add newline character to lines read from dlg
for l in parser.allLines:
l+= '\n'
lines.append(l)
parser.allLines = lines
coords = d.ligMol.allAtoms.coords
if outputfilename is None:
outputfilename = d.ligMol.name + '_BC.pdbqt'
parser.write_with_new_coords(coords, outputfilename)
if verbose:
print 'wrote %s' %outputfilename
# To execute this command type:
# write_largest_cluster_ligand.py [-t rms_tolerance, -o outputfilename] -v
```
#### File: AutoDockTools/Utilities24/write_lowest_energy_ligand.py
```python
import os
from MolKit import Read
from AutoDockTools.Docking import Docking
if __name__ == '__main__':
import sys
import getopt
def usage():
"Print helpful, accurate usage statement to stdout."
print "Usage: write_lowest_energy_ligand.py -f dlgfilename"
print
print " Description of command..."
print " -f dlgfilename"
print " Optional parameters:"
print " [-v] verbose output"
print " [-o pdbqt_filename] (output filename)"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 'f:vo:h')
except getopt.GetoptError, msg:
print 'write_lowest_energy_ligand.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
#-f: dlgfilename
dlgfilename = None
# optional parameters
verbose = None
#-o outputfilename
outputfilename = None
#'f:vo:h'
for o, a in opt_list:
#print "o=", o, " a=", a
if o in ('-f', '--f'):
dlgfilename = a
if verbose: print 'set dlgfilename to ', a
if o in ('-v', '--v'):
verbose = True
if verbose: print 'set verbose to ', True
if o in ('-o', '--o'):
outputfilename = a
if verbose: print 'set outputfilename to ', a
if o in ('-h', '--'):
usage()
sys.exit()
if not dlgfilename:
print 'write_lowest_energy_ligand: dlgfilename must be specified.'
usage()
sys.exit()
#what about nucleic acids???
d = Docking()
d.readDlg(dlgfilename)
if verbose: print 'read ', dlgfilename
key0 = d.clusterer.clustering_dict.keys()[0]
conf0 = d.clusterer.clustering_dict[key0][0][0]
d.ch.set_conformation(conf0)
parser = d.ligMol.parser
lines = []
#have to add newline character to lines read from dlg
for l in parser.allLines:
l+= '\n'
lines.append(l)
parser.allLines = lines
coords = d.ligMol.allAtoms.coords
if outputfilename is None:
outputfilename = d.ligMol.name + '_BE.pdbqt'
parser.write_with_new_coords(coords, outputfilename)
if verbose:
print 'wrote %s' %outputfilename
# To execute this command type:
# write_lowest_energy_ligand.py -f dlgfilename [-o outputfilename] -v
```
#### File: AutoDockTools/Utilities24/write_vs_hits.py
```python
import os
from AutoDockTools.Docking import Docking
if __name__ == '__main__':
import sys
import getopt
def usage():
"""Print helpful, accurate usage statement to stdout."""
print "Usage: write_vs_hits.py -s summary_filename -d path_to_dockings"
print
print " Write result file of top conformations from VS."
print
print " Required parameters:"
print " -s name of summary file, eg 'summary_2.0.sort', produced in exercise10 of VS"
print " -p path_to_dockings containing files listed in summary file"
print " Optional parameters:"
print " [-f pdbqt_filename] file to create. Default is 'vs_results.pdbqt'"
print " [-A] output ATOM and HETATM records only "
print " [-v] verbose output"
print " [-D] debugging output"
# process command arguments
try:
opt_list, args = getopt.getopt(sys.argv[1:], 's:p:f:Avh')
except getopt.GetoptError, msg:
print 'write_vs_hits.py: %s' %msg
usage()
sys.exit(2)
# initialize required parameters
#-s: summary_filename
summary_filename = None
#-p: path_to_dockings
path_to_dockings = None
# optional parameters
#-f: pdbqtfilename
pdbqt_filename = "vs_results.pdbqt"
verbose = None
atom_records_only = False
for o, a in opt_list:
if o in ('-s', '--s'):
summary_filename = a
if verbose: print "set summary_filename %s" % summary_filename
if o in ('-p', '--p'):
path_to_dockings = a
if verbose: print "set path_to_dockings %s" % path_to_dockings
if o in ('-f', '--f'):
pdbqt_filename = a
if verbose: print "set pdbqt_filename to %s" % pdbqt_filename
if o in ('-A', '--A'):
atom_records_only = True
if verbose: print "set print ATOM and HETATM records only to %s" % atom_records_only
if o in ('-v', '--v'):
if verbose: print "set verbose to %s" % verbose
if o in ('-h', '--'):
usage()
sys.exit(2)
# make sure summary_filename and path_to_dockings were specified
if not summary_filename:
print 'write_vs_hits: summary_filename must be specified.'
usage()
if not path_to_dockings:
print 'write_vs_hits: path_to_dockings must be specified.'
usage()
sys.exit(2)
# make sure summary_filename exists
try:
os.stat(summary_filename)
except OSError, msg:
print "write_vs_hits: %s: %s", msg.strerror, msg.filename
sys.exit()
fileptr = open(summary_filename, 'r')
all_lines = fileptr.readlines()
fileptr.close()
if not len(all_lines):
print "write_vs_hits: no useable lines in %s", summary_filename
sys.exit()
#ctr will be recorded in the residue field (18-20, 1-based)
ctr = 1
optr = open(pdbqt_filename, 'w')
for line in all_lines:
#sample line to use:
#ZINC00057384_x1hpv/ZINC00057384_x1hpv, 20, 4, 10, -9.0900....
#skip the header line
if line.find('lowestEnergy')>-1:
#lowestEnergy dlgfn #runs #cl #LEC LE rmsd largestCl_dlgfn ...
continue
#write line from summary_filename
ostr = "REMARK %s"%line
optr.write(ostr)
#find the docking log filename
ll = line.split()
fn = ll[0].strip()[:-1]
dlgFN = path_to_dockings + "/" + fn +".dlg"
#create a docking
d = Docking()
d.readDlg(dlgFN)
#set ligand to lowest energy conformation LE
cluD = d.clusterer.clustering_dict
rms_tol = cluD.keys()[0]
LE = cluD[rms_tol][0][0]
d.ch.set_conformation(LE)
#get coordinates of LE conformation
crds = d.ligMol.allAtoms.coords[:]
#use the parser to get newlines to output
lines_to_print = d.ligMol.parser.write_with_new_coords(crds)
#edit these lines, adding new line + changing the RES field to current count
for nl in lines_to_print:
if nl[-1]!="\n":
nl += "\n"
if atom_records_only:
if nl.find("ATOM")!=0 and nl.find("HETA")!=0:
#skip lines of ligand keywords, eg ROOT
continue
#replace the RES field with current count
nl = nl[:17] + "%3s"%ctr + nl[20:]
optr.write(nl)
if verbose: print "onto next vs hit line"
ctr+=1
optr.close()
# To execute this command type:
# write_vs_hits.py -s summary_filename -o pdbqt_filename -v
```
#### File: Adt/Input/GPFTemplateBrowser.py
```python
from NetworkEditor.items import NetworkNode
from AutoDockTools.VisionInterface.Adt.gpf_template import gpf_template
class GPFTemplateBrowser(NetworkNode):
"""
A node that allows the user to browse for a GPF template with the extension .gpf
Input: GPF template file with the extension .gpf
Output: gpf_template object that contains info about the GPF template file
"""
def __init__(self, name='GPFTemplateBrowser', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='gpf_template_file')
filetypes = [('All supported files', '*.gpf')]
self.widgetDescr['gpf_template_file'] = {
'class':'NEEntryWithFileBrowser', 'master':'node', 'width':20,
'filetypes':filetypes,
'initialValue':'', 'labelCfg':{'text':'GPF template file: '}
}
op = self.outputPortsDescr
op.append(datatype='gpf_template', name='gpf_template')
code = """def doit(self, gpf_template_file):
import os
from AutoDockTools.VisionInterface.Adt.gpf_template import gpf_template
gpf_template_file = os.path.abspath(gpf_template_file)
if not(os.path.exists(gpf_template_file)):
print "ERROR: GPF template file " + gpf_template_file + " does not exist!"
return 'stop'
gpf_template = gpf_template(gpf_template_file)
self.outputData(gpf_template=gpf_template)
"""
self.setFunction(code)
```
#### File: Adt/Input/PreparedStructureBrowser.py
```python
from NetworkEditor.items import NetworkNode
from AutoDockTools.VisionInterface.Adt.receptor import receptor
import os
class PreparedStructureBrowser(NetworkNode):
"""
Allows the user to browse a structure prepared pdbqt structure.
"""
def __init__(self, name='StructureBrowser', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='prepared_structure_file')
filetypes = [('All supported files', '*.pdbqt')]
self.widgetDescr['prepared_structure_file'] = {
'class':'NEEntryWithFileBrowser', 'master':'node', 'width':20,
'filetypes':filetypes,
'initialValue':'', 'labelCfg':{'text':'Prepared Structure file: '}
}
op = self.outputPortsDescr
op.append(datatype='receptor_prepared', name='receptor_obj')
code = """def doit(self, prepared_structure_file):
import os
receptor_file = os.path.abspath(prepared_structure_file)
if not(os.path.exists(prepared_structure_file)):
print "ERROR: prepared structure file " + prepared_structure_file + " does not exist!"
return 'stop'
receptor_obj = receptor(prepared_structure_file)
self.outputData(receptor_obj=receptor_obj)
"""
self.setFunction(code)
```
#### File: VisionInterface/Adt/LigandDB.py
```python
import os
import tempfile
import zipfile
import string, types, re
from AutoDockTools.filterLigands import CalculateProperties, PropertyTable, LigandList, FilterLigands
class LigandDB:
"""Ligand Library Object
"""
# def __init__(self, server_lib=None, url_lib=None, filter_file=None, accepted=None):
def __init__(self, server_lib=None, url_lib=None):
self.server_lib = server_lib
self.url_lib = url_lib
# self.accepted = accepted
self.accepted = None
self.property_file = None
self.propertyTable = None
# if filter_file == None:
# self.filter_file = os.path.abspath('filtered_ligands.txt')
# else:
# self.filter_file = os.path.abspath(filter_file)
self.filter_file = None
if self.server_lib != None:
import urllib
slu = "http://kryptonite.nbcr.net/ligand_props/" + server_lib + ".prop"
pt = PropertyTable(url=slu)
self.propertyTable = pt
self.loc = self.server_lib
self.loc_type = "server_lib"
elif self.url_lib != None:
import urllib
slu = url_lib + "/lib.prop"
#print slu
pt = PropertyTable(url=slu)
self.propertyTable = pt
self.loc = self.url_lib
self.loc_type = "url_lib"
# if accepted == None:
# lfilter = FilterLigands()
# accepted, rejected = lfilter.filterTable(self.propertyTable)
# self.SetAcceptedLigands(accepted.filenames)
# else:
# f = open(self.filter_file, 'w')
# for i in self.accepted:
# f.write(i + '''
#''')
# f.close()
def SetAcceptedLigands(self, accept_list, filter_file=None):
if filter_file == None:
workingDir = tempfile.mkdtemp()
filter_file = workingDir + os.sep + 'filtered_ligands.txt'
self.accepted = accept_list
self.filter_file = filter_file
f = open(self.filter_file, 'w')
for i in self.accepted:
f.write(i + '''
''')
f.close()
def GetPropertyFile(self):
return self.property_file
```
#### File: Adt/Macro/AutodockVsCSF.py
```python
from NetworkEditor.macros import MacroNode
class AutodockVsCSF(MacroNode):
"""
Runs Autodock Virtual Screening on several remote servers with CSF meta scheduler
Inputs:
port 1: LigandDB object containing info about the ligand library
port 2: autogrid_result object containing info about autogrid results
port 3: DPF template object
Outputs:
port 1: string containing URL to autodock virtual screening results
"""
def __init__(self, constrkw={}, name='AutodockVsCSF', **kw):
kw['name'] = name
apply( MacroNode.__init__, (self,), kw)
def beforeAddingToNetwork(self, net):
MacroNode.beforeAddingToNetwork(self, net)
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
net.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from WebServices.VisionInterface.WSNodes import addOpalServerAsCategory
try:
addOpalServerAsCategory("http://oolitevm.calit2.optiputer.net/opal2", replace=False)
except:
pass
try:
addOpalServerAsCategory("http://kryptonite.nbcr.net/opal2", replace=False)
except:
pass
def afterAddingToNetwork(self):
masterNet = self.macroNetwork
from NetworkEditor.macros import MacroNode
MacroNode.afterAddingToNetwork(self)
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
## building macro network ##
AutodockVsCSF_0 = self
from traceback import print_exc
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from WebServices.VisionInterface.WSNodes import addOpalServerAsCategory
try:
addOpalServerAsCategory("http://oolitevm.calit2.optiputer.net/opal2", replace=False)
except:
pass
try:
addOpalServerAsCategory("http://kryptonite.nbcr.net/opal2", replace=False)
except:
pass
try:
## saving node input Ports ##
input_Ports_1 = self.macroNetwork.ipNode
apply(input_Ports_1.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore MacroInputNode named input Ports in network self.macroNetwork"
print_exc()
input_Ports_1=None
try:
## saving node output Ports ##
output_Ports_2 = self.macroNetwork.opNode
apply(output_Ports_2.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
output_Ports_2.move(183, 363)
except:
print "WARNING: failed to restore MacroOutputNode named output Ports in network self.macroNetwork"
print_exc()
output_Ports_2=None
try:
## saving node PrepareADVSInputs ##
from Vision.StandardNodes import Generic
PrepareADVSInputs_3 = Generic(constrkw={}, name='PrepareADVSInputs', library=stdlib)
self.macroNetwork.addNode(PrepareADVSInputs_3,217,76)
apply(PrepareADVSInputs_3.addInputPort, (), {'singleConnection': True, 'name': 'ligands', 'cast': True, 'datatype': 'LigandDB', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'rect', 'color': '#FFCCFF', 'originalDatatype': 'None'})
apply(PrepareADVSInputs_3.addInputPort, (), {'singleConnection': True, 'name': 'autogrid_results', 'cast': True, 'datatype': 'autogrid_results', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'triangle', 'color': '#FF33CC', 'originalDatatype': 'None'})
apply(PrepareADVSInputs_3.addInputPort, (), {'singleConnection': True, 'name': 'dpf_template_obj', 'cast': True, 'datatype': 'dpf_template', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'triangle', 'color': '#9933FF', 'originalDatatype': 'None'})
apply(PrepareADVSInputs_3.addOutputPort, (), {'name': 'filter_file', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(PrepareADVSInputs_3.addOutputPort, (), {'name': 'ligand_lib', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(PrepareADVSInputs_3.addOutputPort, (), {'name': 'dpf_template_file', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(PrepareADVSInputs_3.addOutputPort, (), {'name': 'autogrid_res_url', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(PrepareADVSInputs_3.addOutputPort, (), {'name': 'autogrid_res_local', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
code = """def doit(self, ligands, autogrid_results, dpf_template_obj):
dpf = dpf_template_obj.fullpath
if not(os.path.exists(dpf)):
print "ERROR: DPF template " + dpf + " does not exist!"
return '''stop'''
filter_file = ligands.filter_file
if autogrid_results.type == '''url''':
autogrid_result_url = autogrid_results.path
autogrid_result_local = ""
else:
autogrid_result_url = ""
autogrid_result_local = autogrid_results.path
ligand_lib = ligands.loc
pass
self.outputData(filter_file=filter_file, ligand_lib=ligand_lib, dpf_template_file=dpf, autogrid_res_url=autogrid_result_url, autogrid_res_local=autogrid_result_local)
## to ouput data on port filter_file use
## self.outputData(filter_file=data)
## to ouput data on port ligand_lib use
## self.outputData(ligand_lib=data)
## to ouput data on port dpf_template_file use
## self.outputData(dpf_template_file=data)
## to ouput data on port autogrid_res_url use
## self.outputData(autogrid_res_url=data)
## to ouput data on port autogrid_res_local use
## self.outputData(autogrid_res_local=data)
"""
PrepareADVSInputs_3.configure(function=code)
apply(PrepareADVSInputs_3.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore Generic named PrepareADVSInputs in network self.macroNetwork"
print_exc()
PrepareADVSInputs_3=None
try:
## saving node autodock_kryptonite_nbcr_net ##
from NetworkEditor.items import FunctionNode
autodock_kryptonite_nbcr_net_4 = FunctionNode(functionOrString='autodock_kryptonite_nbcr_net', host="http://kryptonite.nbcr.net/opal2", namedArgs={'ga_run': '', 'lib': '', 'filter_file_url': '', 'ga_num_evals': '', 'filter_file': '', 'sched': 'SGE', 'urllib': '', 'ga_num_generations': '', 'dpf': '', 'u': '', 'utar': '', 'userlib': '', 'ga_pop_size': '', 'localRun': False, 'email': '', 'execPath': ''}, constrkw={'functionOrString': "'autodock_kryptonite_nbcr_net'", 'host': '"http://kryptonite.nbcr.net/opal2"', 'namedArgs': {'ga_run': '', 'lib': '', 'filter_file_url': '', 'ga_num_evals': '', 'filter_file': '', 'sched': 'SGE', 'urllib': '', 'ga_num_generations': '', 'dpf': '', 'u': '', 'utar': '', 'userlib': '', 'ga_pop_size': '', 'localRun': False, 'email': '', 'execPath': ''}}, name='autodock_kryptonite_nbcr_net', library=wslib)
self.macroNetwork.addNode(autodock_kryptonite_nbcr_net_4,217,132)
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['ga_run'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['lib'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file_url'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['ga_num_evals'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['sched'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['urllib'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['ga_num_generations'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['dpf'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['u'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['utar'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['userlib'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['ga_pop_size'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['localRun'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['email'].configure, (), {'defaultValue': None})
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['execPath'].configure, (), {'defaultValue': None})
autodock_kryptonite_nbcr_net_4.inputPortByName['ga_run'].widget.set(r"", run=False)
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['lib'].widget.configure, (), {'choices': ('sample', 'NCIDS_SC', 'NCI_DS1', 'NCI_DS2', 'human_metabolome', 'chembridge_building_blocks', 'drugbank_nutraceutics', 'drugbank_smallmol', 'fda_approved')})
autodock_kryptonite_nbcr_net_4.inputPortByName['lib'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file_url'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['ga_num_evals'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file'].rebindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['filter_file'].unbindWidget()
apply(autodock_kryptonite_nbcr_net_4.inputPortByName['sched'].widget.configure, (), {'choices': ('SGE', 'CSF')})
autodock_kryptonite_nbcr_net_4.inputPortByName['sched'].widget.set(r"CSF", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['urllib'].rebindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['urllib'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['urllib'].unbindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['ga_num_generations'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['dpf'].rebindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['dpf'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['dpf'].unbindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['u'].rebindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['u'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['u'].unbindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['utar'].rebindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['utar'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['utar'].unbindWidget()
autodock_kryptonite_nbcr_net_4.inputPortByName['userlib'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['ga_pop_size'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['localRun'].widget.set(0, run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['email'].widget.set(r"", run=False)
autodock_kryptonite_nbcr_net_4.inputPortByName['execPath'].widget.set(r"", run=False)
apply(autodock_kryptonite_nbcr_net_4.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore FunctionNode named autodock_kryptonite_nbcr_net in network self.macroNetwork"
print_exc()
autodock_kryptonite_nbcr_net_4=None
try:
## saving node GetMainURLFromList ##
from WebServices.VisionInterface.WSNodes import GetMainURLFromListNode
GetMainURLFromList_5 = GetMainURLFromListNode(constrkw={}, name='GetMainURLFromList', library=wslib)
self.macroNetwork.addNode(GetMainURLFromList_5,217,188)
apply(GetMainURLFromList_5.inputPortByName['urls'].configure, (), {'defaultValue': None})
apply(GetMainURLFromList_5.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore GetMainURLFromListNode named GetMainURLFromList in network self.macroNetwork"
print_exc()
GetMainURLFromList_5=None
try:
## saving node GetMainURLFromList ##
from WebServices.VisionInterface.WSNodes import GetMainURLFromListNode
GetMainURLFromList_7 = GetMainURLFromListNode(constrkw={}, name='GetMainURLFromList', library=wslib)
self.macroNetwork.addNode(GetMainURLFromList_7,201,301)
apply(GetMainURLFromList_7.inputPortByName['urls'].configure, (), {'defaultValue': None})
apply(GetMainURLFromList_7.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore GetMainURLFromListNode named GetMainURLFromList in network self.macroNetwork"
print_exc()
GetMainURLFromList_7=None
try:
## saving node AutodockSlice_oolitevm_calit2_optiputer_net ##
from NetworkEditor.items import FunctionNode
AutodockSlice_oolitevm_calit2_optiputer_net_8 = FunctionNode(functionOrString='AutodockSlice_oolitevm_calit2_optiputer_net', host="http://oolitevm.calit2.optiputer.net/opal2", namedArgs={'execPath': '', 'localRun': False, 'divisor': '', 'lib': '', 'input_url': ''}, constrkw={'functionOrString': "'AutodockSlice_oolitevm_calit2_optiputer_net'", 'host': '"http://oolitevm.calit2.optiputer.net/opal2"', 'namedArgs': {'execPath': '', 'localRun': False, 'divisor': '', 'lib': '', 'input_url': ''}}, name='AutodockSlice_oolitevm_calit2_optiputer_net', library=wslib)
self.macroNetwork.addNode(AutodockSlice_oolitevm_calit2_optiputer_net_8,200,240)
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['execPath'].configure, (), {'defaultValue': None})
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['localRun'].configure, (), {'defaultValue': None})
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['divisor'].configure, (), {'defaultValue': None})
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['lib'].configure, (), {'defaultValue': None})
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['input_url'].configure, (), {'defaultValue': None})
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['execPath'].widget.set(r"", run=False)
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['localRun'].widget.set(0, run=False)
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['divisor'].widget.set(r"", run=False)
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['lib'].rebindWidget()
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['lib'].widget.set(r"", run=False)
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['lib'].unbindWidget()
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['input_url'].rebindWidget()
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['input_url'].widget.set(r"", run=False)
AutodockSlice_oolitevm_calit2_optiputer_net_8.inputPortByName['input_url'].unbindWidget()
apply(AutodockSlice_oolitevm_calit2_optiputer_net_8.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore FunctionNode named AutodockSlice_oolitevm_calit2_optiputer_net in network self.macroNetwork"
print_exc()
AutodockSlice_oolitevm_calit2_optiputer_net_8=None
#self.macroNetwork.run()
self.macroNetwork.freeze()
## saving connections for network AutodockVsCSF ##
if autodock_kryptonite_nbcr_net_4 is not None and GetMainURLFromList_5 is not None:
try:
self.macroNetwork.connectNodes(
autodock_kryptonite_nbcr_net_4, GetMainURLFromList_5, "result", "urls", blocking=True
, splitratio=[0.36974288957131424, 0.63465596053596318])
except:
print "WARNING: failed to restore connection between autodock_kryptonite_nbcr_net_4 and GetMainURLFromList_5 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and autodock_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, autodock_kryptonite_nbcr_net_4, "filter_file", "filter_file", blocking=True
, splitratio=[0.33230642287344903, 0.65770700108889613])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and autodock_kryptonite_nbcr_net_4 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and autodock_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, autodock_kryptonite_nbcr_net_4, "ligand_lib", "urllib", blocking=True
, splitratio=[0.50680104599665787, 0.51414170500293577])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and autodock_kryptonite_nbcr_net_4 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and autodock_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, autodock_kryptonite_nbcr_net_4, "dpf_template_file", "dpf", blocking=True
, splitratio=[0.51615646597598808, 0.25661305528484007])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and autodock_kryptonite_nbcr_net_4 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and autodock_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, autodock_kryptonite_nbcr_net_4, "autogrid_res_url", "u", blocking=True
, splitratio=[0.5760732944947704, 0.2032376887917188])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and autodock_kryptonite_nbcr_net_4 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and autodock_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, autodock_kryptonite_nbcr_net_4, "autogrid_res_local", "utar", blocking=True
, splitratio=[0.52802808938949819, 0.66978534572736881])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and autodock_kryptonite_nbcr_net_4 in network self.macroNetwork"
input_Ports_1 = self.macroNetwork.ipNode
if input_Ports_1 is not None and PrepareADVSInputs_3 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, PrepareADVSInputs_3, "new", "ligands", blocking=True
, splitratio=[0.23314258225660414, 0.72184112037432979])
except:
print "WARNING: failed to restore connection between input_Ports_1 and PrepareADVSInputs_3 in network self.macroNetwork"
if input_Ports_1 is not None and PrepareADVSInputs_3 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, PrepareADVSInputs_3, "new", "autogrid_results", blocking=True
, splitratio=[0.56916626620432731, 0.43089669830392019])
except:
print "WARNING: failed to restore connection between input_Ports_1 and PrepareADVSInputs_3 in network self.macroNetwork"
if input_Ports_1 is not None and PrepareADVSInputs_3 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, PrepareADVSInputs_3, "new", "dpf_template_obj", blocking=True
, splitratio=[0.26502286453989665, 0.3911248444502638])
except:
print "WARNING: failed to restore connection between input_Ports_1 and PrepareADVSInputs_3 in network self.macroNetwork"
output_Ports_2 = self.macroNetwork.opNode
if GetMainURLFromList_7 is not None and output_Ports_2 is not None:
try:
self.macroNetwork.connectNodes(
GetMainURLFromList_7, output_Ports_2, "newurl", "new", blocking=True
, splitratio=[0.2408747073082603, 0.22897876889044461])
except:
print "WARNING: failed to restore connection between GetMainURLFromList_7 and output_Ports_2 in network self.macroNetwork"
if PrepareADVSInputs_3 is not None and AutodockSlice_oolitevm_calit2_optiputer_net_8 is not None:
try:
self.macroNetwork.connectNodes(
PrepareADVSInputs_3, AutodockSlice_oolitevm_calit2_optiputer_net_8, "ligand_lib", "lib", blocking=True
, splitratio=[0.36439875698533941, 0.58443612376117082])
except:
print "WARNING: failed to restore connection between PrepareADVSInputs_3 and AutodockSlice_oolitevm_calit2_optiputer_net_8 in network self.macroNetwork"
if GetMainURLFromList_5 is not None and AutodockSlice_oolitevm_calit2_optiputer_net_8 is not None:
try:
self.macroNetwork.connectNodes(
GetMainURLFromList_5, AutodockSlice_oolitevm_calit2_optiputer_net_8, "newurl", "input_url", blocking=True
, splitratio=[0.32808833199778697, 0.69237553555389719])
except:
print "WARNING: failed to restore connection between GetMainURLFromList_5 and AutodockSlice_oolitevm_calit2_optiputer_net_8 in network self.macroNetwork"
if AutodockSlice_oolitevm_calit2_optiputer_net_8 is not None and GetMainURLFromList_7 is not None:
try:
self.macroNetwork.connectNodes(
AutodockSlice_oolitevm_calit2_optiputer_net_8, GetMainURLFromList_7, "result", "urls", blocking=True
, splitratio=[0.69930142895840763, 0.2984777644803871])
except:
print "WARNING: failed to restore connection between AutodockSlice_oolitevm_calit2_optiputer_net_8 and GetMainURLFromList_7 in network self.macroNetwork"
self.macroNetwork.runOnNewData.value = True
## modifying MacroInputNode dynamic ports
input_Ports_1 = self.macroNetwork.ipNode
input_Ports_1.outputPorts[1].configure(name='PrepareADVSInputs_ligands')
input_Ports_1.outputPorts[2].configure(name='PrepareADVSInputs_autogrid_results')
input_Ports_1.outputPorts[3].configure(name='PrepareADVSInputs_dpf_template_obj')
## modifying MacroOutputNode dynamic ports
output_Ports_2 = self.macroNetwork.opNode
output_Ports_2.inputPorts[1].configure(singleConnection='auto')
output_Ports_2.inputPorts[1].configure(name='GetMainURLFromList_newurl')
## configure MacroNode input ports
AutodockVsCSF_0.inputPorts[0].configure(name='PrepareADVSInputs_ligands')
AutodockVsCSF_0.inputPorts[0].configure(datatype='LigandDB')
AutodockVsCSF_0.inputPorts[1].configure(name='PrepareADVSInputs_autogrid_results')
AutodockVsCSF_0.inputPorts[1].configure(datatype='autogrid_results')
AutodockVsCSF_0.inputPorts[2].configure(name='PrepareADVSInputs_dpf_template_obj')
AutodockVsCSF_0.inputPorts[2].configure(datatype='dpf_template')
## configure MacroNode output ports
AutodockVsCSF_0.outputPorts[0].configure(name='GetMainURLFromList_newurl')
AutodockVsCSF_0.outputPorts[0].configure(datatype='string')
AutodockVsCSF_0.shrink()
## reset modifications ##
AutodockVsCSF_0.resetTags()
AutodockVsCSF_0.buildOriginalList()
```
#### File: AutoDockTools/VisionInterface/AdtNodes.py
```python
import warnings
from Vision import UserLibBuild
from NetworkEditor.items import NetworkNode
from MolKit.molecule import Atom, AtomSet, Molecule, MoleculeSet
from MolKit.protein import Residue, ResidueSet, Chain, ChainSet
from AutoDockTools.atomTypeTools import AutoDock4_AtomTyper
from AutoDockTools.atomTypeTools import NonpolarHydrogenMerger, LonepairMerger
from AutoDockTools.atomTypeTools import AromaticCarbonManager, SolvationParameterizer
from AutoDockTools.MoleculePreparation import RotatableBondManager
from AutoDockTools.MoleculePreparation import LigandWriter, AD4LigandWriter
def importAdtLib(net):
try:
from AutoDockTools.VisionInterface.AdtNodes import adtlib
net.editor.addLibraryInstance(
adtlib, 'AutoDockTools.VisionInterface.AdtNodes', 'adtlib')
except:
warnings.warn(
'Warning! Could not import adtlib from AutoDockTools.VisionInterface')
class GridParameterFileBrowserNE(NetworkNode):
"""A specialized Tkinter Filebrowser. Double-clicking into the entry opens the
filebrowser."""
def __init__(self, name='Grid Parameter File Browser', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
#self.readOnly = 1
code = """def doit(self, filename):
if filename:
self.outputData(filename=filename)
"""
self.setFunction(code)
# show the entry widget by default
self.inNodeWidgetVisibleByDefault = True
fileTypes=[('gpf', '*')]
self.widgetDescr['filename'] = {
'class':'NEEntryWithFileBrowser', 'master':'node',
'filetypes':fileTypes, 'title':'read file', 'width':16,
'labelCfg':{'text':'gpf file:'},
}
#self.widgetDescr['filename'] = {
# 'class':'NEEntryWithFileBrowser', 'master':'node', 'width':16,
# 'initialValue':'', 'lockedOnPort':True,
# 'labelCfg':{'text':'Filename: '}
# }
self.inputPortsDescr.append(datatype='string', name='filename')
self.outputPortsDescr.append(datatype='string', name='filename')
class DockingParameterFileBrowserNE(NetworkNode):
"""A specialized Tkinter Filebrowser. Double-clicking into the entry opens the
filebrowser."""
def __init__(self, name='Docking Parameter File Browser', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
#self.readOnly = 1
code = """def doit(self, filename):
if filename:
self.outputData(filename=filename)
"""
self.setFunction(code)
# show the entry widget by default
self.inNodeWidgetVisibleByDefault = True
fileTypes=[('dpf', '*')]
self.widgetDescr['filename'] = {
'class':'NEEntryWithFileBrowser', 'master':'node',
'filetypes':fileTypes, 'title':'read file', 'width':16,
'labelCfg':{'text':'dpf file:'},
}
self.inputPortsDescr.append(datatype='string', name='filename')
self.outputPortsDescr.append(datatype='string', name='filename')
class ReadGridParameterFile(NetworkNode):
#mRequiredTypes = {}
#mRequiredSynonyms = [
#]
def __init__(self, constrkw = {}, name='ReadGridParameterFile', **kw):
kw['constrkw'] = constrkw
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
fileTypes=[('gpf', '*')]
self.widgetDescr['filename'] = {
'class':'NEEntryWithFileBrowser', 'master':'node',
'filetypes':fileTypes, 'title':'read file', 'width':16,
'labelCfg':{'text':'file:'},
}
code = """def doit(self, template_gpf_filename):
if template_gpf_filename:
from AutoDockTools.GridParameters import GridParameters
gpo = GridParameters()
gpo.read(template_gpf_filename)
self.outputData(gpo=gpo)
"""
self.configure(function=code)
self.inputPortsDescr.append(
{'name': 'template_gpf_filename', 'cast': True, 'datatype': 'string', 'balloon': 'template grid parameter filename', 'required': False, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
self.outputPortsDescr.append(
{'name': 'gpo', 'datatype': 'None', 'balloon': 'gpo, grid parameter object, instance of AutoDockTools.GridParameters', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.widgetDescr['template_gpf_filename'] = {
'initialValue': '', 'labelGridCfg': {'column': 0, 'row': 0}, 'master': 'node', 'widgetGridCfg': {'labelSide': 'left', 'column': 1, 'row': 0}, 'labelCfg': {'text': ''}, 'class': 'NEEntryWithFileBrowser'}
def beforeAddingToNetwork(self, net):
try:
ed = net.getEditor()
except:
import traceback; traceback.print_exc()
print 'Warning! Could not import widgets'
class ReadDockingParameterFile(NetworkNode):
#mRequiredTypes = {}
#mRequiredSynonyms = [
#]
def __init__(self, constrkw = {}, name='ReadDockingParameterFile', **kw):
kw['constrkw'] = constrkw
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
fileTypes=[('dpf', '*')]
self.widgetDescr['filename'] = {
'class':'NEEntryWithFileBrowser', 'master':'node',
'filetypes':fileTypes, 'title':'read file', 'width':16,
'labelCfg':{'text':'file:'},
}
code = """def doit(self, template_dpf_filename):
if template_dpf_filename:
from AutoDockTools.DockingParameters import DockingParameters
gpo = DockingParameters()
gpo.read(template_dpf_filename)
self.outputData(gpo=gpo)
"""
self.configure(function=code)
self.inputPortsDescr.append(
{'name': 'template_dpf_filename', 'cast': True, 'datatype': 'string', 'balloon': 'template grid parameter filename', 'required': False, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
self.outputPortsDescr.append(
{'name': 'gpo', 'datatype': 'None', 'balloon': 'gpo, grid parameter object, instance of AutoDockTools.DockingParameters', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.widgetDescr['template_dpf_filename'] = {
'initialValue': '', 'labelGridCfg': {'column': 0, 'row': 0}, 'master': 'node', 'widgetGridCfg': {'labelSide': 'left', 'column': 1, 'row': 0}, 'labelCfg': {'text': ''}, 'class': 'NEEntryWithFileBrowser'}
def beforeAddingToNetwork(self, net):
try:
ed = net.getEditor()
except:
import traceback; traceback.print_exc()
print 'Warning! Could not import widgets'
###class ReadGridParameterFile(NetworkNode):
### """Read a Grid Parameter file [using Python's readlines() command.]
###Double-clicking on the node opens a text entry widget to type the file name.
###In addition, double-clicking in the text entry opens a file browser window.
###Input Ports
### filename: name of the file to be opened
###Output Ports
### data: a list of strings
###"""
### def __init__(self, name='Read Parameter File', **kw):
### kw['name'] = name
### apply( NetworkNode.__init__, (self,), kw )
### #self.readOnly = 1
### code = """def doit(self, filename):
### if filename and len(filename):
### gpo = GridParameters()
### gpo.read(filename)
### #f = open(filename)
### #datastream = f.readlines()
### #f.close()
### #if datastream:
### self.outputData(data=gpo)
###"""
### self.setFunction(code)
### fileTypes=[('gpf', 'gpf')]
### self.widgetDescr['filename'] = {
### 'class':'NEEntryWithFileBrowser', 'master':'node',
### 'filetypes':fileTypes, 'title':'read file', 'width':16,
### 'labelCfg':{'text':'file:'},
### }
### self.inputPortsDescr.append(datatype='string', name='filename')
### self.outputPortsDescr.append(datatype='instance', name='gpo')
class RemoveWaters(NetworkNode):
""" removes water residues
Process entails:
# 1. looping over each molecule in input
# 2. selecting all atoms in water residues
# 3. removing all bonds from each atom
# 4. removing each atom from its parent residue
# 5. removing parent residue if it has no remaining atoms
# 6. removing parent chain if it has no remaining residues
# 7. resetting allAtoms attribute of molecule
# 8. returning number of water residues removed
Input: molecules (MoleculeSet)
Output: molecules where all atoms in HOH residues have been removed(MoleculeSet)"""
def __init__(self, name='RemoveWaters', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='molecules')
ip.append(datatype='str', required=False, name='residue_type_str', defaultValue='HOH')
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='molecules_with_no_water_residues')
op.append(datatype='int', name='num_water_res')
code = """def doit(self, molecules, residue_type_str):
if molecules:
from MolKit.molecule import BondSet
lenHOHs = 0
for mol in molecules:
hohs = mol.allAtoms.get(lambda x: x.parent.type==residue_type_str)
if hohs:
#remove(hohs)
lenHOHs = len(hohs)
for h in hohs:
for b in h.bonds:
c = b.atom1
if c==h:
c = b.atom2
c.bonds.remove(b)
h.bonds = BondSet()
res = h.parent
h.parent.remove(h)
if len(h.parent.children)==0:
res = h.parent
chain = res.parent
#print 'removing residue: ', res.name
chain.remove(res)
if len(chain.children)==0:
mol = chain.parent
print 'removing chain', chain.id
mol.remove(chain)
del chain
del res
del h
#fix allAtoms short cut
mol.allAtoms = mol.chains.residues.atoms
self.outputData(molecules_with_no_water_residues=molecules, num_water_res=lenHOHs)"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class MergeNonPolarHydrogens(NetworkNode):
""" merges nonpolar hydrogens
Process entails:
# 1. adding charge on nonpolar hydrogen to charge of carbon atom to which it is bonded
# 2. removing the nonpolar hydrogen from the molecule
# 3. resetting allAtoms attribute of molecule
# 4. returning number of nonpolar hydrogens removed
Input: mols (MoleculeSet)
Output: mols where each non-polar hydrogen atom has been removed(MoleculeSet)"""
def __init__(self, name='Nonpolar Hydrogen Merger', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols')
ip.append(datatype='int', required=False, name='renumber', defaultValue=1)
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='mols')
op.append(datatype='int', name='num_nphs')
code = """def doit(self,mols, renumber):
if mols:
nph_merger = NonpolarHydrogenMerger()
num_nphs = 0
for mol in mols:
if not len(mol.allAtoms.bonds[0]):
mol.buildBondsByDistance()
num_nphs = nph_merger.mergeNPHS(mol.allAtoms, renumber=renumber)
self.outputData(mols=mols, num_nphs=num_nphs)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class MergeLonePairs(NetworkNode):
""" merges lone pairs
Process entails:
# 1. adding charge on lone pair 'atom' to charge of carbon atom to which it is 'bonded'
# 2. removing the lone pair 'atom' from the molecule
# 3. resetting allAtoms attribute of molecule
# 4. returning number of lone pair 'atoms' removed
Input: mols (MoleculeSet)
Output: mols where each lone pair 'atom' has been removed(MoleculeSet)"""
def __init__(self, name='Lone Pair Merger', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols')
ip.append(datatype='int', required=False, name='renumber', defaultValue=1)
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='mols')
op.append(datatype='int', name='num_lps')
code = """def doit(self,mols, renumber):
if mols:
lps_merger = LonepairMerger()
num_lps = 0
for mol in mols:
if not len(mol.allAtoms.bonds[0]):
mol.buildBondsByDistance()
lps = lps_merger.mergeLPS(mol.allAtoms, renumber=renumber)
num_lps += len(lps)
self.outputData(mols=mols, num_lps=num_lps)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class ManageAromaticCarbons(NetworkNode):
""" manages assigning autodock carbon atom types: aliphatic and aromatic
Process entails:
# 1. 'setAromaticCarbons' method detects cyclic aromatic carbons: renaming
# them 'A' and setting autodock_element to 'A'. Cyclic carbons are 'aromatic'
# if the angle between adjacent normals is less than a specified 'cutoff'
# angle which is 7.5 degrees by default. Returns atoms which are changed
# 2. provides widget for changing the 'cutoff'
# 3. NOT_IMPLEMENTED:provides method 'set_carbon_names' for forcing any 'C' to 'A' and
# the opposite. Returns atoms which are changed
Input: mols (MoleculeSet)
Output: mols where aromatic carbons have been detected (MoleculeSet)"""
def __init__(self, name='Manage Aromatic Carbons', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['cutoff'] = {
'class':'NEDial', 'size':50,
'oneTurn':5.0, 'min':1.0, 'lockMin':1, 'type':'float',
'initialValue':7.5,
'labelGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cutoff'},
}
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols')
ip.append(datatype='float', required=False, name='cutoff', defaultValue=7.5)
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='mols')
op.append(datatype='int', name='num_aromaticCs')
code = """def doit(self, mols, cutoff):
if mols:
aromC_manager = AromaticCarbonManager(cutoff=cutoff)
num_aromCs = 0
for mol in mols:
if not len(mol.allAtoms.bonds[0]):
mol.buildBondsByDistance()
aromCs = aromC_manager.setAromaticCarbons(mol, cutoff=cutoff)
num_aromCs+=len(aromCs)
self.outputData(mols=mols, num_aromaticCs=num_aromCs)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class Assign_AD4Types(NetworkNode):
""" assigns autodock4-style 'autodock_element' to atoms
Process entails:
# 1. distinguishing between nitrogens which do accept hydrogen-bonds and
# those which do not (because they already have bonds to hydrogens)
# 2. distinguishing between oxygens which do accept hydrogen-bonds and
# those which do not (because they already have bonds to hydrogens)
# 3. setting autodock_element to 'A' for carbon atoms in cycles in standard amino acids
# 4. setting autodock_element to 'HD' for all hydrogen atoms
# 5. setting autodock_element for all other atoms to the atom's element
# NOTE: more types can be added if more distinctions are supported by
# autodock
Input: mols (MoleculeSet)
Output: typed_mols where each atom has autodock_element field(MoleculeSet)"""
def __init__(self, name='AD4_typer', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols')
ip.append(datatype='int', required=False, name='set_aromatic_carbons', defaultValue=1)
ip.append(datatype='int', required=False, name='reassign', defaultValue=1)
ip.append(datatype='int', required=False, name='renameAtoms', defaultValue=0)
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='typed_mols')
code = """def doit(self,mols, set_aromatic_carbons=1, reassign=1, renameAtoms=0):
if mols:
at_typer = AutoDock4_AtomTyper(set_aromatic_carbons=1, renameAtoms=renameAtoms)
for mol in mols:
if not len(mol.allAtoms.bonds[0]):
mol.buildBondsByDistance()
at_typer.setAutoDockElements(mol, reassign=reassign)
self.outputData(typed_mols=mols)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class Add_SolvationParameters(NetworkNode):
""" assigns autodock3-style 'solvation parameters' to atoms
Process entails:
# 1. distinguishing between aromatic and aliphatic carbons
# 2. look-up table of solvation volumes (AtSolVol)
# 3. setting AtSolPar and AtVol
Input: mols (MoleculeSet)
Output: typed_mols where each atom has SolVol and AtSolPar fields(MoleculeSet)"""
def __init__(self, name='AD4_SolvationParameterizer', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols')
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='typed_mols')
op.append(datatype='list', name='AtSolPar')
code = """def doit(self,mols):
if mols:
SP = SolvationParameterizer()
for mol in mols:
unknown_atoms = SP.addParameters(mol.chains.residues.atoms)
#?keep information about unknown_atoms?
if unknown_atoms is not None: mol.unknown_atoms = len(unknown_atoms)
self.outputData(typed_mols=mols, AtSolPar=mols.allAtoms.AtSolPar)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class ManageRotatableBonds(NetworkNode):
""" manages setting flexibility pattern in molecule
Process entails:
# 1. distinguishing between possibly-rotatable and non-rotatable bonds
# 2. turning on/off classes of possibly-rotatable bonds such as
# amide, guanidinium, peptide-backbone
# 3. optionally turning on/off specific bonds between named atoms
# 4. optionally limiting the total number of rotatable bonds
# toggling either:
# those which move the most atoms
# or
# those which move the fewest atoms
Input: mol (Molecule)
Output: mol with marked bonds """
def __init__(self, name='Manage Rotatable Bonds', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MoleculeSet', name='mols', defaultValue='auto')
ip.append(datatype='string', required=False, name='root')
ip.append(datatype='string', required=False, name='allowed_bonds', defaultValue='backbone')
ip.append(datatype='int', required=False, name='check_for_fragments', defaultValue=0)
ip.append(datatype='string', required=False, name='bonds_to_inactivate', defaultValue='')
ip.append(datatype='string', required=False, name='limit_torsions', defaultValue='')
op = self.outputPortsDescr
op.append(datatype='MoleculeSet', name='mols')
code = """def doit(self, mols, root, allowed_bonds, check_for_fragments,
bonds_to_inactivate, limit_torsions):
if mols:
#mol = mols[0]
for mol in mols:
if not len(mol.allAtoms.bonds[0]):
mol.buildBondsByDistance()
print "root=", root
mol.RBM = RotatableBondManager(mol, allowed_bonds, root,
check_for_fragments=check_for_fragments,
bonds_to_inactivate=bonds_to_inactivate)
if limit_torsions:
mol.RBM.limit_torsions(limit_torsions)
self.outputData(mols=mols)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class Ligand_Writer(NetworkNode):
""" writes autodock3 ligand pdbq file
Process entails:
# 1. writing REMARK records about torsions
# 2. writing ROOT/ENDROOT records about rigid portion of ligand
# 3. writing BRANCH/ENDBRANCH records about movable sections of ligand
# 4. writing TORSDOF record showing torsional degrees of freedom
Input: mol (Molecule), output_filename (string)
Output: mol """
def __init__(self, name='Ligand_Writer', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
fileTypes=[('pdbq', '*.pdbq'), ('all', '*')]
self.widgetDescr['output_filename'] = {
'class':'NEEntryWithFileSaver', 'master':'node',
'filetypes':fileTypes, 'title':'save AD3 Ligand', 'width':10,
'labelCfg':{'text':'file:'},
}
ip = self.inputPortsDescr
ip.append(datatype='Molecule', name='mol')
ip.append(datatype='string', name='output_filename')
op = self.outputPortsDescr
op.append(datatype='Molecule', name='mol')
code = """def doit(self, mol, output_filename):
if mol:
#mol = mols[0]
#check for bonds with 'possibleTors/activeTOrs keys'
#check for root
#check for TORSDOF
#check for charges
writer = LigandWriter()
writer.write(mol, output_filename)
self.outputData(mol=mol)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class Ligand_Writer_AD4(NetworkNode):
""" writes autodock4 ligand pdbqt file
Process entails:
# 1. writing REMARK records about torsions
# 2. writing ROOT/ENDROOT records about rigid portion of ligand
# 3. writing BRANCH/ENDBRANCH records about movable sections of ligand
# 4. writing TORSDOF record showing torsional degrees of freedom
Input: mol (Molecule), output_filename (string)
Output: mol, output_filename """
def __init__(self, name='Ligand_Writer_AD4', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
fileTypes=[('pdbqt', '*.pdbqt'), ('all', '*')]
self.widgetDescr['output_filename'] = {
'class':'NEEntryWithFileSaver', 'master':'node',
'filetypes':fileTypes, 'title':'save AD4 Ligand', 'width':10,
'labelCfg':{'text':'file:'},
}
ip = self.inputPortsDescr
ip.append(datatype='Molecule', name='mol')
ip.append(datatype='string', name='output_filename')
op = self.outputPortsDescr
op.append(datatype='Molecule', name='mol')
op.append(datatype='string', name='output_filename')
code = """def doit(self, mol, output_filename):
if mol:
writer = AD4LigandWriter()
writer.write(mol, output_filename)
self.outputData(mol=mol, output_filename=output_filename)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
####class AdtPrepareLigand(NetworkNode):
#### """ formats ligand for autodock3 using AutoDockTools.MoleculePreparation.LigandPreparation.
####Process entails:
#### 1. possible clean_up:
#### removing lone pairs
#### merging non_polar hydrogens
#### adding bonds to atoms with no bonds
#### 2. making atoms in ligand conform to autodock3 atom types:
#### distinction between carbons and cyclic-aromatic carbons,
#### no non-polar hydrogens
#### 3. adding partial charges (gasteiger by default)
#### 4. establishing 'torTree' for flexibility pattern by setting 'root' and 'rotatable' bonds
#### 5. writing 'pdbq' file
####Input: mols (MoleculeSet)
####Output: AD3ligand (Molecule)"""
###class Adt4PrepareLigand(NetworkNode):
### """ formats ligand for autodock4 using AutoDockTools.MoleculePreparation.AD4LigandPreparation.
###Process entails:
### 1. possible clean_up:
### removing lone pairs
### merging non_polar hydrogens
### adding bonds to atoms with no bonds
### 2. making atoms in ligand conform to autodock3 atom types:
### distinction between carbons and cyclic-aromatic carbons,
### no non-polar hydrogens
### 3. adding partial charges (gasteiger by default)
### 4. establishing 'torTree' for flexibility pattern by setting 'root' and 'rotatable' bonds
### 5. writing 'pdbqt' file
###Input: mols (MoleculeSet)
###Output: AD4ligand (Molecule)"""
###class AdtPrepareReceptor(NetworkNode):
### """ formats receptor for autodock3 using AutoDockTools.MoleculePreparation.ReceptorPreparation.
###Process entails:
### 1. possible clean_up:
### removing lone pairs
### merging non_polar hydrogens
### adding bonds to atoms with no bonds
### 2. making atoms in receptor conform to autodock3 atom types:
### distinction between carbons and cyclic-aromatic carbons,
### polar hydrogens but no non-polar hydrogens
### 3. adding partial charges (Kollman by default)
### 4. writing 'pdbqs' file
###Input: mols (MoleculeSet)
###Output: AD3receptor (Molecule)"""
###class Adt4PrepareReceptor(NetworkNode):
### """ formats receptor for autodock4 using AutoDockTools.MoleculePreparation.AD4ReceptorPreparation.
###Process entails:
### 1. possible clean_up:
### removing lone pairs
### merging non_polar hydrogens
### adding bonds to atoms with no bonds
### 2. making atoms in receptor conform to autodock4 atom types:
### distinction between carbons and cyclic-aromatic carbons,
### distinction between hydrogen-bonding and non-hydrogen-bonding nitrogens,
### no non-polar hydrogens
### 3. adding partial charges (gasteiger by default)
### 4. writing 'pdbqt' file
###Input: mols (MoleculeSet)
###Output: AD4receptor (Molecule)"""
class AdtPrepareGpf3(NetworkNode):
""" writes parameter file for autogrid3
Process entails:
1. setting ligand
2. setting receptor
3. setting specified values of various parameters
4. writing gpf file for autogrid3
Input: ligand_filename, receptor_filename, optional parameter dictionary
Output: gpf ('string')"""
def __init__(self, name='Prepare Autogrid3 Gpf', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='ligand_filename')
ip.append(datatype='string', name='receptor_filename')
ip.append(datatype='string', required=False, name='gpf_filename', defaultValue='')
ip.append(datatype='dict', required=False, name='parameters', defaultValue={})
ip.append(datatype='string', required=False, name='outputfilename', defaultValue='')
op = self.outputPortsDescr
op.append(datatype='string', name='ag3_parameter_file')
code = """def doit(self, ligand_filename, receptor_filename, gpf_filename, parameters, outputfilename):
if ligand_filename and receptor_filename:
from AutoDockTools.GridParameters import GridParameterFileMaker
gpfm = GridParameterFileMaker()
gpfm.set_ligand(ligand_filename)
gpfm.set_receptor(receptor_filename)
if gpf_filename:
gpfm.read_reference(gpf_filename)
if len(parameters):
gpfm.set_grid_parameters(parameters)
if not outputfilename:
outputfilename = gpfm.ligand.name+'_'+gpfm.receptor_stem + ".gpf"
gpfm.write_gpf(outputfilename)
self.outputData(ag3_parameter_file=outputfilename)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class AdtPrepareGpf4(NetworkNode):
""" writes parameter file for autogrid4
Process entails:
1. setting ligand
2. setting receptor
3. setting specified values of various parameters
4. writing gpf file for autogrid4
Input: ligand_filename, receptor_filename, optional parameter dictionary
Output: gpf ('string')"""
def __init__(self, name='Prepare Autogrid4 Gpf', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='ligand_filename')
ip.append(datatype='string', name='receptor_filename')
ip.append(datatype='string', required=False, name='gpf_filename', defaultValue='')
ip.append(datatype='dict', required=False, name='parameters', defaultValue={})
ip.append(datatype='string', required=False, name='outputfilename', defaultValue='')
op = self.outputPortsDescr
op.append(datatype='string', name='ag4_parameter_file')
code = """def doit(self, ligand_filename, receptor_filename, gpf_filename, parameters, outputfilename):
if ligand_filename and receptor_filename:
from AutoDockTools.GridParameters import GridParameter4FileMaker
gpfm = GridParameter4FileMaker()
gpfm.set_ligand(ligand_filename)
gpfm.set_receptor(receptor_filename)
if gpf_filename:
gpfm.read_reference(gpf_filename)
if len(parameters):
gpfm.set_grid_parameters(parameters)
if not outputfilename:
outputfilename = gpfm.ligand.name+'_'+gpfm.receptor_stem + ".gpf"
gpfm.write_gpf(outputfilename)
self.outputData(ag4_parameter_file=outputfilename)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class AdtPrepareDpf3(NetworkNode):
""" writes parameter file for autodock3
Process entails:
1. setting ligand
2. setting receptor
3. setting specified values of various parameters
4. writing dpf file for autogrid3
Input: ligand_filename, receptor_filename, optional parameter dictionary
Output: dpf ('string')"""
def __init__(self, name='Prepare Autodock3 Dpf', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='ligand_filename')
ip.append(datatype='string', name='receptor_filename')
ip.append(datatype='string', required=False, name='dpf_filename', defaultValue='')
ip.append(datatype='dict', required=False, name='parameters', defaultValue={})
ip.append(datatype='string', required=False, name='outputfilename', defaultValue='')
op = self.outputPortsDescr
op.append(datatype='string', name='ad3_parameter_file')
code = """def doit(self, ligand_filename, receptor_filename, dpf_filename, parameters, outputfilename):
if ligand_filename and receptor_filename:
from AutoDockTools.DockingParameters import DockingParameterFileMaker
dpfm = DockingParameterFileMaker()
dpfm.set_ligand(ligand_filename)
dpfm.set_receptor(receptor_filename)
if dpf_filename:
dpfm.read_reference(dpf_filename)
if len(parameters):
dpfm.set_docking_parameters(parameters)
if not outputfilename:
outputfilename = dpfm.ligand.name+'_'+dpfm.receptor_stem + ".dpf"
dpfm.write_dpf(outputfilename)
self.outputData(ad3_parameter_file=outputfilename)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
class AdtPrepareDpf4(NetworkNode):
""" writes parameter file for autodock4
Process entails:
1. setting ligand
2. setting receptor
3. setting specified values of various parameters
4. writing dpf file for autodock4
Input: ligand_filename, receptor_filename, optional parameter dictionary
Output: dpf ('string')"""
def __init__(self, name='Prepare Autodock4 Dpf', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='string', name='ligand_filename')
ip.append(datatype='string', name='receptor_filename')
ip.append(datatype='string', required=False, name='dpf_filename', defaultValue='')
ip.append(datatype='dict', required=False, name='parameters', defaultValue={})
ip.append(datatype='string', required=False, name='outputfilename', defaultValue='')
op = self.outputPortsDescr
op.append(datatype='string', name='ad4_parameter_file')
code = """def doit(self, ligand_filename, receptor_filename, dpf_filename, parameters, outputfilename):
if ligand_filename and receptor_filename:
from AutoDockTools.DockingParameters import DockingParameter4FileMaker
dpfm = DockingParameter4FileMaker()
dpfm.set_ligand4(ligand_filename)
dpfm.set_receptor4(receptor_filename)
if dpf_filename:
dpfm.read_reference4(dpf_filename)
if len(parameters):
dpfm.set_docking_parameters(parameters)
if not outputfilename:
outputfilename = dpfm.ligand.name+'_'+dpfm.receptor_stem + ".dpf"
dpfm.write_dpf(outputfilename)
self.outputData(ad4_parameter_file=outputfilename)\n"""
self.setFunction(code)
def myCallback(self, event=None):
#self.paramPanel.run()
pass
#class AdtPrepareFlexDocking4
#class AdtPdbqToPdbqt
#class AdtPdbqsToPdbqt
#class AdtGpf3ToGpf4
#class AdtDpf3ToDpf4
#class AdtRunAutogrid3
#class AdtRunAutogrid4
#class AdtRunAutodock3
#class AdtRunAutodock4
#class AdtSummarizeResults
#class AdtSummarizeResults4
#class AdtSummarizeXMLResults4
#class AdtPixelMapResults
#objects:
#MolecularPreparation classes
# AutoDockBondClassifier
# ReceptorWriter<==MolKitNodes/WriteMolecule
# AD4ReceptorWriter<==MolKitNodes/WriteMolecule
#AD4FlexibleDockingPreparation
#prepare_ligand_dict
#ReceptorWriter
#AD4ReceptorWriter
#LigandPreparation
#AD4LigandPreparation
#AutoDock3_AtomTyper
#DockingParameters
#DockingParameterFileMaker
#GridParameters
#GridParameterFileMaker
#??Docking??
from Vision.VPE import NodeLibrary
adtlib = NodeLibrary('adtlib', '#4444FF')
#macros from other files in this directory
#from AutoDockTools.VisionInterface.PrepareAD4Molecule import PrepareAD4Molecule
#adtlib.addNode(PrepareAD4Molecule, 'Prepare AD4Molecule', 'Macro')
#from AutoDockTools.VisionInterface.AD4Ligands import AD4Ligands
#adtlib.addNode(AD4Ligands, 'Prepare AD4 Ligands', 'Macro')
#from AutoDockTools.VisionInterface.Prepare_AD4_Ligands import Prepare_AD4_Ligands
#adtlib.addNode(Prepare_AD4_Ligands, 'Prepare AD4 Ligands', 'Macro')
###from AutoDockTools.VisionInterface.PrepareAD3Ligand import PrepareAD3Ligand
###adtlib.addNode(PrepareAD3Ligand, 'Prepare AD3 Ligand', 'Macro')
###from AutoDockTools.VisionInterface.PrepareAD3Receptor import PrepareAD3Receptor
###adtlib.addNode(PrepareAD3Receptor, 'Prepare AD3Receptor', 'Macro')
###from AutoDockTools.VisionInterface.AD3Gpf import AD3Gpf
###adtlib.addNode(AD3Gpf, 'Prepare AD3 Gpf ', 'Macro')
###from AutoDockTools.VisionInterface.AD3Dpf import AD3Dpf
###adtlib.addNode(AD3Dpf, 'Prepare AD3 Dpf ', 'Macro')
#from AutoDockTools.VisionInterface.GPF4 import GPF4
#adtlib.addNode(GPF4, 'Prepare AD4 Gpf ', 'Macro')
from AutoDockTools.VisionInterface.Docking import Docking
adtlib.addNode(Docking, 'Docking', 'Macro')
from AutoDockTools.VisionInterface.recluster import recluster
adtlib.addNode(recluster, 'recluster...', 'Macro')
adtlib.addNode(GridParameterFileBrowserNE, 'Grid Parameter File Browser', 'Input')
adtlib.addNode(DockingParameterFileBrowserNE, 'Docking Parameter File Browser', 'Input')
#adtlib.addNode(ReadGridParameterFile, 'Read Grid Parameter File', 'Input')
#adtlib.addNode(ReadDockingParameterFile, 'Read Docking Parameter File', 'Input')
#adtlib.addNode(AdtPrepareGpf3, 'Prepare AD3Gpf', 'Macro')
#adtlib.addNode(AdtPrepareGpf4, 'Prepare AD4Gpf', 'Macro')
#adtlib.addNode(AdtPrepareDpf3, 'Prepare AD3Dpf', 'Macro')
#adtlib.addNode(AdtPrepareDpf4, 'Prepare AD4Dpf', 'Macro')
adtlib.addNode(Assign_AD4Types, 'AD4_typer', 'Mapper')
adtlib.addNode(Add_SolvationParameters, 'Add Solvation Parameters', 'Mapper')
adtlib.addNode(ManageRotatableBonds, 'Manage Rotatable Bonds', 'Mapper')
adtlib.addNode(MergeNonPolarHydrogens, 'Merge NonPolar Hydrogens', 'Mapper')
adtlib.addNode(MergeLonePairs, 'Merge Lone Pairs', 'Mapper')
adtlib.addNode(RemoveWaters, 'Remove Water Residues', 'Mapper')
adtlib.addNode(ManageAromaticCarbons, 'Manage Aromatic Carbons', 'Mapper')
adtlib.addNode(Ligand_Writer, 'Ligand Writer', 'Output')
adtlib.addNode(Ligand_Writer_AD4, 'AD4 Ligand Writer', 'Output')
try:
UserLibBuild.addTypes(adtlib, 'MolKit.VisionInterface.MolKitTypes')
except Exception, e:
print "loading types failed:", e
```
#### File: AutoDockTools/VisionInterface/PrepareAD3Ligand.py
```python
from NetworkEditor.macros import MacroNode
class PrepareAD3Ligand(MacroNode):
def __init__(self, constrkw={}, name='Prepare AD3 Ligand', **kw):
kw['name'] = name
apply( MacroNode.__init__, (self,), kw)
def beforeAddingToNetwork(self, net):
MacroNode.beforeAddingToNetwork(self, net)
## loading libraries ##
from AutoDockTools.VisionInterface.AdtNodes import adtlib
net.editor.addLibraryInstance(adtlib,"AutoDockTools.VisionInterface.AdtNodes", "adtlib")
from MolKit.VisionInterface.MolKitNodes import molkitlib
net.editor.addLibraryInstance(molkitlib,"MolKit.VisionInterface.MolKitNodes", "molkitlib")
def afterAddingToNetwork(self):
from NetworkEditor.macros import MacroNode
MacroNode.afterAddingToNetwork(self)
## loading libraries ##
from AutoDockTools.VisionInterface.AdtNodes import adtlib
from MolKit.VisionInterface.MolKitNodes import molkitlib
## building macro network ##
Prepare_AD3_Ligand_0 = self
from traceback import print_exc
## loading libraries ##
from AutoDockTools.VisionInterface.AdtNodes import adtlib
self.macroNetwork.getEditor().addLibraryInstance(adtlib,"AutoDockTools.VisionInterface.AdtNodes", "adtlib")
from MolKit.VisionInterface.MolKitNodes import molkitlib
self.macroNetwork.getEditor().addLibraryInstance(molkitlib,"MolKit.VisionInterface.MolKitNodes", "molkitlib")
try:
## saving node input Ports ##
input_Ports_1 = self.macroNetwork.ipNode
input_Ports_1.move(183, 27)
except:
print "WARNING: failed to restore MacroInputNode named input Ports in network self.macroNetwork"
print_exc()
input_Ports_1=None
try:
## saving node output Ports ##
output_Ports_2 = self.macroNetwork.opNode
output_Ports_2.move(181, 338)
except:
print "WARNING: failed to restore MacroOutputNode named output Ports in network self.macroNetwork"
print_exc()
output_Ports_2=None
try:
## saving node Calculate Gasteiger Charges ##
from MolKit.VisionInterface.MolKitNodes import CalculateGasteigerCharges
Calculate_Gasteiger_Charges_3 = CalculateGasteigerCharges(constrkw = {}, name='Calculate Gasteiger Charges', library=molkitlib)
self.macroNetwork.addNode(Calculate_Gasteiger_Charges_3,200,131)
apply(Calculate_Gasteiger_Charges_3.inputPortByName['mols'].configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Calculate_Gasteiger_Charges_3.outputPortByName['mols'].configure, (), {'color': '#c64e70', 'shape': 'oval'})
apply(Calculate_Gasteiger_Charges_3.outputPortByName['charge_total'].configure, (), {'color': 'green', 'shape': 'circle'})
except:
print "WARNING: failed to restore CalculateGasteigerCharges named Calculate Gasteiger Charges in network self.macroNetwork"
print_exc()
Calculate_Gasteiger_Charges_3=None
try:
## saving node Add Hydrogens ##
from MolKit.VisionInterface.MolKitNodes import AddHydrogens
Add_Hydrogens_4 = AddHydrogens(constrkw = {}, name='Add Hydrogens', library=molkitlib)
self.macroNetwork.addNode(Add_Hydrogens_4,200,80)
apply(Add_Hydrogens_4.inputPortByName['molecules'].configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Add_Hydrogens_4.outputPortByName['molecules'].configure, (), {'color': '#c64e70', 'shape': 'oval'})
apply(Add_Hydrogens_4.outputPortByName['new_h_ct'].configure, (), {'color': 'yellow', 'shape': 'circle'})
except:
print "WARNING: failed to restore AddHydrogens named Add Hydrogens in network self.macroNetwork"
print_exc()
Add_Hydrogens_4=None
try:
## saving node Merge NonPolar Hydrogens ##
from AutoDockTools.VisionInterface.AdtNodes import MergeNonPolarHydrogens
Merge_NonPolar_Hydrogens_5 = MergeNonPolarHydrogens(constrkw = {}, name='Merge NonPolar Hydrogens', library=adtlib)
self.macroNetwork.addNode(Merge_NonPolar_Hydrogens_5,200,182)
apply(Merge_NonPolar_Hydrogens_5.inputPortByName['mols'].configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Merge_NonPolar_Hydrogens_5.inputPortByName['renumber'].configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(Merge_NonPolar_Hydrogens_5.outputPortByName['mols'].configure, (), {'color': '#c64e70', 'shape': 'oval'})
apply(Merge_NonPolar_Hydrogens_5.outputPortByName['num_nphs'].configure, (), {'color': 'yellow', 'shape': 'circle'})
except:
print "WARNING: failed to restore MergeNonPolarHydrogens named Merge NonPolar Hydrogens in network self.macroNetwork"
print_exc()
Merge_NonPolar_Hydrogens_5=None
try:
## saving node Manage Rotatable Bonds ##
from AutoDockTools.VisionInterface.AdtNodes import ManageRotatableBonds
Manage_Rotatable_Bonds_6 = ManageRotatableBonds(constrkw = {}, name='Manage Rotatable Bonds', library=adtlib)
self.macroNetwork.addNode(Manage_Rotatable_Bonds_6,200,235)
apply(Manage_Rotatable_Bonds_6.inputPortByName['mols'].configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Manage_Rotatable_Bonds_6.inputPortByName['root'].configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Manage_Rotatable_Bonds_6.inputPortByName['allowed_bonds'].configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Manage_Rotatable_Bonds_6.inputPortByName['check_for_fragments'].configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(Manage_Rotatable_Bonds_6.inputPortByName['bonds_to_inactivate'].configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Manage_Rotatable_Bonds_6.inputPortByName['limit_torsions'].configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Manage_Rotatable_Bonds_6.outputPortByName['mol'].configure, (), {'color': '#c64e70', 'shape': 'oval'})
except:
print "WARNING: failed to restore ManageRotatableBonds named Manage Rotatable Bonds in network self.macroNetwork"
print_exc()
Manage_Rotatable_Bonds_6=None
try:
## saving node AD4_typer ##
from AutoDockTools.VisionInterface.AdtNodes import Assign_AD4Types
AD4_typer_7 = Assign_AD4Types(constrkw = {}, name='AD4_typer', library=adtlib)
self.macroNetwork.addNode(AD4_typer_7,198,288)
apply(AD4_typer_7.inputPortByName['mols'].configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(AD4_typer_7.inputPortByName['renameAtoms'].configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(AD4_typer_7.inputPortByName['set_aromatic_carbons'].configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(AD4_typer_7.inputPortByName['reassign'].configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(AD4_typer_7.outputPortByName['typed_mols'].configure, (), {'color': '#c64e70', 'shape': 'oval'})
except:
print "WARNING: failed to restore Assign_AD4Types named AD4_typer in network self.macroNetwork"
print_exc()
AD4_typer_7=None
self.macroNetwork.freeze()
## saving connections for network Prepare AD3 Ligand ##
input_Ports_1 = self.macroNetwork.ipNode
if input_Ports_1 is not None and Add_Hydrogens_4 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, Add_Hydrogens_4, "new", "molecules", blocking=True)
except:
print "WARNING: failed to restore connection between input_Ports_1 and Add_Hydrogens_4 in network self.macroNetwork"
if Add_Hydrogens_4 is not None and Calculate_Gasteiger_Charges_3 is not None:
try:
self.macroNetwork.connectNodes(
Add_Hydrogens_4, Calculate_Gasteiger_Charges_3, "molecules", "mols", blocking=True)
except:
print "WARNING: failed to restore connection between Add_Hydrogens_4 and Calculate_Gasteiger_Charges_3 in network self.macroNetwork"
if Calculate_Gasteiger_Charges_3 is not None and Merge_NonPolar_Hydrogens_5 is not None:
try:
self.macroNetwork.connectNodes(
Calculate_Gasteiger_Charges_3, Merge_NonPolar_Hydrogens_5, "mols", "mols", blocking=True)
except:
print "WARNING: failed to restore connection between Calculate_Gasteiger_Charges_3 and Merge_NonPolar_Hydrogens_5 in network self.macroNetwork"
if Merge_NonPolar_Hydrogens_5 is not None and Manage_Rotatable_Bonds_6 is not None:
try:
self.macroNetwork.connectNodes(
Merge_NonPolar_Hydrogens_5, Manage_Rotatable_Bonds_6, "mols", "mols", blocking=True)
except:
print "WARNING: failed to restore connection between Merge_NonPolar_Hydrogens_5 and Manage_Rotatable_Bonds_6 in network self.macroNetwork"
if Manage_Rotatable_Bonds_6 is not None and AD4_typer_7 is not None:
try:
self.macroNetwork.connectNodes(
Manage_Rotatable_Bonds_6, AD4_typer_7, "mol", "mols", blocking=True)
except:
print "WARNING: failed to restore connection between Manage_Rotatable_Bonds_6 and AD4_typer_7 in network self.macroNetwork"
output_Ports_2 = self.macroNetwork.opNode
if AD4_typer_7 is not None and output_Ports_2 is not None:
try:
self.macroNetwork.connectNodes(
AD4_typer_7, output_Ports_2, "typed_mols", "new", blocking=True)
except:
print "WARNING: failed to restore connection between AD4_typer_7 and output_Ports_2 in network self.macroNetwork"
self.macroNetwork.unfreeze()
Prepare_AD3_Ligand_0.shrink()
## reset modifications ##
Prepare_AD3_Ligand_0.resetTags()
Prepare_AD3_Ligand_0.buildOriginalList()
```
#### File: MGLToolsPckgs/binaries/__init__.py
```python
path = __path__[0]
import os, sys, string
def findExecModule(modname):
"""return (platform-dependent) path to executable module"""
assert modname
mod = __import__('binaries')
#pth = mod.__path__[0]
pth = mod.path
if sys.platform == 'win32':
modname = modname + '.exe'
pth = os.path.join( pth, modname)
if os.path.exists(pth):
return pth
else:
print 'ERROR! Module %s not found in %s'%(modname, path)
return None
__MGLTOOLSVersion__ = '1-4alpha3'
CRITICAL_DEPENDENCIES = ['mglutil']
NONCRITICAL_DEPENDENCIES = ['DejaVu',]
```
#### File: MGLToolsPckgs/CADD/WFType.py
```python
import os
from CADD import __path__, WFTypes
class NodeWFType:
""" class used to describe a workflows type"""
def __init__(self, name, dir ):
self.name = None # worfklow Type name
self.dir = None # directory of individual workflows
self.wflist = {} # available workflows list. Key - short name, value - file full path
self.items = []
if name not in WFTypes.keys():
return None
self.name = name
self.dir = dir + os.sep + WFTypes[name]
if not os.path.isdir(self.dir):
self.about = "Missing %s/ directory.\nYour installation may be incomplete" % self.dir
return None
for item in os.listdir(self.dir):
if item.endswith('.py') and (item != '__about__.py'):
filenameNoExt = os.path.splitext(item)[0]
filenameNoExt = filenameNoExt.split('_')[0] # remove version and _net from the name
self.wflist[filenameNoExt] = self.dir + os.sep + item
self.items = self.wflist.items()
try:
f = file (self.dir + os.sep + '__about__.py', 'r')
exec f.read()
f.close()
self.about = about
except:
self.about = "Missing %s/__about__.py file.\nYour installation may be incomplete" % self.dir
def showWFlist(self):
if self.items :
self.items.sort()
return self.items
def showType(self):
return self.about
```
#### File: workflows/docking/PrepareReceptor_0.1_net.py
```python
if __name__=='__main__':
from sys import argv
if '--help' in argv or '-h' in argv or '-w' in argv: # run without Vision
withoutVision = True
from Vision.VPE import NoGuiExec
ed = NoGuiExec()
from NetworkEditor.net import Network
import os
masterNet = Network("process-"+str(os.getpid()))
ed.addNetwork(masterNet)
else: # run as a stand alone application while vision is hidden
withoutVision = False
from Vision import launchVisionToRunNetworkAsApplication, mainLoopVisionToRunNetworkAsApplication
if '-noSplash' in argv:
splash = False
else:
splash = True
masterNet = launchVisionToRunNetworkAsApplication(splash=splash)
import os
masterNet.filename = os.path.abspath(__file__)
from traceback import print_exc
## loading libraries ##
from AutoDockTools.VisionInterface.Adt import Adt
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
try:
masterNet
except (NameError, AttributeError): # we run the network outside Vision
from NetworkEditor.net import Network
masterNet = Network()
masterNet.getEditor().addLibraryInstance(Adt,"AutoDockTools.VisionInterface.Adt", "Adt")
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
from WebServices.VisionInterface.WSNodes import addOpalServerAsCategory
try:
addOpalServerAsCategory("http://ws.nbcr.net/opal2", replace=False)
except:
pass
try:
## saving node PrepareReceptor2 ##
from Adt.Macro.PrepareReceptor import PrepareReceptor
PrepareReceptor2_0 = PrepareReceptor(constrkw={}, name='PrepareReceptor2', library=Adt)
masterNet.addNode(PrepareReceptor2_0,301,206)
apply(PrepareReceptor2_0.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
Pdb2pqrWS_3 = PrepareReceptor2_0.macroNetwork.nodes[2]
Pdb2pqrOpalService_ws_nbcr_net_7 = Pdb2pqrWS_3.macroNetwork.nodes[3]
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['noopt'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['phi'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['psi'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['verbose'].widget.set(1, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['chain'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['nodebump'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['chi'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['ligand'].widget.set(r"", run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['hbond'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['with_ph'].widget.set(r"", run=False)
apply(Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['forcefield'].widget.configure, (), {'choices': ('AMBER', 'CHARMM', 'PARSE', 'TYL06')})
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['forcefield'].widget.set(r"AMBER", run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['clean'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['inId'].widget.set(r"", run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['apbs_input'].widget.set(0, run=False)
apply(Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['ffout'].widget.configure, (), {'choices': ('AMBER', 'CHARMM', 'PARSE', 'TYL06')})
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['ffout'].widget.set(r"", run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['localRun'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['rama'].widget.set(0, run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['execPath'].widget.set(r"", run=False)
Pdb2pqrOpalService_ws_nbcr_net_7.inputPortByName['assign_only'].widget.set(0, run=False)
GetURLFromList_8 = Pdb2pqrWS_3.macroNetwork.nodes[4]
GetURLFromList_8.inputPortByName['ext'].widget.set(r"pqr", run=False)
## saving connections for network Pdb2pqrWS ##
Pdb2pqrWS_3.macroNetwork.freeze()
Pdb2pqrWS_3.macroNetwork.unfreeze()
## modifying MacroInputNode dynamic ports
input_Ports_4 = Pdb2pqrWS_3.macroNetwork.ipNode
input_Ports_4.outputPorts[1].configure(name='CheckFileFormat_value')
## modifying MacroOutputNode dynamic ports
output_Ports_5 = Pdb2pqrWS_3.macroNetwork.opNode
output_Ports_5.inputPorts[1].configure(singleConnection='auto')
output_Ports_5.inputPorts[2].configure(singleConnection='auto')
output_Ports_5.inputPorts[1].configure(name='UpdateReceptor_receptor_obj')
output_Ports_5.inputPorts[2].configure(name='UpdateReceptor_pdb2pqr_result')
Pdb2pqrWS_3.inputPorts[0].configure(name='CheckFileFormat_value')
Pdb2pqrWS_3.inputPorts[0].configure(datatype='receptor')
## configure MacroNode input ports
Pdb2pqrWS_3.outputPorts[0].configure(name='UpdateReceptor_receptor_obj')
Pdb2pqrWS_3.outputPorts[0].configure(datatype='receptor')
Pdb2pqrWS_3.outputPorts[1].configure(name='UpdateReceptor_pdb2pqr_result')
Pdb2pqrWS_3.outputPorts[1].configure(datatype='string')
## configure MacroNode output ports
Pdb2pqrWS_3.shrink()
PrepareReceptorWS_10 = PrepareReceptor2_0.macroNetwork.nodes[3]
PrepareReceptorOpalService_ws_nbcr_net_14 = PrepareReceptorWS_10.macroNetwork.nodes[3]
PrepareReceptorOpalService_ws_nbcr_net_14.inputPortByName['o'].widget.set(r"", run=False)
PrepareReceptorOpalService_ws_nbcr_net_14.inputPortByName['v'].widget.set(0, run=False)
PrepareReceptorOpalService_ws_nbcr_net_14.inputPortByName['localRun'].widget.set(0, run=False)
PrepareReceptorOpalService_ws_nbcr_net_14.inputPortByName['execPath'].widget.set(r"", run=False)
GetURLFromList_15 = PrepareReceptorWS_10.macroNetwork.nodes[4]
GetURLFromList_15.inputPortByName['ext'].widget.set(r"pdbqt", run=False)
DownloadToFile_16 = PrepareReceptorWS_10.macroNetwork.nodes[5]
DownloadToFile_16.inputPortByName['overwrite'].widget.set(1, run=False)
## saving connections for network PrepareReceptorWS ##
PrepareReceptorWS_10.macroNetwork.freeze()
PrepareReceptorWS_10.macroNetwork.unfreeze()
## modifying MacroInputNode dynamic ports
input_Ports_11 = PrepareReceptorWS_10.macroNetwork.ipNode
input_Ports_11.outputPorts[1].configure(name='CheckFileFormat_value')
input_Ports_11.outputPorts[2].configure(name='PrepareReceptorOpalService_ws_nbcr_net_C')
## modifying MacroOutputNode dynamic ports
output_Ports_12 = PrepareReceptorWS_10.macroNetwork.opNode
output_Ports_12.inputPorts[1].configure(singleConnection='auto')
output_Ports_12.inputPorts[2].configure(singleConnection='auto')
output_Ports_12.inputPorts[1].configure(name='UpdateReceptor_receptor_prepared_obj')
output_Ports_12.inputPorts[2].configure(name='UpdateReceptor_receptor_result')
PrepareReceptorWS_10.inputPorts[0].configure(name='CheckFileFormat_value')
PrepareReceptorWS_10.inputPorts[0].configure(datatype='receptor')
PrepareReceptorWS_10.inputPorts[1].configure(name='PrepareReceptorOpalService_ws_nbcr_net_C')
PrepareReceptorWS_10.inputPorts[1].configure(datatype='boolean')
## configure MacroNode input ports
PrepareReceptorWS_10.outputPorts[0].configure(name='UpdateReceptor_receptor_prepared_obj')
PrepareReceptorWS_10.outputPorts[0].configure(datatype='receptor_prepared')
PrepareReceptorWS_10.outputPorts[1].configure(name='UpdateReceptor_receptor_result')
PrepareReceptorWS_10.outputPorts[1].configure(datatype='string')
## configure MacroNode output ports
PrepareReceptorWS_10.shrink()
## saving connections for network PrepareReceptor2 ##
PrepareReceptor2_0.macroNetwork.freeze()
PrepareReceptor2_0.macroNetwork.unfreeze()
## modifying MacroInputNode dynamic ports
input_Ports_1 = PrepareReceptor2_0.macroNetwork.ipNode
input_Ports_1.outputPorts[1].configure(name='Pdb2pqrWS_CheckFileFormat_value')
input_Ports_1.outputPorts[2].configure(name='PrepareReceptorWS_PrepareReceptorOpalService_ws_nbcr_net_C')
## modifying MacroOutputNode dynamic ports
output_Ports_2 = PrepareReceptor2_0.macroNetwork.opNode
output_Ports_2.inputPorts[1].configure(singleConnection='auto')
output_Ports_2.inputPorts[2].configure(singleConnection='auto')
output_Ports_2.inputPorts[1].configure(name='PrepareReceptorWS_UpdateReceptor_receptor_prepared_obj')
output_Ports_2.inputPorts[2].configure(name='PrepareReceptorWS_UpdateReceptor_receptor_result')
PrepareReceptor2_0.inputPorts[0].configure(name='Pdb2pqrWS_CheckFileFormat_value')
PrepareReceptor2_0.inputPorts[0].configure(datatype='receptor')
PrepareReceptor2_0.inputPorts[1].configure(name='PrepareReceptorWS_PrepareReceptorOpalService_ws_nbcr_net_C')
PrepareReceptor2_0.inputPorts[1].configure(datatype='boolean')
## configure MacroNode input ports
PrepareReceptor2_0.outputPorts[0].configure(name='PrepareReceptorWS_UpdateReceptor_receptor_prepared_obj')
PrepareReceptor2_0.outputPorts[0].configure(datatype='receptor_prepared')
PrepareReceptor2_0.outputPorts[1].configure(name='PrepareReceptorWS_UpdateReceptor_receptor_result')
PrepareReceptor2_0.outputPorts[1].configure(datatype='string')
## configure MacroNode output ports
PrepareReceptor2_0.shrink()
apply(PrepareReceptor2_0.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore PrepareReceptor named PrepareReceptor2 in network masterNet"
print_exc()
PrepareReceptor2_0=None
try:
## saving node StructureBrowser ##
from Adt.Input.StructureBrowser import StructureBrowser
StructureBrowser_18 = StructureBrowser(constrkw={}, name='StructureBrowser', library=Adt)
masterNet.addNode(StructureBrowser_18,52,43)
StructureBrowser_18.inputPortByName['receptor_file'].widget.set(r"PrepareReceptor_0.1_input/2HTY_A.pdb", run=False)
apply(StructureBrowser_18.configure, (), {'paramPanelImmediate': 1})
except:
print "WARNING: failed to restore StructureBrowser named StructureBrowser in network masterNet"
print_exc()
StructureBrowser_18=None
try:
## saving node Preserve charges? ##
from Vision.StandardNodes import CheckButtonNE
Preserve_charges__19 = CheckButtonNE(constrkw={}, name='Preserve charges?', library=stdlib)
masterNet.addNode(Preserve_charges__19,458,43)
Preserve_charges__19.inputPortByName['button'].widget.set(0, run=False)
apply(Preserve_charges__19.configure, (), {'paramPanelImmediate': 1})
except:
print "WARNING: failed to restore CheckButtonNE named Preserve charges? in network masterNet"
print_exc()
Preserve_charges__19=None
try:
## saving node SaveReceptor ##
from Vision.StandardNodes import Generic
SaveReceptor_20 = Generic(constrkw={}, name='SaveReceptor', library=stdlib)
masterNet.addNode(SaveReceptor_20,424,278)
apply(SaveReceptor_20.addInputPort, (), {'singleConnection': True, 'name': 'r', 'cast': True, 'datatype': 'string', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white', 'originalDatatype': 'None'})
apply(SaveReceptor_20.addInputPort, (), {'singleConnection': True, 'name': 'outdir', 'cast': True, 'datatype': 'string', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white', 'originalDatatype': 'None'})
apply(SaveReceptor_20.addOutputPort, (), {'name': 'outdir', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
code = """def doit(self, r, outdir):
outfile = os.path.join(outdir, os.path.basename(r))
if (r.startswith("http://")):
import urllib
opener = urllib.FancyURLopener({})
in_file = opener.open(r)
f = open(filename, '''w''')
f.write(in_file.read())
f.close()
else:
import shutil
shutil.copy (r, outfile)
pass
## to ouput data on port outdir use
self.outputData(outdir=outfile)
"""
SaveReceptor_20.configure(function=code)
apply(SaveReceptor_20.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore Generic named SaveReceptor in network masterNet"
print_exc()
SaveReceptor_20=None
try:
## saving node Output Directory Browser ##
from Vision.StandardNodes import DirBrowserNE
Output_Directory_Browser_21 = DirBrowserNE(constrkw={}, name='Output Directory Browser', library=stdlib)
masterNet.addNode(Output_Directory_Browser_21,638,46)
Output_Directory_Browser_21.inputPortByName['directory'].widget.set(r"PrepareReceptor_0.1_output", run=False)
apply(Output_Directory_Browser_21.configure, (), {'paramPanelImmediate': 1})
except:
print "WARNING: failed to restore DirBrowserNE named Output Directory Browser in network masterNet"
print_exc()
Output_Directory_Browser_21=None
#masterNet.run()
masterNet.freeze()
## saving connections for network PrepareReceptor-0.1 ##
if StructureBrowser_18 is not None and PrepareReceptor2_0 is not None:
try:
masterNet.connectNodes(
StructureBrowser_18, PrepareReceptor2_0, "receptor_obj", "Pdb2pqrWS_CheckFileFormat_value", blocking=True
, splitratio=[0.51287662428234593, 0.74658029742646814])
except:
print "WARNING: failed to restore connection between StructureBrowser_18 and PrepareReceptor2_0 in network masterNet"
if Preserve_charges__19 is not None and PrepareReceptor2_0 is not None:
try:
masterNet.connectNodes(
Preserve_charges__19, PrepareReceptor2_0, "value_bool", "PrepareReceptorWS_PrepareReceptorOpalService_ws_nbcr_net_C", blocking=True
, splitratio=[0.44734707960554609, 0.37373648392115422])
except:
print "WARNING: failed to restore connection between Preserve_charges__19 and PrepareReceptor2_0 in network masterNet"
if PrepareReceptor2_0 is not None and SaveReceptor_20 is not None:
try:
masterNet.connectNodes(
PrepareReceptor2_0, SaveReceptor_20, "PrepareReceptorWS_UpdateReceptor_receptor_result", "r", blocking=True
, splitratio=[0.38815590219305951, 0.71363867512527479])
except:
print "WARNING: failed to restore connection between PrepareReceptor2_0 and SaveReceptor_20 in network masterNet"
if Output_Directory_Browser_21 is not None and SaveReceptor_20 is not None:
try:
masterNet.connectNodes(
Output_Directory_Browser_21, SaveReceptor_20, "AbsPath_directory", "outdir", blocking=True
, splitratio=[0.32372299779158487, 0.59979789316638676])
except:
print "WARNING: failed to restore connection between Output_Directory_Browser_21 and SaveReceptor_20 in network masterNet"
masterNet.runOnNewData.value = False
if __name__=='__main__':
from sys import argv
lNodePortValues = []
if (len(argv) > 1) and argv[1].startswith('-'):
lArgIndex = 2
else:
lArgIndex = 1
while lArgIndex < len(argv) and argv[lArgIndex][-3:]!='.py':
lNodePortValues.append(argv[lArgIndex])
lArgIndex += 1
masterNet.setNodePortValues(lNodePortValues)
if '--help' in argv or '-h' in argv: # show help
masterNet.helpForNetworkAsApplication()
elif '-w' in argv: # run without Vision and exit
# create communicator
from NetworkEditor.net import Communicator
masterNet.communicator = Communicator(masterNet)
print 'Communicator listening on port:', masterNet.communicator.port
import socket
f = open(argv[0]+'.sock', 'w')
f.write("%s %i"%(socket.gethostbyname(socket.gethostname()),
masterNet.communicator.port))
f.close()
masterNet.run()
else: # stand alone application while vision is hidden
if '-e' in argv: # run and exit
masterNet.run()
elif '-r' in argv or len(masterNet.userPanels) == 0: # no user panel => run
masterNet.run()
mainLoopVisionToRunNetworkAsApplication(masterNet.editor)
else: # user panel
mainLoopVisionToRunNetworkAsApplication(masterNet.editor)
```
#### File: MGLToolsPckgs/DejaVu/Camera.py
```python
import os, sys, warnings
import Image
import ImageFilter
import ImageChops
import tkMessageBox
from opengltk.OpenGL.GLU import gluPerspective, gluPickMatrix, gluUnProject, gluErrorString, gluLookAt
from opengltk.extent import _gllib
from opengltk.OpenGL.GL import *
from opengltk.extent.utillib import glCleanRotMat
from opengltk.OpenGL import GL
from mglutil.gui import widgetsOnBackWindowsCanGrabFocus
import DejaVu
from DejaVu import loadTogl
from DejaVu.Insert2d import Insert2d
from DejaVu.Spheres import Spheres
from DejaVu.Ellipsoids import Ellipsoids
from DejaVu.Cylinders import Cylinders
from DejaVu import bitPatterns
from DejaVu.cursors import cursorsDict
from DejaVu.Texture import Texture
if hasattr(DejaVu, 'enableVertexArray') is False:
DejaVu.enableVertexArray = False
if hasattr( DejaVu, 'allowedAntiAliasInMotion') is False:
DejaVu.allowedAntiAliasInMotion = 0
if hasattr( DejaVu, 'enableSelectionContour') is False:
DejaVu.enableSelectionContour = False
if hasattr( DejaVu, 'selectionContourSize') is False:
DejaVu.selectionContourSize = 0
if hasattr( DejaVu, 'selectionContourColor') is False:
DejaVu.selectionContourColor = (1., 0., 1., .7)
if hasattr( DejaVu, 'selectionPatternSize') is False:
DejaVu.selectionPatternSize = 6
if hasattr( DejaVu, 'enableSSAO') is False:
DejaVu.enableSSAO = True
sndDeriv = [ -0.125, -0.125, -0.125,
-0.125, 1.0, -0.125,
-0.125, -0.125, -0.125]
fstDeriveV1 = [-0.125, -0.25, -0.125,
0.0 , 0.0, 0.0,
0.125, 0.25, 0.125]
fstDeriveV2 = [ 0.125, 0.25, 0.125,
0.0 , 0.0, 0.0,
-0.125, -0.25, -0.125]
fstDeriveH1 = [-0.125, 0.0, 0.125,
-0.25 , 0.0, 0.25,
-0.125, 0.0, 0.125]
fstDeriveH2 = [ 0.125, 0.0, -0.125,
0.25 , 0.0, -0.25,
0.125, 0.0, -0.125]
from time import time
try:
from opengltk.extent.utillib import namedPoints
except ImportError:
def namedPoints(v):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
i = 0
for p in v:
glPushName(i)
glBegin(GL_POINTS)
glVertex3f(float(p[0]), float(p[1]), float(p[2]))
glEnd()
glPopName()
i = i + 1
import Tkinter, os
import numpy.oldnumeric as Numeric
import math
import types
import weakref
import viewerConst, ViewerGUI, jitter
from Geom import Geom
from Transformable import Transformable
import colorTool
import viewerFns
from Trackball import Trackball
from EventHandler import EventManager
from IndexedPolygons import IndexedPolygons
from viewerFns import checkKeywords
import array
matf = array.array('f', [0]*16)
try:
from opengltk.extent._glextlib import *
except:
print "no _glextlib"
# DejaVu.enableSSAO = False
class Fog:
keywords = [
'tagModified',
'enabled',
'start',
'end',
'density',
'mode',
'color'
]
def Reset(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.color = (0.0, 0.0, 0.0, 1.0)
self.enabled = False
self.start = 25
self.end = 40
self.mode = GL_LINEAR
self.density = 0.1
self._modified = False
def __init__(self, camera):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.Reset()
self.camera = weakref.ref(camera) # used to activate right context
# the alternative would be to have the Set of
# fog values be done trough Camera.Set
self.name = 'Fog'+camera.name
def getState(self):
"""return a dictionary describing this object's state
This dictionary can be passed to the Set method to restore the object's state
"""
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
state = {'enabled':self.enabled,
'start':self.start,
'end':self.end,
'density':self.density,
'color':self.color
}
mode='GL_LINEAR'
if self.mode==GL_EXP: mode='GL_EXP'
elif self.mode==GL_EXP2: mode='GL_EXP2'
state['mode'] = mode
return state
def __repr__(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
return '<Fog enabled=%d from %5.2f to %5.2f mode=%d density=%f \
color=%s>' % \
(self.enabled, self.start, self.end, self.mode, self.density,
repr(self.color) )
def Set(self, check=1, **kw):
"""Set various fog parameters"""
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if __debug__:
if check:
apply( checkKeywords, ("Fog",self.keywords), kw)
val = kw.get( 'tagModified', True )
assert val in [True, False]
self._modified = val
self.camera().tk.call(self.camera()._w, 'makecurrent')
val = kw.get( 'enabled')
if val is not None:
if val in [False, 0]:
glDisable(GL_FOG)
elif val in [True, 1]:
glFogi(GL_FOG_MODE, self.mode)
if self.mode == GL_LINEAR:
glFogf(GL_FOG_START, float(self.start) )
glFogf(GL_FOG_END, float(self.end) )
else:
glFogf(GL_FOG_DENSITY, float(self.density))
glFogfv(GL_FOG_COLOR, self.color)
glEnable(GL_FOG)
else:
raise ValueError('Bad argument, Only True ot False are possible %s'%val)
self.enabled = val
val = kw.get( 'start')
if not val is None:
if kw.has_key('end'): end = kw.get('end')
else: end = self.end
if val < end:
glFogf(GL_FOG_START, float(val) )
self.start = val
else:
raise AttributeError('start has to be smaller than end=',
self.start, self.end)
val = kw.get( 'end')
if not val is None:
if val > self.start:
glFogf(GL_FOG_END, float(val) )
self.end = val
else:
raise AttributeError('end has to be larger than start=',
self.start, self.end)
val = kw.get( 'density')
if not val is None:
if val <= 1.0 and val >= 0.0:
glFogf(GL_FOG_DENSITY, float(val))
self.density = val
else:
raise AttributeError('density has to be <=1.0 and >= 0.0')
val = kw.get( 'mode')
if not val is None:
if val=='GL_LINEAR': val=GL_LINEAR
elif val=='GL_EXP': val=GL_EXP
elif val=='GL_EXP2': val=GL_EXP2
if val in (GL_LINEAR, GL_EXP, GL_EXP2):
glFogi(GL_FOG_MODE, int(val))
self.mode = val
else:
raise AttributeError('mode has to be GL_LINEAR,GL_EXP or\
GL_EXP2')
val = kw.get( 'color')
if not val is None:
self.color = colorTool.OneColor( val )
glFogfv(GL_FOG_COLOR, self.color)
class PickObject:
"""Class to represent the result of picking or drag selection
the keys of hits dictionary are geometries,
the values are lists of 2-tuples (vertexIndexe, instance), where vertexInd
is the index of the a vertex of a face of the geometry and instance is a list
of integer providing the instance matrix index for the geometry and all its
parents.
"""
def __init__(self, mode, camera, type='vertices'):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
assert mode in ['pick', 'drag select']
assert type in ['vertices', 'parts']
self.type = type
self.mode = mode
self.hits = {}
self.camera = weakref.ref(camera)
self.p1 = None # intersection of pick ray with front clip plane
self.p2 = None # intersection of pick ray with back clip plane
self.event = None # event that triggered picking
self.box = (0,0,0,0) # screen coordinates of selection box
def add(self, object=None, vertex=None, instance=0):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if self.hits.has_key(object):
self.hits[object].append( (vertex, instance) )
else:
self.hits[object] = [ (vertex, instance) ]
from math import sqrt, fabs
import Pmw
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
import numpy
from IndexedPolygons import IndexedPolygons
from Spheres import Spheres
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
# sub class combobox to intercept _postList and populate list when the pull
# down is posted
class DynamicComboBox(Pmw.ComboBox):
def __init__(self, viewer, parent = None, **kw):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.viewer = viewer
Pmw.ComboBox.__init__(self, parent, **kw)
def _postList(self, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
geomNames = []
for g in self.viewer.rootObject.AllObjects():
if isinstance(g, IndexedPolygons):
geomNames.append(g.fullName)
self.component('scrolledlist').setlist(geomNames)
Pmw.ComboBox._postList(self, event)
## class OcclusionCamera(Tkinter.Widget, Tkinter.Misc):
## def orient(self, eyex, eyey, eyez, nx, ny, nz):
## """Place camera at x,y,z and look along vector nx, ny, nz"""
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## glPushMatrix()
## glLoadIdentity()
## # compute normal vector
## if nx==0.0 and ny==0.0:
## x2=1.
## y2=0.
## z2=0.
## else:
## z2 = nz
## if ny==0.0 and nz==0.0:
## x2 = 0.0
## y2 = 1.0
## elif nx==0 and nz==0:
## x2 = 1.0
## y2 = 0.0
## else:
## if fabs(nx)>fabs(ny):
## x2 = 0.0
## y2 = ny
## else:
## x2 = nx
## y2 = 0.0
## upx = ny*z2 - nz*y2
## upy = nz*x2 - nx*z2
## upz = nx*y2 - ny*x2
## n = 1. / sqrt(upx*upx + upy*upy + upz*upz)
## upx *=n
## upy *=n
## upz *=n
## gluLookAt( eyex, eyey, eyez, eyex+nx, eyey+ny, eyez+nz, upx, upy, upz)
## m = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
## glPopMatrix()
## # compute gluLookAt( x, y, z, x+nx, y+ny, z+nz, x3, y3, z3) matrix
## # http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/glu/lookat.html
## ## # nx, ny, nz is the vector F (eye->center) (normalized)
## ## # x, y, z is the eye position
## ## # s = f x up
## ## sx = ny*upz - nz*upy
## ## sy = nz*upx - nx*upz
## ## sz = nx*upy - ny*upx
## ## # u = s x f
## ## ux = sy*nz - sz*ny
## ## uy = sz*nx - sx*nz
## ## uz = sx*ny - sy*nx
## ## M = ( sx, ux, -nx, 0, sy, uy, -ny, 0, sz, uz, -nz, 0, -eyex, -eyey, -eyez, 1.)
## ## diff = Numeric.sum(m-M)
## ## if diff > 0.1:
## ## raise ValueError
## self.matrix = m
## self.Redraw()
## def computeOcclusion(self, positions, directions):
## """For a list of pocitions and directions, render the geometry and
## compute occlusion by summing Zbuffer. Direction have to be normalized"""
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## from time import time
## t1 = time()
## occlusionValues = []
## self.tk.call(self._w, 'makecurrent')
## OnePercent = len(positions)/100
## percent = 0
## counter = 0
## for pos, dir in zip(positions,directions):
## if OnePercent>0 and counter % OnePercent == 0:
## self.counterText.configure(text=str(percent)+'%')
## self.update_idletasks()
## percent += 1
## counter += 1
## x, y, z = pos
## nx, ny, nz = dir
## self.orient(float(x), float(y), float(z),
## float(nx), float(ny), float(nz) )
## zbuf = self.GrabZBufferAsArray()
## sum = Numeric.sum(zbuf)
## occlusionValues.append(sum)
## #print time()-t1
## return occlusionValues
## def computeOcclusion_cb(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.removeOcclusion()
## occluderGeoms = self.occluders.getAll(index=2)
## computeOccluGeoms = self.compOcclusion.getAll(index=2)
## #print occluderGeoms
## #print '-------------'
## #print computeOccluGeoms
## if len(occluderGeoms)==0:
## print "WARNING: no occluders"
## return
## # allocate new dispaly lists
## # build display lists for all geoms
## self.tk.call(self._w, 'makecurrent')
## for i,g in enumerate(occluderGeoms):
## if hasattr(g, 'Draw'):
## g.oldinheritmaterial = g.inheritMaterial
## g.inheritMaterial = True
## if isinstance(g, Spheres):
## g.oldquality = g.quality
## self.tk.call(self.viewer.currentCamera._w, 'makecurrent')
## g.deleteTemplate()
## #self.tk.call(self._w, 'makecurrent')
## g.Set(quality=1)
## self.tk.call(self._w, 'makecurrent')
## g.makeTemplate()
## l = glGenLists(1)
## GL.glNewList(l, GL.GL_COMPILE)
## status = g.Draw()
## #print 'status', status
## GL.glEndList()
## self.dpyList.append(l)
## # compute occlusion for each geom
## #self.tk.call(self._w, 'makecurrent')
## for g in computeOccluGeoms:
## if isinstance(g, Spheres):
## self.near = 3.0
## self.setFovy(135.0)
## v = g.getVertices()
## from math import sqrt
## n = sqrt(3,)
## occRight = self.computeOcclusion(v, ( (-n,-n,n), )*len(v) )
## occLeft = self.computeOcclusion(v, ( (n,n,n), )*len(v) )
## occTop = self.computeOcclusion(v, ( (-n,n,-n), )*len(v) )
## occBottom = self.computeOcclusion(v, ( (n,-n,-n), )*len(v) )
## #occRight = self.computeOcclusion(v, ( (1.,0.,0.), )*len(v) )
## #occLeft = self.computeOcclusion(v, ( (-1.,0.,0.), )*len(v) )
## #occTop = self.computeOcclusion(v, ( (0.,1.,0.), )*len(v) )
## #occBottom = self.computeOcclusion(v, ( (0.,-1.,0.), )*len(v) )
## #occFront = self.computeOcclusion(v, ( (0.,0.,1.), )*len(v) )
## #occBack = self.computeOcclusion(v, ( (0.,0.,-1.), )*len(v) )
## occlusionValues = []
## for i in xrange(len(v)):
## occlusionValues.append( occRight[i] + occLeft[i] +
## occTop[i] + occBottom[i])# +
## #occFront[i] + occBack[i])
## g.occlusionValues = occlusionValues
## #g.occlusionValues = occRight
## else:
## self.near = self.near
## self.setFovy(self.fovyTW.get())
## v, n = g.getOcclusionPointsDir()
## #print 'computing for:', g, len(v)
## g.occlusionValues = self.computeOcclusion(v, n)
## # delete display lists
## for l in self.dpyList:
## glDeleteLists(l, 1)
## self.dpyList = []
## # restore Sphere templates and display list
## self.tk.call(self.viewer.currentCamera._w, 'makecurrent')
## #for i,g in enumerate(set.union(set(occluderGeoms), set(computeOccluGeoms))):
## for i,g in enumerate(occluderGeoms):
## if hasattr(g, 'Draw'):
## g.inheritMaterial = g.oldinheritmaterial
## if isinstance(g, Spheres):
## self.tk.call(self._w, 'makecurrent')
## g.deleteTemplate()
## #GL.glDeleteLists(g.templateDSPL[0], 3)
## #g.templateDSPL = None
## #self.tk.call(self.viewer.currentCamera._w, 'makecurrent')
## g.Set(quality=g.oldquality)
## self.tk.call(self.viewer.currentCamera._w, 'makecurrent')
## g.makeTemplate()
## del g.oldquality
## self.applyOcclusion()
## def normalize(self, values):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## mini = min(values)
## delta = max(values)-mini
## off = self.off*delta
## delta = delta + off
## nvalues = []
## for v in values:
## nv = ((v-mini+off)/delta)
## #nv = ((v-mini)/delta)
## nvalues.append(nv)
## #print 'normalize off:', self.off, 'delta:',delta, min(nvalues), max(nvalues)
## return nvalues
## def applyOcclusion(self):#, *dummy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## #print "applyOcclusion"
## lGeoms = self.compOcclusion.getAll(index=2)
## if len(lGeoms) == 0:
## tkMessageBox.showwarning('ambient occlusion','add geometry to apply occlusion')
## elif hasattr(lGeoms[0], 'occlusionValues') is False:
## tkMessageBox.showwarning('ambient occlusion','compute occlusion first')
## for g in self.compOcclusion.getAll(index=2):
## # max value is 2500 becauseocculsion rendering is 50x50 pixels
## # set values below 2400 to 2400. If we do not do this
## # we sometiems get very small values that kill the range
## # for instance gpcr
## #print "g.occlusionValues", g.occlusionValues
## if isinstance(g, Spheres):
## values = numpy.clip(g.occlusionValues, 5000., 7500.0)
## else:
## values = numpy.clip(g.occlusionValues, 2400., 2500.0)
## if values is None: return
## ambiScale = self.ambiScale
## diffScale = self.diffScale
## #print 'ambiScale:', ambiScale
## #print 'diffScale:', diffScale
## #print "values", values
## nvalues = self.normalize(values)
## nvalues = numpy.array(nvalues)
## nvalues.shape = (-1, 1)
## #print 'nvalues:', g.name, min(nvalues), max(nvalues)
## # modulate ambient
## from DejaVu import preventIntelBug_WhiteTriangles
## if preventIntelBug_WhiteTriangles is False:
## prop = numpy.ones( (len(values), 4) )*nvalues
## p = prop*ambiScale
## p[:,3] = 1
## g.materials[1028].getFrom[0][1] = p
## # modulate specular
## prop = numpy.ones( (len(values), 4) )*nvalues
## p = prop*ambiScale
## p[:,3] = 1
## g.materials[1028].getFrom[0][1] = p
## # modulate diffuse
## prop = numpy.ones( (len(values), 4) )*nvalues
## origProp = g.materials[1028].prop[1].copy()
## p = prop*diffScale
## g.materials[1028].getFrom[1] = [1, p]
## else:
## # modulate diffuse
## prop = numpy.ones( (len(values), 4) )*nvalues
## origProp = g.materials[1028].prop[1].copy()
## g.materials[1028].getFrom[1] = [1, prop]
## g.Set(inheritMaterial=False)
## g.RedoDisplayList()
## g.viewer.Redraw()
## def removeOcclusion(self):#, *dummy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## # reset
## for g in self.compOcclusion.getAll(index=2):
## from DejaVu import preventIntelBug_WhiteTriangles
## if preventIntelBug_WhiteTriangles:
## g.materials[1028].getFrom[0] = None # same as Materials.py line 107
## g.materials[1028].getFrom[1] = None # same as Materials.py line 107
## else:
## g.materials[1028].getFrom[0][1] = 0.6 # same as Materials.py line 107
## # g.materials[1028].getFrom[1][1] = 0.6 # same as Materials.py line 107
## g.Set(inheritMaterial=False)
## g.RedoDisplayList()
## g.viewer.Redraw()
## def setOffAndApplyOcclusion(self, val):
## self.setOff(val)
## self.applyOcclusion()
## def __init__(self, master, viewer, cnf={}, **kw):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.fovy = 90.0
## self.near = 0.1
## self.far = 100.
## self.matrix = None
## self.dpyList = []
## self.ambiScale = 0.6 # same as Materials.py line 107
## self.diffScale = 0.6 # same as Materials.py line 107
## self.off = 0.4
## self.ownMaster = False # set tot tru is the master of self.Frame
## # has to be destroyed when Camera is deleted
## self.exposeEvent = False # set to true on expose events and reset in
## # Viewer.ReallyRedraw
## self.frameBorderWidth = 3
## self.frame = Tkinter.Frame(master, bd=self.frameBorderWidth)
## cfg = 0
## self.counterText = Tkinter.Label(self.frame, text='0%')
## self.fovyTW = ThumbWheel(
## self.frame, width=70, height=16, type=float, value=self.fovy,
## callback=self.setFovy_cb, continuous=False, oneTurn=180,
## wheelPad=2, min=1.0, max=179.99,
## labCfg = {'text':'cavity darkness:', 'side':'top'}
## )
## #self.fovyTW.grid(column=3, row=0)
## self.fovyTW.pack(side='left')
## self.compute = Tkinter.Button(self.frame, text='compute',
## command = self.computeOcclusion_cb)
## self.guiFrame = Tkinter.Frame(master, bd=self.frameBorderWidth)
## frame = self.guiFrame
## # build geometry chooser
## #objects = []
## #for g in viewer.rootObject.AllObjects():
## # if g.visible and len(g.getVertices())>0:
## # objects.append( (g.fullName, 'no comment available', g) )
## b = Tkinter.Button(frame, text='Update Geom list',
## command=self.listGeoms)
## b.grid(column=0, row=0)
## self.chooser = ListChooser(
## frame, mode='extended', title='Geometry list', #entries=objects,
## lbwcfg={'height':12}
## )
## self.chooser.grid(column=0, row=1, rowspan=5)
## b = Tkinter.Button(frame, text='Add', command=self.addGeoms)
## b.grid(column=1, row=1)
## b = Tkinter.Button(frame, text='Remove', command=self.removeGeoms)
## b.grid(column=1, row=2)
## self.compOcclusion = ListChooser(
## frame, lbwcfg={'height':5}, mode='extended', title='Compute Occlusion',
## )
## self.compOcclusion.grid(column=2, row=0, rowspan=3)
## b = Tkinter.Button(frame, text='Add', command=self.addOccluders)
## b.grid(column=1, row=4)
## b = Tkinter.Button(frame, text='Remove', command=self.removeOccluders)
## b.grid(column=1, row=5)
## self.occluders = ListChooser(
## frame, lbwcfg={'height':5}, mode='extended', title='Occluders',
## )
## self.occluders.grid(column=2, row=3, rowspan=3)
## # self.ambiScaleTW = ThumbWheel(
## # frame, width=70, height=16, type=float, value=self.ambiScale,
## # callback=self.setambiScale, continuous=True, oneTurn=1.,
## # wheelPad=2, min=0.0001, max=1.,
## # labCfg = {'text':'ambi. sca.:', 'side':'top'})
## # self.ambiScaleTW.grid(column=3, row=1)
## #
## # self.diffScaleTW = ThumbWheel(
## # frame, width=70, height=16, type=float, value=self.diffScale,
## # callback=self.setdiffScale, continuous=True, oneTurn=1.,
## # wheelPad=2, min=0.0001, max=1.,
## # labCfg = {'text':'diff. sca.:', 'side':'top'})
## # self.diffScaleTW.grid(column=3, row=2)
## self.offTW = ThumbWheel(
## frame, width=70, height=16, type=float, value=self.off,
## callback=self.setOffAndApplyOcclusion,
## continuous=False, oneTurn=1.,
## wheelPad=2, min=0.0001, max=1.,
## labCfg = {'text':'overall brightness:', 'side':'top'})
## self.offTW.grid(column=3, row=3)
## self.apply = Tkinter.Button(frame, text='apply occ.',
## command = self.applyOcclusion)
## self.apply.grid(column=3, row=4)
## self.remove = Tkinter.Button(frame, text='remove occ.',
## command = self.removeOcclusion)
## self.remove.grid(column=3, row=5)
## self.viewer = viewer
## from DejaVu.Viewer import AddObjectEvent, RemoveObjectEvent, ReparentObjectEvent
## viewer.registerListener(AddObjectEvent, self.geomAddedToViewer)
## viewer.registerListener(RemoveObjectEvent, self.geomRemovedFromViewer)
## viewer.registerListener(ReparentObjectEvent, self.geomReparented)
## if not kw.has_key('double'): kw['double'] = 1
## if not kw.has_key('depth'): kw['depth'] = 1
## #kw['rgba'] = False
## #kw['depthsize'] = 20
## if not kw.has_key('sharecontext') and len(viewer.cameras):
## # share context with the default camera.
## cam = viewer.cameras[0]
## kw['sharecontext'] = cam.uniqID
## self.width = 50
## if 'width' in cnf.keys():
## self.width = cnf['width']
## cfg = 1
## self.height = 50
## if 'height' in cnf.keys():
## self.height = cnf['height']
## cfg = 1
## self.rootx = 320
## if 'rootx' in cnf.keys():
## self.rootx = cnf['rootx']
## del cnf['rootx']
## cfg = 1
## self.rooty = 180
## if 'rooty' in cnf.keys():
## self.rooty = cnf['rooty']
## del cnf['rooty']
## cfg = 1
## if cfg: self.Geometry()
## if 'side' in cnf.keys():
## side = cnf['side']
## del cnf['side']
## else: side = 'top'
## self.frame.pack(side=side)
## self.compute.pack(side='left')
## self.counterText.pack(side='left')
## self.defFrameBack = self.frame.config()['background'][3]
## loadTogl(self.frame)
## from Tkinter import TclError
## try :
## Tkinter.Widget.__init__(self, self.frame, 'togl', cnf, kw)
## self.tk.call(self._w, 'makecurrent')
## glDepthFunc(GL_LESS)
## except TclError, e:
## kw.pop('sharecontext')
## # after this line self.master will be set to self frame
## Tkinter.Widget.__init__(self, self.frame, 'togl', cnf, kw)
## self.tk.call(self._w, 'makecurrent')
## glDepthFunc(GL_LESS)
## glEnable(GL_DEPTH_TEST)
## glDisable(GL_LIGHTING)
## glEnable(GL_CULL_FACE)
## # create a TK-event manager for this camera
## self.eventManager = EventManager(self)
## self.eventManager.AddCallback('<Map>', self.Map)
## self.eventManager.AddCallback('<Expose>', self.Expose)
## self.eventManager.AddCallback('<Configure>', self.Expose)
## self.pack(side=side)
## frame.pack()
## self.matrix = (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
## master.update_idletasks()
## self.tk.call(viewer.currentCamera._w, 'makecurrent')
## def listGeoms(self, event=None):
## self.chooser.clear()
## objects = []
## for g in self.viewer.rootObject.AllObjects():
## if g.visible and len(g.getVertices())>0:
## objects.append( (g.fullName, 'no comment available', g) )
## self.chooser.setlist(objects)
## def geomAddedToViewer(self, event):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## geom = event.object
## if not hasattr(geom, "getVertices"): return
## if geom.visible and len(geom.getVertices())>0:
## self.chooser.add( (geom.fullName, 'no comment available', geom) )
## def geomRemovedFromViewer(self, event):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## #print "geomRemovedFromViewer", event.object.name
## geom = event.object
## self.chooser.remove( geom.fullName )
## # MS not sure we need this function ... viewer.ReparentObject shoudl be used
## def geomReparented(self, event):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## geom = event.object
## oldparent = event.oldparent
## # the listchooser needs to be updated when a geometry gets reparented.
## # replace old geometry name in the listchooser with the new one:
## oldname = oldparent.fullName + "|" + geom.name
## allentries = map(lambda x: x[0],self.chooser.entries)
## if oldname in allentries:
## ind = allentries.index(oldname)
## oldentry = self.chooser.entries[ind]
## self.chooser.remove(ind)
## self.chooser.insert(ind, (geom.fullName, 'no comment available', geom))
## if len(oldentry)> 1:
## self.chooser.entries[ind] = (geom.fullName, 'no comment available', geom) + oldentry[1:]
## def setambiScale(self, val):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.ambiScale = val
## def setdiffScale(self, val):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.diffScale = val
## def setOff(self, val):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.off = val
## def addGeoms(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## for g in self.chooser.get(index=2):
## self.compOcclusion.add( (g.fullName, 'no comment available', g))
## self.occluders.add( (g.fullName, 'no comment available', g))
## self.chooser.remove( g.fullName )
## return
## def removeGeoms(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## for g in self.compOcclusion.get(index=2):
## if g.fullName not in self.chooser.lb.get(0, 'end'):
## self.chooser.add( (g.fullName, 'no comment available', g) )
## self.compOcclusion.remove( g.fullName )
## return
## def addOccluders(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## for g in self.chooser.get(index=2):
## self.occluders.add( (g.fullName, 'no comment available', g))
## self.chooser.remove( g.fullName )
## return
## def removeOccluders(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## for g in self.occluders.get(index=2):
## if g.fullName not in self.chooser.lb.get(0, 'end'):
## self.chooser.add( (g.fullName, 'no comment available', g) )
## self.occluders.remove( g.fullName )
## return
## def setFovy_cb(self, *dummy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## val = self.fovyTW.get()
## self.setFovy(val)
## def setFovy(self, fovy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## #print 'fovy:', fovy, self.near, self.far
## self.fovy = fovy
## self.tk.call(self._w, 'makecurrent')
## glMatrixMode(GL_PROJECTION);
## glLoadIdentity()
## gluPerspective(float(fovy),
## float(self.width)/float(self.height),
## float(self.near), float(self.far))
## glMatrixMode(GL_MODELVIEW)
## def GrabZBufferAsArray(self):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## """Grabs the detph buffer and returns it as a Numeric array"""
## from opengltk.extent import _gllib as gllib
## width = self.width
## height = self.height
## nar = Numeric.zeros(width*height, 'f')
## glFinish() #was glFlush()
## gllib.glReadPixels( 0, 0, width, height, GL.GL_DEPTH_COMPONENT,
## GL.GL_FLOAT, nar)
## glFinish()
## return nar
## def GrabZBuffer(self, zmin=None, zmax=None):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## """Grabs the detph buffer and returns it as PIL P image"""
## deptharray = self.GrabZBufferAsArray()
## # map z values to unsigned byte
## if zmin is None:
## zmin = min(deptharray)
## if zmax is None:
## zmax = max(deptharray)
## if (zmax!=zmin):
## zval1 = 255 * ((deptharray-zmin) / (zmax-zmin))
## else:
## zval1 = Numeric.ones(self.width*self.height, 'f')*zmax*255
## import Image
## depthImage = Image.fromstring('L', (self.width, self.height),
## zval1.astype('B').tostring())
## return depthImage
## def Map(self, *dummy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## """Cause the opengl widget to redraw itself."""
## self.tk.call(self._w, 'makecurrent')
## self.Redraw()
## def Expose(self, event=None):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## """set the camera's exposeEvent so that at the next redraw
## the camera width and height are updated
## """
## self.tk.call(self._w, 'makecurrent')
## self.Redraw()
## def setGeom(self, geom):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## self.tk.call(self._w, 'makecurrent')
## self.dpyList = GL.glGenLists(1)
## GL.glNewList(self.dpyList, GL.GL_COMPILE)
## if hasattr(geom, 'Draw'):
## status = geom.Draw()
## else:
## status = 0
## GL.glEndList()
## self.geom = geom
## def Redraw(self, *dummy):
## if __debug__:
## if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
## #if self.dpyList is None:
## # return
## if self.matrix is None:
## return
## if self.dpyList is None:
## return
## glClearColor(0, 0, 0, 1 )
## glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
## glViewport(0, 0, self.width, self.height)
## glPushMatrix()
## glLoadIdentity()
## glMultMatrixf(self.matrix)
## for l in self.dpyList:
## glCallList(l)
## glPopMatrix()
## if self.swap:
## self.tk.call(self._w, 'swapbuffers')
## ## if not self.viewer.isInitialized:
## ## self.after(100, self.Expose)
## ## else:
## ## # if viewer is in autoRedraw mode the next redraw will handle it
## ## if not self.exposeEvent and self.viewer.autoRedraw:
## ## self.viewer.Redraw()
## ## self.exposeEvent = True
## ## for o in self.viewer.rootObject.AllObjects():
## ## if o.needsRedoDpyListOnResize or o.scissor:
## ## self.viewer.objectsNeedingRedo[o] = None
## ##
class StandardCamera(Transformable, Tkinter.Widget, Tkinter.Misc):
"""Class for Opengl 3D drawing window"""
initKeywords = [
'height',
'width',
'rgba'
'redsize',
'greensize',
'bluesize',
'double',
'depth',
'depthsize',
'accum',
'accumredsize',
'accumgreensize',
'accumbluesize',
'accumalphasize',
'alpha',
'alphasize',
'stencil',
'stencilsize',
'auxbuffers',
'privatecmap',
'overlay',
'stereo',
'time',
'sharelist',
'sharecontext',
'ident',
'rootx',
'rooty',
'side',
'stereoflag',
'ssao',
'SSAO_OPTIONS'
]
setKeywords = [
'tagModified',
'height',
'width',
'fov',
'near',
'far',
'color',
'antialiased',
'contours',
'd1ramp',
'd1scale',
'd1off',
'd1cutL',
'd1cutH',
'd2scale',
'd2off',
'd2cutL',
'd2cutH',
'boundingbox',
'rotation',
'translation',
'scale',
'pivot',
'direction',
'lookAt',
'lookFrom',
'projectionType',
'rootx',
'rooty',
'stereoMode',
'sideBySideRotAngle',
'sideBySideTranslation',
'suspendRedraw',
'drawThumbnail',
'ssao',
'SSAO_OPTIONS'
]
PERSPECTIVE = 0
ORTHOGRAPHIC = 1
stereoModesList = ['MONO',
'SIDE_BY_SIDE_CROSS',
'SIDE_BY_SIDE_STRAIGHT',
'STEREO_BUFFERS',
'COLOR_SEPARATION_RED_BLUE',
'COLOR_SEPARATION_BLUE_RED',
'COLOR_SEPARATION_RED_GREEN',
'COLOR_SEPARATION_GREEN_RED',
'COLOR_SEPARATION_RED_GREENBLUE',
'COLOR_SEPARATION_GREENBLUE_RED',
'COLOR_SEPARATION_REDGREEN_BLUE',
'COLOR_SEPARATION_BLUE_REDGREEN'
]
def getState(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""return a dictionary describing this object's state
This dictionary can be passed to the Set method to restore the object's state
"""
states = {
'height':self.height,
'width':self.width,
'rootx':self.rootx,
'rooty':self.rooty,
'fov':self.fovy,
'near':self.near,
'far':self.far,
'color':self.backgroundColor,
'antialiased':self.antiAliased,
'boundingbox':self.drawBB,
'rotation':list(self.rotation),
'translation':list(self.translation),
'scale':list(self.scale),
'pivot':list(self.pivot),
'direction':list(self.direction),
'lookAt':list(self.lookAt),
'lookFrom':list(self.lookFrom),
'projectionType':self.projectionType,
'stereoMode':self.stereoMode,
'sideBySideRotAngle':self.sideBySideRotAngle,
'sideBySideTranslation':self.sideBySideTranslation,
'suspendRedraw':self.suspendRedraw,
'drawThumbnail':self.drawThumbnailFlag,
'contours': self.contours,
'd1ramp':list(self.d1ramp),
'd1scale': self.d1scale,
'd1off': self.d1off,
'd1cutL': self.d1cutL,
'd1cutH': self.d1cutH,
'd2scale': self.d2scale,
'd2off': self.d2off,
'd2cutL': self.d2cutL,
'd2cutH': self.d2cutH,
'ssao':self.ssao,
}
if self.ssao:
d = {}
# for k in self.SSAO_OPTIONS:
# d[k] = self.SSAO_OPTIONS[k][0]
states['SSAO_OPTIONS'] = self.SSAO_OPTIONS
return states
def lift(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""brings the window containing the camera in front of others"""
window = self.frame.master
if isinstance(window, Tkinter.Tk) or \
isinstance(window, Tkinter.Toplevel):
self.frame.master.lift()
else:
m = self.master
while m.master:
m = m.master
m.lift()
def AutoDepthCue(self, nearOffset=0.0, farOffset=0.0, object=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""
AutoDepthCue(nearOffset=0.0, farOffset=0.0)
set fog start and end automatically using the bounding box of the
specified object.
if delta is the depth of the bounding box,
start will be set to near+(nearOffset*delta)
end will be set to farn+(farOffset*delta)
"""
#print "StandardCamera.AutoDepthCue"
#print 'BEFORE', self.near, self.far, self.fog.start, self.fog.end, self.nearDefault, self.farDefault
if object is None:
object = self.viewer.rootObject
bb = object.ComputeBB()
lf = self.lookFrom
la = self.lookAt
v = lf-la
from math import sqrt
fl = frustrumlength = sqrt( v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
# compute unit vector in viewing direction
viewDir1 = v/fl
# project center of bb to view direction
# and measure length from lookfrom to projected point
bbCenter = (bb[1]+bb[0])*.5
u = bbCenter-lf
u1 = u/sqrt(numpy.sum(u*u))
cosAlpha = numpy.dot(viewDir1, u1)
v = u*cosAlpha
l = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) # length from lookFrom
# subtract from this distance
halfDiag = bbCenter-bb[1]
rad = sqrt(numpy.sum(halfDiag*halfDiag))
d = rad/sqrt(3)
v = (l-d*.5)*viewDir1
start = sqrt(numpy.sum(v*v))
v = (l+d)*viewDir1
end = sqrt(numpy.sum(v*v))
#print l, d, start, end
#far = -min(bb[0])+frustrumlength
#near= -max(bb[1])+frustrumlength
#delta = far-near
#start = near+delta*nearOffset
#end = far+delta*farOffset
if start < end:
self.fog.Set(start=start, end=end)
# update camera near and far
#self.Set(near=self.nearDefault, far=self.farDefault)
#self.Set(near=self.fog.start*.9, far=self.fog.end*1.1)
self.Set(far=self.fog.end*1.1)
self.viewer.GUI.NearFarFog.Set(self.near,
self.far,
self.fog.start,
self.fog.end)
#print 'AFTER', self.near, self.far, self.fog.start, self.fog.end, self.nearDefault, self.farDefault
def GrabFrontBufferAsArray(self, lock=True, buffer=GL.GL_FRONT):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Grabs the front buffer and returns it as Numeric array of
size camera.width*camera.height*3"""
from opengltk.extent import _gllib as gllib
width = self.width
height = self.height
nar = Numeric.zeros(3*width*height, Numeric.UnsignedInt8)
# get the redraw lock to prevent viewer from swapping buffers
if lock:
self.viewer.redrawLock.acquire()
self.tk.call(self._w, 'makecurrent')
glPixelStorei(GL.GL_PACK_ALIGNMENT, 1)
current_buffer = int(GL.glGetIntegerv(GL.GL_DRAW_BUFFER)[0])
# tell OpenGL we want to read pixels from front buffer
glReadBuffer(buffer)
glFinish() #was glFlush()
gllib.glReadPixels( 0, 0, width, height, GL.GL_RGB,
GL.GL_UNSIGNED_BYTE, nar)
glFinish()
# restore buffer from on which we operate
glReadBuffer(current_buffer)
if lock:
self.viewer.redrawLock.release()
return nar
def GrabFrontBuffer(self, lock=True, buffer=GL.GL_FRONT):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Grabs the detph buffer and returns it as PIL P image"""
nar = self.GrabFrontBufferAsArray(lock, buffer)
import Image
image = Image.fromstring('RGB', (self.width, self.height),
nar.tostring())
#if sys.platform!='win32':
image = image.transpose(Image.FLIP_TOP_BOTTOM)
return image
def GrabZBufferAsArray(self, lock=True):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Grabs the detph buffer and returns it as a Numeric array"""
from opengltk.extent import _gllib as gllib
width = self.width
height = self.height
nar = Numeric.zeros(width*height, 'f')
if lock:
# get the redraw lock to prevent viewer from swapping buffers
self.viewer.redrawLock.acquire()
glFinish() #was glFlush()
gllib.glReadPixels( 0, 0, width, height, GL.GL_DEPTH_COMPONENT,
GL.GL_FLOAT, nar)
glFinish()
if lock:
self.viewer.redrawLock.release()
return nar
def GrabZBuffer(self, lock=True, flipTopBottom=True, zmin=None, zmax=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Grabs the detph buffer and returns it as PIL P image"""
deptharray = self.GrabZBufferAsArray(lock)
# map z values to unsigned byte
if zmin is None:
zmin = min(deptharray)
if zmax is None:
zmax = max(deptharray)
if (zmax!=zmin):
zval1 = 255 * ((deptharray-zmin) / (zmax-zmin))
else:
zval1 = Numeric.ones(self.width*self.height, 'f')*zmax*255
import Image
depthImage = Image.fromstring('L', (self.width, self.height),
zval1.astype('B').tostring())
#if sys.platform!='win32':
if flipTopBottom is True:
depthImage = depthImage.transpose(Image.FLIP_TOP_BOTTOM)
return depthImage
def SaveImage(self, filename, transparentBackground=False):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""None <- cam.SaveImage(filename, transparentBackground=False)
The file format is defined by the filename extension.
Transparent background is only supported in 'png' format.
"""
im = self.GrabFrontBuffer()
if transparentBackground:
errmsg = 'WARNING: transparent background is only supported with the png file format'
name, ext = os.path.splitext(filename)
if ext.lower != '.png':
print errmsg
filename += '.png'
def BinaryImage(x):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if x==255:
return 0
else:
return 255
# grab z buffer
z = self.GrabZBuffer()
# turn 255 (i.e. bg into 0 opacity and everything else into 255)
alpha = Image.eval(z, BinaryImage)
im = Image.merge('RGBA', im.split()+(alpha,))
extension = os.path.splitext(filename)[1]
kw = {}
if not extension:
filename += '.png'
elif extension in ['.jpg', '.jpeg', '.JPG', '.JPEG']:
kw = {'quality':95}
im.save(filename, **kw)
def ResetTransformation(self, redo=1):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
Transformable.ResetTransformation(self, redo=redo)
# Point at which we are looking
self.lookAt = Numeric.array([0.0, 0.0, 0.0])
# Point at which the camera is
self.lookFrom = Numeric.array([0.0, 0.0, 30.0])
# Vector from lookFrom to lookAt
self.direction = self.lookAt - self.lookFrom
# Field of view in y direction
self.fovyNeutral = 40.
self.fovy = self.fovyNeutral
self.projectionType = self.PERSPECTIVE
self.left = 0.
self.right = 0.
self.top = 0.
self.bottom = 0.
# Position of clipping planes.
self.nearDefault = .1
self.near = self.nearDefault
self.near_real = self.near
self.farDefault = 50.
self.far = self.farDefault
self.SetupProjectionMatrix()
def ResetDepthcueing(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.fog.Set(start = 25, end = 40)
def BuildTransformation(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Creates the camera's transformation"""
fx, fy, fz = self.lookFrom
ax, ay, az = self.lookAt
#ux, uy, uz = self.up
gluLookAt( float(fx), float(fy), float(fz),
float(ax), float(ay), float(az),
float(0), float(1), float(0))
#lMatrix = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
#print 'Before', lMatrix
#lRotation, lTranslation, lScale = self.Decompose4x4(lMatrix, cleanup=False)
#print lRotation
#print lTranslation
#glLoadIdentity()
#glTranslatef(float(lTranslation[0]), float(lTranslation[1]), float(lTranslation[2]))
#glMultMatrixf(lRotation)
#lMatrix = Numeric.array(glGetDoublev(GL_PROJECTION_MATRIX)).astype('f')
#print 'After', lMatrix
#float(ux), float(uy), float(uz) )
## ## eye = self.lookFrom
## ## center = self.lookAt
## ## gluLookAt( eye[0], eye[1], eye[2], center[0], center[1], center[2],
## ## 0, 1, 0)
## ## return
## ## rot = Numeric.reshape(self.rotation, (4,4))
## ## dir = Numeric.dot(self.direction, rot[:3,:3])
## ## glTranslatef(dir[0], dir[1], dir[2])
## glTranslatef(float(self.direction[0]),float(self.direction[1]),float(self.direction[2]))
## glMultMatrixf(self.rotation)
## glTranslatef(float(-self.lookAt[0]),float(-self.lookAt[1]),float(-self.lookAt[2]))
## ## glTranslatef(self.pivot[0],self.pivot[1],self.pivot[2])
## ## glMultMatrixf(self.rotation)
## ## glTranslatef(-self.pivot[0],-self.pivot[1],-self.pivot[2])
def GetMatrix(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Returns the matrix that is used to transform the whole scene to the
proper camera view"""
glPushMatrix()
glLoadIdentity()
self.BuildTransformation()
m = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
glPopMatrix()
return Numeric.transpose(m)
def GetMatrixInverse(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Returns the inverse of the matrix used to transform the whole scene
to the proper camera view"""
m = self.GetMatrix()
m = Numeric.reshape(Numeric.transpose(m), (16,)).astype('f')
rot, transl, scale = self.Decompose4x4(m)
sc = Numeric.concatenate((Numeric.reshape(scale,(3,1)), [[1]]))
n = Numeric.reshape(rot, (4,4))/sc
tr = Numeric.dot(n, (transl[0], transl[1], transl[2],1) )
n[:3,3] = -tr[:3]
return n
## def ConcatLookAtRot(self, matrix):
## """Rotates the lookAt point around the lookFrom point."""
## matrix = Numeric.transpose(Numeric.reshape( matrix, (4,4) ))
## rot = Numeric.reshape( self.rotation, (4,4))
## m = Numeric.dot(rot, matrix)
## m = Numeric.dot(m, Numeric.transpose(rot))
## dir = Numeric.dot(self.direction, m[:3,:3])
## self.lookAt = self.lookFrom + dir
## self.ConcatRotation(Numeric.reshape(matrix, (16,)))
## self.pivot = self.lookFrom
## def ConcatLookAtRot(self, matrix):
## """Rotates the lookAt point around the lookFrom point."""
## self.SetPivot(self.lookFrom)
## #print "ConcatLookAtRot", self.pivot
## self.ConcatRotation(matrix)
## def ConcatLookFromRot(self, matrix):
## """Rotates the lookFrom point around the lookAt point."""
## self.SetPivot(self.lookAt)
## #print "ConcatLookFromRot", self.pivot
## self.ConcatRotation(matrix)
## # not implemented
## def ConcatLookAtTrans(self, trans):
## pass
def ConcatRotation(self, matrix):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Rotates the camera around the lookAt point"""
self._modified = True
x,y,z = self.lookFrom
import numpy
matrix = Numeric.reshape( matrix, (4,4) )
newFrom = numpy.dot((x,y,z,1), matrix )
self.Set(lookFrom=newFrom[:3])
## glPushMatrix()
## glLoadIdentity()
## matrix = Numeric.reshape( matrix, (4,4) )
## ## rot = Numeric.reshape( self.rotation, (4,4))
## ## m = Numeric.dot(rot, matrix)
## ## m = Numeric.dot(m, Numeric.transpose(rot))
## ## self.direction = Numeric.dot(self.direction, m[:3,:3])
## ## self.lookFrom = self.lookAt - self.direction
## matrix = Numeric.reshape( Numeric.transpose( matrix ), (16,) )
## glMultMatrixf(matrix)
## glMultMatrixf(self.rotation)
## self.rotation = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
## self.rotation = glCleanRotMat(self.rotation).astype('f')
## self.rotation.shape = (16,)
## glPopMatrix()
## #self.pivot = self.lookAt
self.viewer.deleteOpenglList() # needed to redraw the clippingplanes little frame
def ConcatTranslation(self, trans, redo=1):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Translate the camera from lookFrom to looAt"""
self._modified = True
newFrom = self.lookFrom+trans
newAt = self.lookAt+trans
self.Set(lookFrom = newFrom, lookAt=newAt)
# FIXME compute deltaZ and update near, far and fog
## trans = Numeric.array(trans)
## sign = Numeric.add.reduce(trans)
## if sign > 0.0:
## n = 1 + (math.sqrt(Numeric.add.reduce(trans*trans)) * 0.01 )
## newdir = self.direction*n
## diff = self.direction-newdir
## diff = math.sqrt(Numeric.add.reduce(diff*diff))
## else:
## n = 1 - (math.sqrt(Numeric.add.reduce(trans*trans)) * 0.01 )
## newdir = self.direction*n
## diff = self.direction-newdir
## diff = -math.sqrt(Numeric.add.reduce(diff*diff))
## self.direction = newdir
## # print self.lookFrom, self.near, self.far, self.fog.start, self.fog.end
## # update near and far
## near = self.near_real + diff
## far = self.far + diff
## if near < far:
## self.Set(near=near, far=far, redo=redo)
## # update fog start and end
## #self.fog.Set(start=self.fog.start, end=self.fog.end + diff)
## if self.fog.start < self.fog.end + diff:
## self.fog.Set(end=self.fog.end + diff)
## # update viewerGUI
## if self == self.viewer.currentCamera:
## self.viewer.GUI.NearFarFog.Set(self.near, self.far,
## self.fog.start, self.fog.end)
## self.lookFrom = self.lookAt - self.direction
#self.viewer.Redraw()
self.viewer.deleteOpenglList() # needed to redraw the clippingplanes little frame
def ConcatScale(self, scale, redo=1):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Open and close camera's FOV
"""
#print "Camera.ConcatScale", scale
self._modified = True
if scale > 1.0 or self.scale[0] > 0.001:
#fovy = abs(math.atan( math.tan(self.fovy*math.pi/180.) * scale ) * 180.0/math.pi)
fovy = self.fovy * scale
if fovy < 180.:
self.Set(fov=fovy, redo=redo)
def Geometry(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""
Resize the Tk widget holding the camera to:
self.widthxself.height+self.rootx+self.rooty
This only applies when the camera is in its own top level.
"""
# get a handle to the master of the frame containing the Togl widget
window = self.frame.master
# if window is a toplevel window
# replaced this test by test for geometry method
#if isinstance(, Tkinter.Tk) or \
# isinstance(self.frame.master, Tkinter.Toplevel):
if hasattr(window, 'geometry') and callable(window.geometry):
# we have to set the geoemtry of the window to be the requested
# size plus 2 times the border width of the frame containing the
# camera
off = 2*self.frameBorderWidth
geom = '%dx%d+%d+%d' % (self.width+off, self.height+off,
self.rootx, self.rooty)
window.geometry(geom)
def getGeometry(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""return the posx, posy, width, height of the window containing the camera"""
geom = self.winfo_geometry()
size, x, y = geom.split('+')
w, h = size.split('x')
return int(x), int(y), int(w), int(h)
def __repr__(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
return self.name
def __init__(self, master, screenName, viewer, num, check=1,
cnf={}, **kw):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#print "StandardCamera.__init__"
self.name = 'Camera'+str(num)
self.num = num
self.uniqID = self.name+viewer.uniqID
# used for unprojection un gluUnProject
self.unProj_model = None
self.unProj_proj = None
self.unProj_view = None
self.swap = True # set to false to prevent camera from swapping after
# redraw (used by tile renderer)
self.suspendRedraw = False # set to True to prevent camera to be redraw
# Use for ARViewer ( Added by AG 01/12/2006)
self.lastBackgroundColorInPhotoMode = (0.,0.,0.,1.)
if __debug__:
if check:
apply( checkKeywords, (self.name,self.initKeywords), kw)
self.initialized = 0
self.swap = True
Transformable.__init__(self, viewer)
# FIXME: quick hack. Flag set by SetCurrentXxxx. When set object's
# transformation and material are saved in log file
self.hasBeenCurrent = 0
self._modified = False
#self.posLog = []
# Once togl will allow to create widgets with same context
# but for now we ignore it ==> no more multiple cameras
# kw['samecontext'] = 1
#
# Togl Tk widget options as of Version 1.5
# -height [DEFAULT_WIDTH=400], -width [DEFAULT_HEIGHT=400],
# -rgba [true]
# -redsize [1], -greensize [1], -bluesize [1]
# -double [false]
# -depth [false]
# -depthsize [1]
# -accum [false]
# -accumredsize [1], -accumgreensize [1], -accumbluesize [1], -accumalphasize [1]
# -alpha [false], -alphasize [1]
# -stencil [false], -stencilsize [1]
# -auxbuffers [0]
# -privatecmap [false]
# -overlay [false]
# -stereo [false]
# -time [DEFAULT_TIME = "1"]
# -sharelist [NULL]
# -sharecontext [NULL]
# -ident [DEFAULT_IDENT = ""]
if not kw.has_key('double'): kw['double'] = 1
# if not kw.has_key('overlay'): kw['overlay'] = 1
if not kw.has_key('depth'): kw['depth'] = 1
if not kw.has_key('stencil'): kw['stencil'] = 1
if hasattr(viewer, 'accumBuffersError') and viewer.accumBuffersError:
# if we tried to create a context with accumulation buffers before
# and it failed we set accum to False
kw['accum'] = 0
else:
# if the user did not specify accumulation we turn them on by defaut
if not kw.has_key('accum'):
kw['accum'] = 1
if not kw.has_key('stereo'): kw['stereo'] = 'none'
if not kw.has_key('ident'):
kw['ident'] = self.uniqID
# kw['ident'] = 'camera%d' % num
if not kw.has_key('sharelist') and len(viewer.cameras):
# share list with the default camera.
cam = viewer.cameras[0]
kw['sharelist'] = cam.uniqID
if not kw.has_key('sharecontext') and len(viewer.cameras):
# share context with the default camera.
cam = viewer.cameras[0]
kw['sharecontext'] = cam.uniqID
if not hasattr(cam, 'shareCTXWith'): cam.shareCTXWith = []
cam.shareCTXWith.append(self)
## if master is None:
## from os import path
## from opengltk.OpenGL import Tk
## toglInstallDir = path.dirname(path.abspath(Tk.__file__))
## tclIncludePath = master.tk.globalgetvar('auto_path')
## master.tk.globalsetvar('auto_path', toglInstallDir + ' ' +
## tclIncludePath)
## master.tk.call('package', 'require', 'Togl')
self.frameBorderWidth = 3
self.frame = Tkinter.Frame(master, bd=self.frameBorderWidth)
#self.frame.master.protocol("WM_DELETE_WINDOW", self.hide)
cfg = 0
if 'width' in cnf.keys():
self.width = cnf['width']
cfg = 1
else:
cnf['width'] = self.width = 406
if 'height' in cnf.keys():
self.height = cnf['height']
cfg = 1
else:
cnf['height'] = self.height = 406
self.rootx = 320
if 'rootx' in cnf.keys():
self.rootx = cnf['rootx']
del cnf['rootx']
cfg = 1
self.rooty = 180
if 'rooty' in cnf.keys():
self.rooty = cnf['rooty']
del cnf['rooty']
cfg = 1
if cfg: self.Geometry()
if 'side' in cnf.keys():
side = cnf['side']
del cnf['side']
else: side = 'top'
self.frame.pack(fill=Tkinter.BOTH, expand=1, side=side)
self.defFrameBack = self.frame.config()['background'][3]
self.ResetTransformation(redo=0)
self.currentTransfMode = 'Object' # or 'Clip', 'Camera'
self.renderMode = GL_RENDER
self.pickNum = 0
self.objPick = []
self.drawBB = 0
self.drawMode = None # bit 1: for Opaque objects with no dpyList
# bit 2: for objects using dpy list
# bit 3: for Transp Object with dpyList
self.drawTransparentObjects = 0
self.hasTransparentObjects = 0
self.selectDragRect = 0
self.fillSelectionBox = 0
# variable used for stereographic display
self.sideBySideRotAngle = 3.
self.sideBySideTranslation = 0.
self.imageRendered = 'MONO' # can be LEFT_EYE or RIGHT_EYE
self.stereoMode = 'MONO' # or 'SIDE_BY_SIDE'
self.backgroundColor = (.0,.0,.0, 1.0)
self.selectionColor = (1.0, 1.0, 0.0, 1.0)
self.fillDelay = 200 # delay in miliseconds for filling selection box
toglVersion = loadTogl(self.frame)
#print "Togl Version:", toglVersion
if os.name == 'nt':
if kw['stereo'] == 'none':
kw['stereo'] = 0
else:
kw['stereo'] = 1
# after this line self.master will be set to self frame
from Tkinter import TclError
from opengltk.exception import GLerror
try:
Tkinter.Widget.__init__(self, self.frame, 'togl', cnf, kw)
try:
GL.glAccum(GL.GL_LOAD, 1.0)
viewer.accumBuffersError = False
except GLerror:
viewer.accumBuffersError = True
#viewer.accumBuffersError = False
except Tkinter.TclError, e:
print "Warning: disabling accumulation buffers", e
kw.pop('accum')
viewer.accumBuffersError = True
Tkinter.Widget.__init__(self, self.frame, 'togl', cnf, kw)
#currentcontext = self.tk.call(self._w, 'contexttag')
#print "StandardCamera.__init__ currentcontext", currentcontext
if (DejaVu.preventIntelBug_BlackTriangles is None) \
or (DejaVu.preventIntelBug_WhiteTriangles is None):
isIntelOpenGL = GL.glGetString(GL.GL_VENDOR).find('Intel') >= 0
if isIntelOpenGL is True:
isIntelGmaRenderer = GL.glGetString(GL.GL_RENDERER).find("GMA") >= 0
lPreventIntelBugs = isIntelOpenGL and not isIntelGmaRenderer
else:
lPreventIntelBugs = False
if DejaVu.preventIntelBug_BlackTriangles is None:
DejaVu.preventIntelBug_BlackTriangles = lPreventIntelBugs
if DejaVu.preventIntelBug_WhiteTriangles is None:
DejaVu.preventIntelBug_WhiteTriangles = lPreventIntelBugs
if DejaVu.defaultAntiAlias is None:
if os.name == 'nt':
DejaVu.defaultAntiAlias = 0
else:
try:
from opengltk.extent import _glextlib # tells us the graphic card is not too bad
DejaVu.defaultAntiAlias = 4
except:
DejaVu.defaultAntiAlias = 0
self.antiAliased = DejaVu.defaultAntiAlias
self._wasAntiAliased = 0
self.drawThumbnailFlag = False
if self.antiAliased == 0:
self.accumWeigth = 1.
self.jitter = None
else:
self.accumWeigth = 1./self.antiAliased
self.jitter = eval('jitter._jitter'+str(self.antiAliased))
self.newList = GL.glGenLists(1)
self.dpyList = None
self.visible = 1
self.ownMaster = False # set tot tru is the master of self.Frame
# has to be destroyed when Camera is deleted
self.exposeEvent = False # set to true on expose events and reset in
# Viewer.ReallyRedraw
self.firstRedraw = True
# create a TK-event manager for this camera
self.eventManager = EventManager(self)
self.eventManager.AddCallback('<Map>', self.Map)
self.eventManager.AddCallback('<Expose>', self.Expose)
self.eventManager.AddCallback('<Configure>', self.Expose)
self.eventManager.AddCallback('<Enter>', self.Enter_cb)
self.onButtonUpCBlist = [] # list of functions to be called when
self.onButtonDownCBlist = [] # mouse button is pressed or depressed
# they take 1 argument of type Tk event
# register funtion to swi
self.addButtonDownCB(self.suspendAA)
self.addButtonUpCB(self.restoreAA)
self.addButtonDownCB(self.suspendNPR)
self.addButtonUpCB(self.restoreNPR)
self.addButtonDownCB(self.reduceSSAOQuality)
self.addButtonUpCB(self.restoreSSAOQuality)
self.addButtonUpCB(self.capClippedGeoms)
# these are used in bindPickingToMouseButton to bind picking to a
# given mouse button
self.mouseButtonModifiers = ['None', 'Shift', 'Control', 'Alt',
'Meta']
# this keys if self.mouseButtonActions are the objects to which the
# trackball can be attached i.e. 'Object', 'Insert2d', 'Camera' etc.
# for each such key there is a dict with buttonnum as key (1,2,3)
# for each such key there is a dict with keys modifiers and values
# a string describing an action
#
# e.g mouseButtonActions['Object'][3]['Shift'] = 'Ztranslation'
self.mouseButtonActions = {}
for bindings in ['Object', 'Insert2d', 'Camera', 'Clip', 'Light',
'Texture', 'Scissor']:
self.mouseButtonActions[bindings] = { 1:{}, 2:{}, 3:{} }
bd = self.mouseButtonActions[bindings]
for b in (1,2,3):
d = bd[b]
for mod in self.mouseButtonModifiers:
d[mod] = 'None'
# initialize actions for object
bd = self.mouseButtonActions['Object']
for mod in self.mouseButtonModifiers:
bd[2][mod] = 'picking'
bd[1]['None'] = 'rotation'
bd[1]['Shift'] = 'addToSelection'
bd[1]['Control'] = 'removeFromSelection'
bd[2]['None'] = 'None'
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Control'] = 'scale'
bd[2]['Shift'] = 'zoom'
bd[3]['None'] = 'XYtranslation'
bd[3]['Control'] = 'pivotOnPixel'
bd[3]['Shift'] = 'Ztranslation'
# initialize actions for Insert2d
bd = self.mouseButtonActions['Insert2d']
for mod in self.mouseButtonModifiers:
bd[1][mod] = 'picking'
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Shift'] = 'zoom'
# initialize actions for Clip
bd = self.mouseButtonActions['Clip']
bd[1]['None'] = 'rotation'
#bd[2]['None'] = 'rotation'
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Control'] = 'scale'
bd[2]['Shift'] = 'zoom'
bd[3]['None'] = 'screenXYtranslation'
bd[3]['Control'] = 'screenZtranslation'
bd[3]['Shift'] = 'Ztranslation'
# initialize actions for Light
bd = self.mouseButtonActions['Light']
bd[1]['None'] = 'rotation'
#bd[2]['None'] = 'rotation'
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Shift'] = 'zoom'
# initialize actions for Camera
bd = self.mouseButtonActions['Camera']
bd[1]['None'] = 'camRotation'
#bd[2]['None'] = 'camRotation'
#bd[2]['Alt'] = 'camZtranslation'
#bd[2]['Control'] = 'zoom'
bd[3]['Shift'] = 'zoom '
bd[3]['None'] = 'camXYtranslation'
bd[3]['Control'] = 'camZtranslation'
# initialize actions for Texture
bd = self.mouseButtonActions['Texture']
bd[1]['None'] = 'rotation'
#bd[2]['None'] = 'rotation'
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Control'] = 'scale'
bd[2]['Shift'] = 'zoom'
bd[3]['None'] = 'XYtranslation'
bd[3]['Shift'] = 'Ztranslation'
# initialize actions for Scissor
bd = self.mouseButtonActions['Scissor']
#bd[2]['Alt'] = 'camZtranslation'
bd[2]['Control'] = 'scale'
bd[2]['Shift'] = 'zoom'
bd[3]['None'] = 'translation'
bd[3]['Shift'] = 'ratio'
# define actionName and callback fucntions equivalence
self.actions = {
'Object': {
'picking':self.initSelectionRectangle,
'addToSelection':self.initSelectionRectangle,
'removeFromSelection':self.initSelectionRectangle,
'rotation':viewer.RotateCurrentObject,
'scale':viewer.ScaleCurrentObject,
'XYtranslation':viewer.TranslateCurrentObjectXY,
'Ztranslation':viewer.TranslateCurrentObjectZ,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
'pivotOnPixel':viewer.pivotOnPixel,
},
'Insert2d': {
'picking':self.SetInsert2dPicking,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
},
'Clip': {
'picking':None,
'rotation':viewer.RotateCurrentClipPlane,
'scale':viewer.ScaleCurrentClipPlane,
'screenXYtranslation':viewer.screenTranslateCurrentObjectXY,
'Ztranslation':viewer.TranslateCurrentObjectZ,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
'screenZtranslation':viewer.screenTranslateCurrentObjectZ,
},
'Light': {
'picking':None,
'rotation':viewer.RotateCurrentDLight,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
},
'Camera': {
'picking':None,
'camRotation':viewer.RotateCurrentCamera,
'zoom':viewer.ScaleCurrentCamera,
'zoom ':viewer.ScaleCurrentCamera, #it doesn't work if we use the same name
'camZtranslation':viewer.TranslateCurrentCamera,
'camXYtranslation':viewer.TranslateXYCurrentCamera, #it doesn't work if we use the same name
},
'Texture': {
'picking':None,
'rotation':viewer.RotateCurrentTexture,
'scale':viewer.ScaleCurrentTexture,
'XYtranslation':viewer.TranslateCurrentTextureXY,
'Ztranslation':viewer.TranslateCurrentTextureZ,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
},
'Scissor': {
'picking':None,
'ratio':viewer.AspectRatioScissor,
'scale':viewer.ScaleCurrentScissor,
'translation':viewer.TranslateCurrentScissor,
'zoom':viewer.ScaleCurrentCamera,
'camZtranslation':viewer.TranslateCurrentCamera,
},
}
# add a trackball
self.AddTrackball()
for binding in ['Object', 'Insert2d', 'Camera', 'Clip', 'Light',
'Texture', 'Scissor']:
self.actions[binding]['None'] = self.trackball.NoFunc
if os.name == 'nt': #sys.platform == 'win32':
self.eventManager.AddCallback(
"<MouseWheel>", viewer.scaleCurrentCameraMouseWheel)
#self.bind("<MouseWheel>", viewer.scaleCurrentCameraMouseWheel)
else:
self.eventManager.AddCallback(
"<Button-4>", viewer.scaleCurrentCameraMouseWheel)
self.eventManager.AddCallback(
"<Button-5>", viewer.scaleCurrentCameraMouseWheel)
#self.bind("<Button-4>", viewer.scaleCurrentCameraMouseWheel)
#self.bind("<Button-5>", viewer.scaleCurrentCameraMouseWheel)
# light model is define in Viewer for all cameras
# self.lightModel = None
self.fog = Fog(self)
self.fog.Set(color=self.backgroundColor)
self.pack(side='left', expand=1, fill='both')
# attributes used to draw black outlines
# self.imCanvastop = None # top level window for silhouette rendering
self.contouredImage = None # will hole the final PIL image
self.outlineim = None # will hole the final contour
self.outline = None # accumulation buffer used for AA contour
self.contours = False # set to True to enable contouring
self.d1scale = 0.013
self.d1off = 4
self.d1cutL = 0
self.d1cutH = 60
self.d1ramp = Numeric.arange(0,256,1,'f')
self.d2scale = 0.0 # turn off second derivative
self.d2off = 1
self.d2cutL = 150
self.d2cutH = 255
self._suspendNPR = False # used during motion
# we save it so it can be reapplied if the projection matrix is recreated
self.pickMatrix = None
# prepare contour highlight
self.contourTextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.contourTextureName]), numpy.array([1.])) # supposedly make this texture fast
_gllib.glBindTexture(GL_TEXTURE_2D, int(self.contourTextureName) )
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
self.stencilTextureName = int(glGenTextures(1)[0])
# glPrioritizeTextures supposedly make this texture fast
glPrioritizeTextures(numpy.array([self.stencilTextureName]),
numpy.array([1.]))
_gllib.glBindTexture(GL_TEXTURE_2D, int(self.stencilTextureName) )
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
# prepare patterned highlight
self.textureName = int(glGenTextures(1)[0])
lTexture = Numeric.array(
(
(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.8),(1.,1.,1.,.6),(1.,1.,1.,.6),(.0,.0,.0,.8),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.8),(1.,1.,1.,.6),(1.,1.,1.,.6),(.0,.0,.0,.8),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.8),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),(.0,.0,.0,.0),
),'f')
_gllib.glBindTexture(GL_TEXTURE_2D, self.textureName )
glPrioritizeTextures(numpy.array([self.textureName]), numpy.array([1.])) # supposedly make this texture fast
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
_gllib.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 8, 8, 0, GL_RGBA,
GL.GL_FLOAT, lTexture)
#glEnable(GL_TEXTURE_GEN_S)
#glEnable(GL_TEXTURE_GEN_T)
#glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR )
#glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR )
#glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)
# to protect our texture, we bind the default texture while we don't use it
self.dsT = 0
# to protect our texture, we bind the default texture while we don't use it
self.ssao_method = 0
self.copy_depth_ssao = True
if 'ssao' not in kw:
kw['ssao'] = False
self.ssao = False
self.use_mask_depth = 0
self._oldSSAOSamples = 6
else :
self.ssao = kw['ssao']
self._oldSSAOSamples = 6
if 'SSAO_OPTIONS' in kw :
self.SSAO_OPTIONS = kw['SSAO_OPTIONS']
else :
self.use_mask_depth = 0
self.setDefaultSSAO_OPTIONS()
self.setShaderSSAO()
_gllib.glBindTexture(GL_TEXTURE_2D, 0 )
self.setShaderSelectionContour()
self.cursorStack = []
self.currentCursor = 'default'
def addButtonDownCB(self, func):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
assert callable(func)
if func not in self.onButtonDownCBlist:
self.onButtonDownCBlist.append(func)
def delButtonDownCB(self, func, silent=False):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if func in self.onButtonDownCBlist:
self.onButtonDownCBlist.remove(func)
else:
if not silent:
print 'WARNING: delButtonDownCB: function not found', func
def addButtonUpCB(self, func):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
assert callable(func)
if func not in self.onButtonUpCBlist:
self.onButtonUpCBlist.append(func)
def delButtonUpCB(self, func, silent=False):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if func in self.onButtonUpCBlist:
self.onButtonUpCBlist.remove(func)
else:
if not silent:
print 'WARNING: delButtonUpCB: function not found', func
def reduceSSAOQuality(self, event):
if self.ssao:
self._oldSSAOSamples = self.SSAO_OPTIONS['samples'][0]
if len(self.SSAO_OPTIONS['samples']) == 5 :
self.SSAO_OPTIONS['samples'][-1].set(2)
else:
self.SSAO_OPTIONS['samples'][0] = 2
def restoreSSAOQuality(self, event):
if self.ssao:
if len(self.SSAO_OPTIONS['samples']) == 5 :
self.SSAO_OPTIONS['samples'][-1].set(self._oldSSAOSamples)
else:
self.SSAO_OPTIONS['samples'][0] = self._oldSSAOSamples
del self._oldSSAOSamples
def suspendAA(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Function used to turn off anti-aliasing during motion
"""
#print "suspendAA"
if self.antiAliased == False:
self.antiAliased = 0
assert isinstance(self.antiAliased, types.IntType), self.antiAliased
if self._wasAntiAliased == 0 : # else it is already suspended
if self.antiAliased <= DejaVu.allowedAntiAliasInMotion:
# save the state
self._wasAntiAliased = self.antiAliased
# we don't suspend anti alias or anti alias is already suspended
else:
# save the state
self._wasAntiAliased = self.antiAliased
# we suspend anti alias
self.antiAliased = 0
def restoreAA(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Function used to restore anti-aliasing after motion
"""
#print "restoreAA"
self.antiAliased = self._wasAntiAliased
self._wasAntiAliased = 0
def capClippedGeoms(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Function used to cap clipped geoms when button is released"""
if self.currentTransfMode!='Clip':
return
for geom, cp, capg in self.viewer.cappedGeoms:
if cp != self.viewer.currentClip:
continue
vc, fc = cp.getCapMesh(geom)
capg.Set(vertices=vc, faces=fc)
def suspendNPR(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Function used to turn off NPR during motion
"""
if self.viewer.GUI.contourTk.get() is True:
self._suspendNPR = True
self._suspendNPR_rootMaterialsPropDiffuse = self.viewer.rootObject.materials[GL.GL_FRONT].prop[1]
self._suspendNPR_rootMaterialsbindDiffuse = self.viewer.rootObject.materials[GL.GL_FRONT].binding[1]
#print "self._suspendNPR_rootMaterialsPropDiffuse", self._suspendNPR_rootMaterialsPropDiffuse
#print "self._suspendNPR_rootMaterialsbindDiffuse", self._suspendNPR_rootMaterialsbindDiffuse
if self._suspendNPR_rootMaterialsbindDiffuse == 1 \
and len(self._suspendNPR_rootMaterialsPropDiffuse) == 1 \
and len(self._suspendNPR_rootMaterialsPropDiffuse[0]) >= 3 \
and self._suspendNPR_rootMaterialsPropDiffuse[0][0] == 1 \
and self._suspendNPR_rootMaterialsPropDiffuse[0][1] == 1 \
and self._suspendNPR_rootMaterialsPropDiffuse[0][2] == 1 :
# root color is set to grey
self.viewer.rootObject.materials[GL.GL_FRONT].prop[1] = Numeric.array( ((.5, .5, .5, 1.0 ), ), 'f' )
self.viewer.rootObject.materials[GL.GL_FRONT].binding[1] = viewerConst.OVERALL
# lighting is turned on
self._suspendNPR_OverAllLightingIsOn = self.viewer.OverAllLightingIsOn.get()
self.viewer.OverAllLightingIsOn.set(1)
self.viewer.deleteOpenglListAndCallRedrawAndCallDisableGlLighting()
def restoreNPR(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Function used to restore NPR after motion
"""
if self.viewer.GUI.contourTk.get() is True:
# root color is set to what it was
self.viewer.rootObject.materials[GL.GL_FRONT].prop[1] = self._suspendNPR_rootMaterialsPropDiffuse
self.viewer.rootObject.materials[GL.GL_FRONT].binding[1] = self._suspendNPR_rootMaterialsbindDiffuse
# lighting is set to what it was
self.viewer.OverAllLightingIsOn.set(self._suspendNPR_OverAllLightingIsOn)
self.viewer.deleteOpenglListAndCallRedrawAndCallDisableGlLighting()
self._suspendNPR = False
def pushCursor(self, cursorName):
self.configure(cursor=cursorsDict[cursorName])
self.cursorStack.append(self.currentCursor)
self.currentCursor = cursorName
def popCursor(self):
if len(self.cursorStack):
self.currentCursor = cursorName = self.cursorStack.pop(-1)
self.configure(cursor=cursorsDict[cursorName])
def setCursor(self, buttonNum):
modDict = self.viewer.kbdModifier
xform = self.viewer.GUI.Xform.get()
if modDict['Shift_L']:
action = self.mouseButtonActions[xform][buttonNum]['Shift']
elif modDict['Control_L']:
action = self.mouseButtonActions[xform][buttonNum]['Control']
elif modDict['Alt_L']:
action = self.mouseButtonActions[xform][buttonNum]['Alt']
else:
action = self.mouseButtonActions[xform][buttonNum]['None']
#print 'AAAAAAAAAAAA', action#, modDict
if cursorsDict.has_key(action):
self.configure(cursor=cursorsDict[action])
def bindAllActions(self, actionDict):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#print "bindAllActions", actionDict
for b in (1,2,3):
d = self.mouseButtonActions[actionDict][b]
for mod in self.mouseButtonModifiers:
self.bindActionToMouseButton(d[mod], b, mod, actionDict)
def findButton(self, action, actionDict):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
for b in (1,2,3):
d = self.mouseButtonActions[actionDict][b]
for mod in self.mouseButtonModifiers:
if d[mod]==action: return b, mod
return None, None
# FIXME picking and other mouse actions should be unified
# Press events register the motion and release callbacks
# this will enable to process picking and others in the same way
def bindActionToMouseButton(self, action, buttonNum, modifier='None',
actionDict='Object'):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""registers callbacks to trigger picking when the specified mouse
button is pressed. buttonNum can be 1,2,3 or 0 to remove call backs
"""
#print "bindActionToMouseButton", buttonNum, action, modifier, actionDict
ehm = self.eventManager
func = self.actions[actionDict][action]
# find button and modifier to which actions is bound currently
oldnum, oldmod = self.findButton(action, actionDict)
if action in ['picking', 'addToSelection', 'removeFromSelection',
'pivotOnPixel']:
if oldnum: # picking action was bound to a mouse button
# remove the picking callbacks from previous picking button
if modifier=='None': modifier1=''
else: modifier1=modifier+'-'
ev = '<'+modifier1+'ButtonPress-'+str(oldnum)+'>'
ehm.RemoveCallback(ev, func)
# remove all motion call back on buttonNum for all modifiers
if modifier=='None': modifier1=''
else: modifier1=modifier+'-'
setattr(self.trackball, modifier1+'B'+str(buttonNum)+'motion',
self.trackball.NoFunc)
# now bind picking to buttonNum for all modifiers
self.mouseButtonActions[actionDict][buttonNum][modifier] = action
if modifier=='None': modifier1=''
else: modifier1=modifier+'-'
ev = '<'+modifier1+'ButtonPress-'+str(buttonNum)+'>'
ehm.AddCallback(ev, func)
else: # not picking
if oldnum: # action was bound to a mouse button
# remove the picking callbacks from previous picking button
if oldmod=='None': mod1=''
else: mod1=oldmod+'-'
ev = '<'+mod1+'ButtonPress-'+str(oldnum)+'>'
oldaction = self.mouseButtonActions[actionDict][buttonNum][oldmod]
if oldaction=='picking' or oldaction=='pivotOnPixel':
ehm.RemoveCallback(ev, self.actions[actionDict][oldaction])
# remove motion callback on oldbuttonNum for oldmodifier
if oldmod=='None': mod=''
else: mod=oldmod
setattr(self.trackball, mod+'B'+str(oldnum)+'motion',
self.trackball.NoFunc)
self.mouseButtonActions[actionDict][oldnum][oldmod] = 'None'
# remove picking callback on buttonNum for modifier
if modifier=='None': mod=''
else: mod=modifier+'-'
oldaction = self.mouseButtonActions[actionDict][buttonNum][modifier]
if oldaction=='picking' or oldaction=='pivotOnPixel':
ev = '<'+mod+'ButtonPress-'+str(buttonNum)+'>'
ehm.RemoveCallback(ev, self.actions[actionDict][oldaction])
# now bind picking to buttonNum for all modifiers
if modifier=='None': mod=''
else: mod=modifier
setattr(self.trackball, mod+'B'+str(buttonNum)+'motion', func)
self.mouseButtonActions[actionDict][buttonNum][modifier] = action
def AddTrackball(self, size=0.8, rscale=2.0, tscale=0.05,
sscale=0.01, renorm=97):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Add a Trackball to this camera with default bindings
"""
#print "AddTrackball"
self.trackball = Trackball(self, size, rscale, tscale, sscale, renorm )
ehm = self.eventManager
#print 'FOO1'
# COMMENTED OUT BY MS when I moved rotation to button 1
#self.bindActionToMouseButton('rotation', 1)
## ehm.AddCallback('<ButtonPress-1>', self.recordMousePosition_cb)
## ehm.AddCallback('<ButtonRelease-1>', self.SelectPick)
## ehm.AddCallback('<Shift-ButtonRelease-1>', self.CenterPick_cb)
## ehm.AddCallback('<Double-ButtonRelease-1>', self.DoubleSelectPick_cb)
## ehm.AddCallback('<Triple-ButtonRelease-1>', self.TransfCamera_cb)
# <ButtonPress-1> is set by default to record the mouse position
# add drawing of first selection rectangle
# ehm.AddCallback("<ButtonPress-1>", self.initSelectionRectangle )
# ehm.AddCallback("<Shift-ButtonPress-1>", self.initSelectionRectangle )
# ehm.AddCallback("<Control-ButtonPress-1>", self.initSelectionRectangle )
# ehm.AddCallback("<Alt-ButtonPress-1>", self.initSelectionRectangle )
def ListBoundEvents(self, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""List all event bound to a callback function"""
if not event:
return self.bind()
else:
return self.bind(event)
def __del__(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Destroy the camera
"""
#print "StandardCamera.__del__", self
self.frame.master.destroy()
def Enter_cb(self, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Call back function trigger when the mouse enters the camera
"""
if widgetsOnBackWindowsCanGrabFocus is False:
lActiveWindow = self.focus_get()
if lActiveWindow is not None \
and ( lActiveWindow.winfo_toplevel() != self.winfo_toplevel() ):
return
self.focus_set()
self.tk.call(self._w, 'makecurrent')
if not self.viewer:
return
self.SelectCamera()
if not hasattr(self.viewer.GUI, 'Xform'):
return
self.viewer.GUI.Xform.set(self.currentTransfMode)
if self.currentTransfMode=='Object':
self.viewer.GUI.enableNormalizeButton(Tkinter.NORMAL)
self.viewer.GUI.enableCenterButton(Tkinter.NORMAL)
else:
self.viewer.GUI.enableNormalizeButton(Tkinter.DISABLED)
self.viewer.GUI.enableCenterButton(Tkinter.DISABLED)
def _setFov(self, fov):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if fov > 0.0 and fov < 180.0: self.fovy = fov
else: raise AttributeError('fov has to be < 180.0 and > 0.0 was %f'%fov)
def _setLookFrom(self, val):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
mat = numpy.array(val, 'f')
self.lookFrom = mat
self.direction = self.lookAt - self.lookFrom
def Set(self, check=1, redo=1, **kw):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Set various camera parameters
"""
#print "Camera.Set", redo
if __debug__:
if check:
apply( checkKeywords, (self.name,self.setKeywords), kw)
val = kw.get( 'tagModified', True )
assert val in [True, False]
self._modified = val
# we disable redraw because autoRedraw could cause ReallyRedraw
# to set camera.width and camera.height BEFORE te window gets
# resized by Tk
if self.viewer.autoRedraw:
restoreAutoRedraw = True
self.viewer.stopAutoRedraw()
else:
restoreAutoRedraw = False
w = kw.get( 'width')
if not w is None:
assert type(w)==types.IntType
if w > 0:
self.width = w
else:
raise AttributeError('width has to be > 0')
h = kw.get( 'height')
if not h is None:
assert type(h)==types.IntType
if h > 0:
# we disable redraw because autoRedraw could cause ReallyRedraw
# to set camera.width and camera.height BEFORE te window gets
# resized by Tk
self.height = h
else:
raise AttributeError('height has to be > 0')
px = kw.get( 'rootx')
if not px is None:
px = max(px, 0)
master = self.frame.master
while hasattr(master, 'wm_maxsize') is False:
master = master.master
xmax, ymax = master.wm_maxsize()
px = min(px, xmax -100)
self.rootx = px
py = kw.get( 'rooty')
if not py is None:
py = max(py, 0)
master = self.frame.master
while hasattr(master, 'wm_maxsize') is False:
master = master.master
xmax, ymax = master.wm_maxsize()
py = min(py, ymax - 100)
self.rooty = py
# if width, height of position of camera changed apply changes
if w or h or px or py:
self.Geometry()
self.viewer.update()
if restoreAutoRedraw:
self.viewer.startAutoRedraw()
fov = kw.get( 'fov')
if not fov is None:
if fov > 0.0 and fov < 180.0: self.fovy = fov
else: raise AttributeError('fov has to be < 180.0 and > 0.0 was %f'%fov)
near = kw.get( 'near')
if not near is None:
if kw.has_key('far'): far = kw.get('far')
else: far = self.far
if near >= far:
raise AttributeError('near sould be smaller than far')
self.near = max(near, self.nearDefault)
self.near_real = near
far = kw.get( 'far')
if not far is None:
if far <= self.near:
if self.near == self.nearDefault:
self.far = self.near * 1.5
else:
raise AttributeError('far sould be larger than near')
else:
self.far = far
if fov or near or far:
self.SetupProjectionMatrix()
val = kw.get( 'color')
if not val is None:
color = colorTool.OneColor( val )
if color:
self.backgroundColor = color
val = kw.get( 'antialiased')
if not val is None:
if val in jitter.jitterList:
self.antiAliased = val
if val!=0:
self.accumWeigth = 1.0/val
self.jitter = eval('jitter._jitter'+str(val))
else: raise ValueError('antiAliased can only by one of', \
jitter.jitterList)
# NPR parameters
#first derivative
val = kw.get( 'd1ramp')
if not val is None:
self.d1ramp=val
val = kw.get( 'd1scale')
if not val is None:
assert isinstance(val, float)
assert val>=0.0
self.d1scale = val
val = kw.get( 'd1off')
if not val is None:
assert isinstance(val, int)
self.d1off = val
val = kw.get( 'd1cutL')
if not val is None:
assert isinstance(val, int)
assert val>=0
self.d1cutL = val
val = kw.get( 'd1cutH')
if not val is None:
assert isinstance(val, int)
assert val>=0
self.d1cutH = val
#second derivative
val = kw.get( 'd2scale')
if not val is None:
assert isinstance(val, float)
assert val>=0.0
self.d2scale = val
val = kw.get( 'd2off')
if not val is None:
assert isinstance(val, int)
self.d2off = val
val = kw.get( 'd2cutL')
if not val is None:
assert isinstance(val, int)
assert val>=0
self.d2cutL = val
val = kw.get( 'd2cutH')
if not val is None:
assert isinstance(val, int)
assert val>=0
self.d2cutH = val
val = kw.get( 'contours')
if not val is None:
assert val in [True, False]
if self.contours != val:
self.contours = val
if val is True:
self.lastBackgroundColorInPhotoMode = self.backgroundColor
self.backgroundColor = (1.,1.,1.,1.)
if self.viewer.OverAllLightingIsOn.get() == 1:
self.viewer.OverAllLightingIsOn.set(0)
else:
self.backgroundColor = self.lastBackgroundColorInPhotoMode
if self.viewer.OverAllLightingIsOn.get() == 0:
self.viewer.OverAllLightingIsOn.set(1)
self.fog.Set(color=self.backgroundColor)
self.viewer.deleteOpenglListAndCallRedrawAndCallDisableGlLighting()
# if val:
# self.imCanvastop = Tkinter.Toplevel()
# self.imCanvas = Tkinter.Canvas(self.imCanvastop)
# self.imCanvas1 = Tkinter.Canvas(self.imCanvastop)
# self.imCanvas2 = Tkinter.Canvas(self.imCanvastop)
# self.imCanvas3 = Tkinter.Canvas(self.imCanvastop)
# self.canvasImage = None
# self.canvasImage1 = None
# self.canvasImage2 = None
# self.canvasImage3 = None
# elif self.imCanvastop:
# self.imCanvastop.destroy()
# self.imCanvas = None
# self.imCanvas1 = None
# self.imCanvas2 = None
# self.imCanvas3 = None
# if hasattr(self, 'ivi'):
# self.ivi.Exit()
# from opengltk.OpenGL import GL
# if not hasattr(GL, 'GL_CONVOLUTION_2D'):
# print 'WARNING: camera.Set: GL_CONVOLUTION_2D nor supported'
# self.contours = False
# else:
# from DejaVu.imageViewer import ImageViewer
# self.ivi = ImageViewer(name='zbuffer')
val = kw.get( 'boundingbox')
if not val is None:
if val in viewerConst.BB_MODES:
self.drawBB = val
else: raise ValueError('boundingbox can only by one of NO, \
ONLY, WITHOBJECT')
val = kw.get( 'rotation')
if not val is None:
self.rotation = Numeric.identity(4, 'f').ravel()
mat = Numeric.reshape(Numeric.array(val), (4,4)).astype('f')
self.ConcatRotation(mat)
val = kw.get( 'translation')
if not val is None:
self.translation = Numeric.zeros( (3,), 'f')
mat = Numeric.reshape(Numeric.array(val), (3,)).astype('f')
self.ConcatTranslation(mat, redo=redo)
val = kw.get( 'scale')
if not val is None:
self.SetScale( val, redo=redo )
val = kw.get( 'pivot')
if not val is None:
self.SetPivot( val )
val = kw.get( 'direction')
if not val is None:
mat = Numeric.reshape(Numeric.array(val), (3,)).astype('f')
self.direction = mat
valLookFrom = kw.get('lookFrom')
if valLookFrom is not None:
mat = numpy.array(valLookFrom, 'f')
assert mat.shape==(3,)
self.lookFrom = mat
self.direction = self.lookAt - self.lookFrom
valLookAt = kw.get('lookAt')
if valLookAt is not None:
mat = numpy.array(valLookAt, 'f')
assert mat.shape==(3,)
self.lookAt = mat
self.direction = self.lookAt - self.lookFrom
valUp = kw.get('up')
if valUp is not None:
mat = numpy.array(valUp, 'f')
assert mat.shape==(3,)
self.up = mat
## # compute .translation and .rotation used to build camera transformation
## # FIXME .. could recompute only if one changed
## if valLookAt is not None \
## or valLookFrom is not None \
## or valUp is not None:
## glPushMatrix()
## glLoadIdentity()
## glMatrixMode(GL_MODELVIEW)
## fx, fy, fz = self.lookFrom
## ax, ay, az = self.lookAt
## ux, uy, uz = self.up
## gluLookAt( float(fx), float(fy), float(fx),
## float(ax), float(ay), float(az),
## float(ux), float(uy), float(uz) )
## lMatrix = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
## lRotation, lTranslation, lScale = self.Decompose4x4(lMatrix, cleanup=False)
## glPopMatrix()
## if numpy.any(lMatrix):
## self.rotation = lRotation
## self.translation = lTranslation
## self.lookAt = Numeric.reshape(Numeric.array(valLookAt), (3,)).astype('f')
## val = kw.get( 'lookAt')
## if not val is None:
## mat = Numeric.reshape(Numeric.array(val), (3,)).astype('f')
## self.lookAt = mat
## self.direction = self.lookAt - self.lookFrom
## val = kw.get( 'lookFrom')
## if not val is None:
## mat = Numeric.reshape(Numeric.array(val), (3,)).astype('f')
## self.lookFrom = mat
## self.direction = self.lookAt - self.lookFrom
val = kw.get( 'projectionType')
if val==self.PERSPECTIVE:
if self.projectionType==self.ORTHOGRAPHIC:
self.projectionType = val
self.OrthogonalToPerspective()
elif val==self.ORTHOGRAPHIC:
if self.projectionType==self.PERSPECTIVE:
self.projectionType = val
self.PerspectiveToOrthogonal()
val = kw.get( 'sideBySideRotAngle')
if not val is None:
assert type(val)==types.FloatType
self.sideBySideRotAngle = val
if self.viewer:
self.viewer.Redraw()
val = kw.get( 'sideBySideTranslation')
if not val is None:
assert type(val)==types.FloatType
self.sideBySideTranslation = val
if self.viewer:
self.viewer.Redraw()
val = kw.get( 'ssao')
if not val is None:
self.ssao = kw["ssao"]
val = kw.get( 'SSAO_OPTIONS')
if not val is None:
self.SSAO_OPTIONS = kw['SSAO_OPTIONS']
self._oldSSAOSamples = 6
val = kw.get( 'stereoMode')
if val is not None:
assert val in self.stereoModesList
glDrawBuffer(GL_BACK)
if self.viewer is None:
warnings.warn("""Stereo buffers are not present
or not enabled on this system.
enableStereo must be set to True in:
~/.mgltools/(ver_number)/DejaVu/_dejavurc
"""
)
val = 'MONO'
elif self.viewer.activeStereoSupport is False:
if val == 'STEREO_BUFFERS':
warnings.warn("""Stereo buffers are not present
or not enabled on this system.
enableStereo must be set to True in:
~/.mgltools/(ver_number)/DejaVu/_dejavurc
"""
)
val = 'MONO'
self.stereoMode = val
if self.viewer:
self.viewer.Redraw()
val = kw.get( 'suspendRedraw')
if val is not None:
assert val in [True, False]
self.suspendRedraw = val
val = kw.get( 'drawThumbnail')
if val is not None:
assert val in [True, False]
self.drawThumbnailFlag = val
# def deleteOpenglList(self):
# #import traceback;traceback.print_stack()
# #print "Camera.deleteOpenglList"
# if self.dpyList is not None:
# self.tk.call(self._w, 'makecurrent')
# currentcontext = self.tk.call(self._w, 'contexttag')
# if currentcontext != self.dpyList[1]:
# warnings.warn("""deleteOpenglList failed because the current context is the wrong one""")
# #print "currentcontext != self.dpyList[1]", currentcontext, self.dpyList[1]
# else:
# #print '-%d'%self.dpyList[0], currentcontext, "glDeleteLists Viewer"
# GL.glDeleteLists(self.dpyList[0], 1)
# self.dpyList = None
def SwapBuffers(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.tk.call(self._w, 'swapbuffers')
def Activate(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Make this Opengl widget the current destination for drawing."""
self.tk.call(self._w, 'makecurrent')
def OrthogonalToPerspective(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Compute left, right, top, bottom from field of view"""
d = self.near + (self.far - self.near)*0.5
self.fovy = (math.atan(self.top/d) * 360.0) / math.pi
self.SetupProjectionMatrix()
def PerspectiveToOrthogonal(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Compute left, right, top, bottom from field of view"""
aspect = self.width / float(self.height)
fov2 = (self.fovy*math.pi) / 360.0 # fov/2 in radian
d = self.near + (self.far - self.near)*0.5
self.top = d*math.tan(fov2)
self.bottom = -self.top
self.right = aspect*self.top
self.left = -self.right
self.SetupProjectionMatrix()
def SetupProjectionMatrix(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Setup the projection matrix"""
if not self.initialized:
return
self.tk.call(self._w, 'makecurrent')
glViewport(0, 0, self.width, self.height)
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_PROJECTION);
glLoadIdentity()
## if self.viewer.tileRender:
## print 'FUGU'
## if self.projectionType==self.PERSPECTIVE:
## self.viewer.tileRenderCtx.perspective(self.fovy,
## float(self.width)/float(self.height),
## self.near, self.far)
## else:
## self.viewer.tileRenderCtx.ortho(self.left, self.right,
## self.bottom, self.top,
## self.near, self.far)
## print 'near', self.viewer.tileRenderCtx.Near
if self.projectionType==self.PERSPECTIVE:
# protect from bug in mac intel when zomming on molecule 1BX4
if sys.platform == 'darwin':
if self.fovy < .003:
self.fovy = .003
gluPerspective(float(self.fovy),
float(self.width)/float(self.height),
float(self.near), float(self.far))
else:
glOrtho(float(self.left), float(self.right),
float(self.bottom), float(self.top),
float(self.near), float(self.far))
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
## from opengltk.OpenGL import GLU
## GLU.gluLookAt(0., 0., 30., 0.,0.,0., 0.,1.,0.)
## print 'Mod Mat:', glGetDoublev(GL_MODELVIEW_MATRIX)
## glLoadIdentity();
# The first 6 arguments are identical to the glFrustum() call.
#
# pixdx and pixdy are anti-alias jitter in pixels.
# Set both equal to 0.0 for no anti-alias jitter.
# eyedx and eyedy are depth-of field jitter in pixels.
# Set both equal to 0.0 for no depth of field effects.
#
# focus is distance from eye to plane in focus.
# focus must be greater than, but not equal to 0.0.
#
# Note that AccFrustum() calls glTranslatef(). You will
# probably want to insure that your ModelView matrix has been
# initialized to identity before calling accFrustum().
def AccFrustum(self, left, right, bottom, top, near, far,
pixdx, pixdy, eyedx, eyedy, focus):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
viewport = Numeric.array(glGetDoublev (GL_VIEWPORT))
xwsize = right - left
ywsize = top - bottom
dx = -(pixdx*xwsize/viewport[2] + eyedx*near/focus)
dy = -(pixdy*ywsize/viewport[3] + eyedy*near/focus)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glFrustum (float(left + dx), float(right + dx),
float(bottom + dy), float(top + dy),
float(near), float(far))
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef (float(-eyedx), float(-eyedy), 0.0)
# The first 4 arguments are identical to the gluPerspective() call.
# pixdx and pixdy are anti-alias jitter in pixels.
# Set both equal to 0.0 for no anti-alias jitter.
# eyedx and eyedy are depth-of field jitter in pixels.
# Set both equal to 0.0 for no depth of field effects.
#
# focus is distance from eye to plane in focus.
# focus must be greater than, but not equal to 0.0.
# Note that AccPerspective() calls AccFrustum().
def AccPerspective(self, pixdx, pixdy, eyedx, eyedy, focus,
left=None, right=None, bottom=None, top=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Build perspective matrix for jitter"""
from math import pi, cos, sin
fov2 = self.fovy*pi / 360.0;
if top is None:
top = self.near / (cos(fov2) / sin(fov2))
if bottom is None:
bottom = -top
if right is None:
right = top * float(self.width)/float(self.height)
if left is None:
left = -right;
self.AccFrustum (left, right, bottom, top, self.near, self.far,
pixdx, pixdy, eyedx, eyedy, focus)
def InitGL(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Initialize some GL features"""
self.tk.call(self._w, 'makecurrent')
glEnable(GL_CULL_FACE)
glEnable(GL_NORMALIZE) # required if glScale is used,
# else the lighting doesn't work anymore
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
# blend function used for line anti-aliasing
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
self.initialized = 1
def Map(self, *dummy):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Cause the opengl widget to redraw itself."""
self.Expose()
## def Configure(self, *dummy):
## """Cause the opengl widget to redraw itself."""
## self.tk.call(self._w, 'makecurrent')
## self.width = self.winfo_width()
## self.height = self.winfo_height()
## self.rootx = self.winfo_rootx()
## self.rooty = self.winfo_rooty()
## # FIXME .. this is not symetrical ... should we just recompute left, right,
## # top and botom here ???
## if self.projectionType==self.ORTHOGRAPHIC:
## self.PerspectiveToOrthogonal()
## else:
## self.SetupProjectionMatrix()
## self.Expose()
def Expose(self, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""set the camera's exposeEvent so that at the next redraw
the camera width and height are updated
"""
if not self.viewer.isInitialized:
self.after(100, self.Expose)
else:
# if viewer is in autoRedraw mode the next redraw will handle it
if not self.exposeEvent and self.viewer.autoRedraw:
self.viewer.Redraw()
self.exposeEvent = True
for o in self.viewer.rootObject.AllObjects():
if o.needsRedoDpyListOnResize or o.scissor:
self.viewer.objectsNeedingRedo[o] = None
## moved the width and height into viewer.ReallyRedraw
## def ReallyExpose(self, *dummy):
## """Redraw the widget.
## Make it active, update tk events, call redraw procedure and
## swap the buffers. Note: swapbuffers is clever enough to
## only swap double buffered visuals."""
## self.tk.call(self._w, 'makecurrent')
## self.width = self.winfo_width()
## self.height = self.winfo_height()
## #self.SetupProjectionMatrix()
## #self.InitGL()
## self.Redraw()
def drawOneObjectThumbnail(self, obj):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.ActivateClipPlanes( obj.clipP, obj.clipSide )
if obj.scissor:
glEnable(GL_SCISSOR_TEST)
glScissor(obj.scissorX, obj.scissorY, obj.scissorW, obj.scissorH)
inst = 0
v = obj.vertexSet.vertices.array
v = Numeric.reshape(v, (-1,3)).astype('f')
for m in obj.instanceMatricesFortran:
inst = inst + 1
glPushMatrix()
glMultMatrixf(m)
if isinstance(obj, Transformable):
v = obj.vertexSet.vertices.array
if len(v.shape) >2 or v.dtype.char!='f':
v = Numeric.reshape(v, (-1,3)).astype('f')
if len(v) >0:
#t1 = time()
namedPoints(len(v), v)
#glVertexPointer(2, GL_FLOAT, 0, v)
#glEnableClientState(GL_VERTEX_ARRAY)
#glDrawArrays(GL_POINTS, 0, len(v) )
#glDisableClientState(GL_VERTEX_ARRAY)
else: #Insert2d
obj.pickDraw()
glPopMatrix()
for c in obj.clipP: # disable object's clip planes
c._Disable()
if obj.scissor:
glDisable(GL_SCISSOR_TEST)
def DrawObjThumbnail(self, obj):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""draws an object for picking purposes. If type is 'vertices' a
display list for vertices identification is used. If type is parts
a display list identifying geometric primitives such as triangles or
lines is used
"""
if isinstance(obj, Transformable):
glPushMatrix()
obj.MakeMat()
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
inst = 0
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
for child in obj.children:
if child.visible:
self.DrawObjThumbnail(child)
glPopMatrix()
inst = inst + 1
if obj.visible:
self.drawOneObjectThumbnail(obj)
for c in obj.clipPI: # disable object's clip planes that are
c._Disable() # inherited by children
glPopMatrix() # Restore the matrix
def RedrawThumbnail(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
glClear(GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glPointSize(1.0)
self.BuildTransformation() # camera transformation
obj = self.viewer.rootObject
obj.MakeMat()
if len(obj.clipPI):
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
inst = 0
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
for child in obj.children:
if child.visible:
self.DrawObjThumbnail(child)
glPopMatrix()
inst = inst + 1
for c in obj.clipPI: c._Disable()
glPopMatrix()
def drawThumbnail(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.tk.call(self._w, 'makecurrent')
glViewport(0, 0, self.width/10, self.height/10)
glMatrixMode (GL_PROJECTION)
glPushMatrix()
glLoadIdentity ()
# create projection matrix and modeling
# self.SetupProjectionMatrix()
if self.projectionType==self.PERSPECTIVE:
gluPerspective(float(self.fovy),
float(self.width)/float(self.height),
float(self.near),float(self.far))
else:
glOrtho(float(self.left),float(self.right),
float(self.bottom), float(self.top),
float(self.near), float(self.far))
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
self.RedrawThumbnail()
glFlush ()
glMatrixMode (GL_PROJECTION)
glPopMatrix ()
glMatrixMode(GL_MODELVIEW)
def DoPick(self, x, y, x1=None, y1=None, type=None, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Makes a redraw in GL_SELECT mode to pick objects
"""
if self.stereoMode != 'MONO':
return
if type is None:
type = self.viewer.pickLevel
if x1 is None: x1 = x
if y1 is None: y1 = y
#print 'pick at', x, y, x1, y1
self.tk.call(self._w, 'makecurrent')
vp = [0,0,self.width, self.height]
selectBuf = glSelectBuffer( 1000000 )
# 500000 was insuficient on bigger molecule as 2plv.pdb with MSMS
y1 = vp[3] - y1
y = vp[3] - y
dx = x - x1
dy = y - y1
#x = x
pickWinSize = 10
if math.fabs(dx) < pickWinSize: dx=pickWinSize
else: x = x1 + (dx/2)
if math.fabs(dy) < pickWinSize: dy=pickWinSize
else: y = y1 + (dy/2)
if dx==pickWinSize and dy==pickWinSize:
mode = 'pick'
else:
mode = 'drag select'
abdx = int(math.fabs(dx))
abdy = int(math.fabs(dy))
#print 'pick region ', x-math.fabs(dx), y-math.fabs(dy), x+math.fabs(dx), y+math.fabs(dy), mode
# debug
glRenderMode (GL_SELECT)
self.renderMode = GL_SELECT
glInitNames()
glPushName(0)
glMatrixMode (GL_PROJECTION)
glPushMatrix()
glLoadIdentity ()
# create abs(dx)*abs(dy) pixel picking region near cursor location
gluPickMatrix( x, y, abdx, abdy, vp)
# we save it so it can be reapplied if the projection matrix is recreated
self.pickMatrix = glGetFloatv(GL_PROJECTION_MATRIX)
# create projection matrix and modeling
# self.SetupProjectionMatrix()
if self.projectionType==self.PERSPECTIVE:
gluPerspective(self.fovy,float(self.width)/float(self.height),
self.near, self.far)
else:
glOrtho(float(self.left),float(self.right),
float(self.bottom),float(self.top),
float(self.near), float(self.far))
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
self.RedrawPick(type);
glFlush ()
# debug
###self.tk.call(self._w, 'swapbuffers')
###return PickObject('pick')
self.renderMode = GL_RENDER;
# get the number of hits
selectHits = glRenderMode (GL_RENDER)
#print "hits", selectHits
#removed because it generates bug in displaylist
#if selectHits == 0:
# # if we pick the background, root becomes selected
# self.viewer.SetCurrentObject(self.viewer.rootObject)
# restore projection matrix
glMatrixMode (GL_PROJECTION)
glPopMatrix ()
# unproject points x and y
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() # restore matrix for unproject
self.BuildTransformation()
self.viewer.rootObject.MakeMat()
self.unProj_model = glGetDoublev(GL_MODELVIEW_MATRIX)
self.unProj_proj = glGetDoublev(GL_PROJECTION_MATRIX)
self.unProj_view = glGetIntegerv(GL_VIEWPORT)
p1 = gluUnProject( (x, y, 0.), self.unProj_model, self.unProj_proj,
self.unProj_view)
p2 = gluUnProject( (x, y, 1.), self.unProj_model, self.unProj_proj,
self.unProj_view)
glLoadIdentity()
if selectHits:
if mode == 'pick':
pick = self.handlePick(selectHits, selectBuf, type)
else:
pick = self.handleDragSelect(selectHits, selectBuf, type)
else:
pick = PickObject('pick', self)
## if selectHits and self.viewer.showPickedVertex:
## self.DrawPickingSphere(pick)
pick.p1 = p1
pick.p2 = p2
pick.box = (x, y, x1, y1)
pick.event = event
self.viewer.lastPick = pick
#DEBUG used to debug picking
# from IndexedPolylines import IndexedPolylines
# l = IndexedPolylines('line', vertices = (self._p1,self._p2), faces=((0,1),) )
# self.viewer.AddObject(l)
# return o, parts, self.viewer.lastPickedVertex, self._p1, self._p2
return pick
# ## DEPRECATED, is not using instance for computing coordinates (MS 12/04)
# def DrawPickingSphere(self, pick):
# """display a transient sphere at picked vertex"""
# from warnings import warn
# warnings.warn('DrawPickingSphere is deprecated',
# DeprecationWarning, stacklevel=2)
#
# obj = pick.hits.keys()[0]
# varray = obj.vertexSet.vertices.array
# coords = Numeric.take( varray, pick.hits[obj] )
# p = self.viewer.pickVerticesSpheres
# mat = obj.GetMatrix( obj.LastParentBeforeRoot() )
# mat = Numeric.transpose(mat)
# p.Matrix = Numeric.reshape(mat, (16, ))
# p.SetMatrix(mat)
# self.viewer.pickVerticesSpheres.Set(vertices=coords,
# transient=self.viewer.pickReminiscence,
# redo=redo)
# self.Redraw()
def xyzFromPixel( self, winx, winy):
"""compute x, and y values in scene from x and y corrdinates in event
find z from Zbuffer.
pt3d, background = xyzFromPixel( self, winx, winy)
background is True if pick occured on background"""
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# unproject pixel
self.tk.call(self._w, 'makecurrent')
glPushMatrix()
self.BuildTransformation() # camera transformation
nar = Numeric.zeros(1, 'f')
glFinish()
from opengltk.extent import _gllib as gllib
gllib.glReadPixels( winx, winy, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT,
nar)
winz = float(nar[0])
background = winz == 1.0
#print 'xyzFromPixel: picks',winz, background
#print "winx, winy, winz", winx, winy, winz
l3dPoint = gluUnProject( (winx, winy, winz),
glGetDoublev(GL_MODELVIEW_MATRIX),
glGetDoublev(GL_PROJECTION_MATRIX),
glGetIntegerv(GL_VIEWPORT)
)
#print "l3dPoint", l3dPoint
glPopMatrix()
return l3dPoint, background
def handleDragSelect(self, selectHits, selectBuf, type):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
pick = PickObject('drag select', self, type)
p = 0
for i in range(selectHits):
nb_names = selectBuf[p]
z1 = float(selectBuf[p+1]) #/ 0x7fffffff
end = int(p+3+nb_names)
instance = list(selectBuf[p+3:end-2])
obj = self.objPick[int(selectBuf[end-2])]
vertex = selectBuf[end-1]
#print 'vertex', vertex, obj.name, instance
pick.add(object=obj, vertex=vertex, instance=instance)
p = end
return pick
def handlePick(self, selectHits, selectBuf, type):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""We are looking for the vertex closest to the viewer"""
# now handle selection
mini = 9999999999.9
p = 0
vertex = None
obj = None
# loop over hits. selectBuf contains for each hit:
# - number of names for that hit (num)
# - z1
# - z2
# - instNumRoot, instNumRootParent_1, instNumRootParent_2, ... ,
# geomIndex, vertexNum
# For each parent we have an instance number
# the geomIndex is the index of the geometry in self.objPick
# vertexNum is the index of the vertex in the geometry's vertexSet
#
pick = PickObject('pick', self, type)
for i in range(selectHits):
nb_names = selectBuf[p]
z1 = float(selectBuf[p+1]) #/ 0x7fffffff
# compute the end of the pick info for this hit
end = int(p+3+nb_names)
#print 'vertex', selectBuf[end-1], self.objPick[selectBuf[end-2]], list(selectBuf[p+3:end-2]), z1
if z1 < mini:
#end = p+3+nb_names
mini = z1
instance = list(selectBuf[p+3:end-2])
obj = self.objPick[int(selectBuf[end-2])]
vertex = selectBuf[end-1]
# advance p to begin of next pick hit data
p = end
pick.add( object=obj, vertex=vertex, instance=instance )
return pick
def drawOneObjectPick(self, obj, type):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
lIsInstanceTransformable = isinstance(obj, Transformable)
if lIsInstanceTransformable:
self.ActivateClipPlanes( obj.clipP, obj.clipSide )
if obj.scissor:
glEnable(GL_SCISSOR_TEST)
glScissor(obj.scissorX, obj.scissorY,
obj.scissorW, obj.scissorH)
obj.pickNum = self.pickNum
self.objPick.append(obj)
inst = 0
if lIsInstanceTransformable and type=='vertices':
#print 'using vertices', obj.name
v = obj.vertexSet.vertices.array
v = Numeric.reshape(v, (-1,3)).astype('f')
for m in obj.instanceMatricesFortran:
glPushName(inst) # instance number
inst = inst + 1
glPushName(self.pickNum) # index into self.objPick
glPushMatrix()
glMultMatrixf(m)
if lIsInstanceTransformable:
if type=='vertices':
#print 'using vertices', obj.name
v = obj.vertexSet.vertices.array
if len(v.shape) >2 or v.dtype.char!='f':
v = Numeric.reshape(v, (-1,3)).astype('f')
if len(v) >0:
#t1 = time()
namedPoints(len(v), v)
#print 'draw points:', time()-t1
## i = 0
## for p in v:
## glPushName(i)
## glBegin(GL_POINTS)
## glVertex3f(p[0], p[1], p[2])
## glEnd()
## glPopName()
## i = i + 1
# can't be used since we cannot push and pop names
## glVertexPointer(2, GL_FLOAT, 0, v)
## glEnableClientState(GL_VERTEX_ARRAY)
## glDrawArrays(GL_POINTS, 0, len(v) )
## glDisableClientState(GL_VERTEX_ARRAY)
elif type=='parts':
if obj.pickDpyList:
#print "pick displayFunction"
currentcontext = self.viewer.currentCamera.tk.call(self.viewer.currentCamera._w, 'contexttag')
if currentcontext != obj.pickDpyList[1]:
warnings.warn("""DisplayFunction failed because the current context is the wrong one""")
#print "currentcontext != obj.pickDpyList[1]", currentcontext, obj.pickDpyList[1]
else:
print '#%d'%obj.pickDpyList[0], currentcontext, "glCallList Camera"
glCallList(obj.pickDpyList[0])
else:
#print "displayFunction"
obj.DisplayFunction()
else:
print 'Error: bad type for PickRedraw: ',type
else: #Insert2d
obj.pickDraw()
glPopMatrix()
glPopName() # instance number
glPopName() # index into self.objPick
self.pickNum = self.pickNum + 1
if lIsInstanceTransformable:
for c in obj.clipP: # disable object's clip planes
c._Disable()
if obj.scissor:
glDisable(GL_SCISSOR_TEST)
def DrawObjPick(self, obj, type):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""draws an object for picking purposes. If type is 'vertices' a
display list for vertices identification is used. If type is parts
a display list identifying geometric primitives such as triangles or
lines is used"""
lIsInstanceTransformable = isinstance(obj, Transformable)
if lIsInstanceTransformable:
glPushMatrix()
obj.MakeMat()
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
inst = 0
for m in obj.instanceMatricesFortran:
glPushName(inst) # instance number
glPushMatrix()
glMultMatrixf(m)
for child in obj.children:
if child.visible:
self.DrawObjPick(child, type)
glPopMatrix()
glPopName() # instance number
inst = inst + 1
if obj.pickable:
self.drawOneObjectPick(obj, type)
if lIsInstanceTransformable:
for c in obj.clipPI: # disable object's clip planes that are
c._Disable() # inherited by children
glPopMatrix() # Restore the matrix
def RedrawPick(self, type):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.pickNum = 0
self.objPick = [ ]
glClear(GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glPointSize(1.0)
self.BuildTransformation() # camera transformation
obj = self.viewer.rootObject
obj.MakeMat()
if len(obj.clipPI):
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
inst = 0
for m in obj.instanceMatricesFortran:
glLoadName(inst)
glPushMatrix()
glMultMatrixf(m)
for child in obj.children:
if child.visible:
self.DrawObjPick(child, type)
glPopMatrix()
inst = inst + 1
for c in obj.clipPI: c._Disable()
glPopMatrix()
def drawRect(self, P1, P2, P3, P4, fill=0):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if fill: prim=GL_POLYGON
else: prim=GL_LINE_STRIP
glBegin(prim)
glVertex3f( float(P1[0]), float(P1[1]), float(P1[2]) )
glVertex3f( float(P2[0]), float(P2[1]), float(P2[2]) )
glVertex3f( float(P3[0]), float(P3[1]), float(P3[2]) )
glVertex3f( float(P4[0]), float(P4[1]), float(P4[2] ))
glVertex3f( float(P1[0]), float(P1[1]), float(P1[2] ))
glEnd()
def Insert2dPickingCallBack(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# this shoudn't be necessary but somewhere/sometimes the
# current object is set without a call to SetCurrentObject
# So self.viewer.currentCamera.bindAllActions('Insert2d') is no set
if isinstance(self.viewer.currentObject, Insert2d) is False:
assert isinstance(self.viewer.currentObject, Transformable), self.viewer.currentObject
self.viewer.SetCurrentObject(self.viewer.currentObject)
return
self.viewer.currentObject.respondToMouseMove(event)
def SetInsert2dPicking(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
num = str(self.findButton('picking', 'Insert2d')[0])
ehm = self.eventManager
for mod in self.mouseButtonModifiers:
if mod == 'None':
mod = ''
else:
mod = mod + '-'
ev = '<' + mod + 'B' + num + '-Motion>'
#print "ev", ev
ehm.AddCallback(ev, self.Insert2dPickingCallBack )
pick = self.DoPick(event.x, event.y, event=event)
#if pick and len(pick.hits):
self.viewer.processPicking(pick)
def initSelectionRectangle(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if isinstance(self.viewer.currentObject, Insert2d):
return
if self.stereoMode != 'MONO':
return
self.selectDragRect = 1
self.afid=None
self.fill=0
self.tk.call(self._w, 'makecurrent')
glPushMatrix()
self.BuildTransformation() # camera transformation
glDrawBuffer(GL_FRONT)
# glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
# glDisable(GL_CULL_FACE)
glLineWidth( 1.0 )
glDisable( GL_LIGHTING )
glColor3f( float(self.selectionColor[0]), float(self.selectionColor[1]),
float(self.selectionColor[2]) )
glDisable(GL_DEPTH_TEST)
glEnable(GL_COLOR_LOGIC_OP)
glLogicOp(GL_XOR)
x2 = self._x1 = event.x
y2 = self._y1 = self.height - event.y
self.unProj_model = glGetDoublev(GL_MODELVIEW_MATRIX)
self.unProj_proj = glGetDoublev(GL_PROJECTION_MATRIX)
self.unProj_view = glGetIntegerv(GL_VIEWPORT)
from opengltk.extent import _glulib as glulib
self._P1 = gluUnProject( (self._x1, self._y1, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view )
self._P2 = gluUnProject( (self._x1, y2, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view )
self._P3 = gluUnProject( (x2, y2, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view )
self._P4 = gluUnProject( (x2, self._y1, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view )
# draw first rectangle
#self.history = [ ('draw', self._P3) ]
self.drawRect( self._P1, self._P2, self._P3, self._P4 )
glPopMatrix()
# set "<ButtonMotion-1>" to call draw selection rectangle
# add un-drawing of last selection rectangle and call functions
ehm = self.eventManager
num = str(event.num)#str(self.findButton('picking', 'Object')[0])
for mod in self.mouseButtonModifiers:
if mod=='None': mod=''
else: mod=mod+'-'
ev = '<'+mod+'B'+num+'-Motion>'
ehm.AddCallback(ev, self.drawSelectionRectangle )
ehm.AddCallback("<"+mod+"ButtonRelease-"+num+">",
self.endSelectionRectangle )
def drawSelectionRectangle(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if not self.selectDragRect: return
self.tk.call(self._w, 'makecurrent')
glPushMatrix()
self.BuildTransformation() # camera transformation
#print 'AAAAAAAAAAA2 drawSelectionRectangle'
# draw over previous rectangle
#self.history.append( ('hide', self._P3) )
glDisable(GL_DEPTH_TEST)
if self.fill:
self.drawRect( self._P1, self._P2, self._P3, self._P4, 1 )
self.fill = 0
else:
self.drawRect( self._P1, self._P2, self._P3, self._P4, 0 )
# draw new rectangle
x2 = event.x
y2 = self.height - event.y
self.unProj_model = glGetDoublev(GL_MODELVIEW_MATRIX)
self._P2 = gluUnProject( (self._x1, y2, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view)
self._P3 = gluUnProject( (x2, y2, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view)
self._P4 = gluUnProject( (x2, self._y1, 0.5),
self.unProj_model, self.unProj_proj,
self.unProj_view)
#self.history.append( ('draw', self._P3) )
self.drawRect( self._P1, self._P2, self._P3, self._P4, self.fill )
glPopMatrix()
glFlush()
if self.fillSelectionBox:
if self.afid:
self.after_cancel(self.afid)
self.afid = self.after(self.fillDelay, self.DrawFilledSelectionBox)
def DrawFilledSelectionBox(self, event=None):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.fill = 1
self.tk.call(self._w, 'makecurrent')
glPushMatrix()
self.BuildTransformation() # camera transformation
# draw over previous rectangle
self.drawRect( self._P1, self._P2, self._P3, self._P4, 0 )
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glDisable(GL_CULL_FACE)
glColor3f( float(self.selectionColor[0]), float(self.selectionColor[1]),
float(self.selectionColor[2] ))
self.drawRect( self._P1, self._P2, self._P3, self._P4, 1 )
glFlush()
glPopMatrix()
def endSelectionRectangle(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#print "Camera.endSelectionRectangle"
if not self.selectDragRect: return
if self.afid:
self.after_cancel(self.afid)
# remove "<Any-ButtonMotion-1>" to call draw selection rectangle
# remove un-drawing of last selection rectangle and call functions
ehm = self.eventManager
num = str(event.num)#str(self.findButton('picking', 'Object')[0])
for mod in self.mouseButtonModifiers:
if mod=='None': mod=''
else: mod=mod+'-'
ev = '<'+mod+'B'+num+'-Motion>'
ehm.RemoveCallback(ev, self.drawSelectionRectangle )
ehm.RemoveCallback("<"+mod+"ButtonRelease-"+num+">",
self.endSelectionRectangle )
self.selectDragRect = 0
self.tk.call(self._w, 'makecurrent')
glPushMatrix()
self.BuildTransformation() # camera transformation
# this line is required for last rectangle to disappear !
# not sure why
# oct 2001: apparently not necessary
#glEnable(GL_COLOR_LOGIC_OP)
#self.history.append( ('hide', self._P3) )
self.drawRect( self._P1, self._P2, self._P3, self._P4 )
#self.drawRect( self._P1, self._P2, self._P3, self._P4 )
glPopMatrix()
glEnable(GL_DEPTH_TEST)
glDisable(GL_COLOR_LOGIC_OP)
#glEnable(GL_LIGHTING)
if self.viewer is not None:
self.viewer.enableOpenglLighting()
glDrawBuffer(GL_BACK)
pick = self.DoPick(event.x, event.y, self._x1, self.height-self._y1,
event=event)
del self._x1
del self._y1
del self._P1
del self._P2
del self._P3
del self._P4
if self.viewer and len(pick.hits):
self.viewer.processPicking(pick)
#print "len(pick.hits)", len(pick.hits)
def SelectCamera(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""First pick in a non current camera selects it"""
curCam = self.viewer.currentCamera
if curCam == self: return 0
curCam.frame.config( background = self.defFrameBack )
self.frame.config( background = "#900000" )
if self.viewer:
self.viewer.currentCamera = self
self.viewer.BindTrackballToObject(self.viewer.currentObject)
self.SetupProjectionMatrix()
return 1
def DoubleSelectPick_cb(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Handle a double pick event in this camera"""
self.DoPick(event.x, event.y, event=event)
self.viewer.BindTrackballToObject(self.viewer.rootObject)
## DEPRECATED, is not using instance for computing coordinates
def CenterPick_cb(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Handle a pick event. Center the cur. object on the picked vertex"""
from warnings import warn
warnings.warn('CenterPick_cbg is deprecated',
DeprecationWarning, stacklevel=2)
pick = self.DoPick(event.x, event.y, event=event)
if len(pick.hits)==0: return
g = Numeric.zeros( (3), 'f' )
object = self.viewer.currentObject
inv = object.GetMatrixInverse()
for obj, vertInd in pick.hits.items():
if len(vertInd)==0:
print 'WARNING: object',obj.name,' is not vertex pickable'
else:
m = Numeric.dot( inv, obj.GetMatrix() )
vert = obj.vertexSet.vertices * m
vertsel = Numeric.take( vert, vertInd )
g = g + Numeric.sum(vertsel)/len(vertsel)
object.SetPivot( g )
## varray = obj.vertexSet.vertices.array
## vert = Numeric.take( varray, vertInd )
## vert = Numeric.concatenate( vert, Numeric.ones( (1,len(vert))), 1)
## vert = Numeric.dot(m, vert)
## obj.SetPivot( (Numeric.sum(vert)/len(vert))[:3] )
## obj.SetPivot( self.viewer.lastPickedVertex[1] )
def TransfCamera_cb(self, event):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.viewer.BindTrackballToCamera(self.viewer.currentCamera)
def ActivateClipPlanes(self, cplist, cpside):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""activate a list of clipping planes"""
if len(cplist)==0: return
glPushMatrix()
glLoadIdentity()
glMultMatrixf(self.rootObjectTransformation)
glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT |
GL_LINE_BIT)
glDisable (GL_LIGHTING)
for c in cplist: # display them
if c.visible:
# if we push a name here we won't know how many values
# to skip in handlePick after z1 and z2
#if self.renderMode == GL_SELECT:
# c.pickNum = self.pickNum
# self.objPick.append(c)
# self.pickNum = self.pickNum + 1
# glLoadName(c.pickNum)
c.DisplayFunction()
glPopAttrib()
for c in cplist: # enable them
c._Enable(cpside[c.num])
glPopMatrix();
def DrawAllDirectionalLights(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Draw all directional lights"""
glDisable (GL_LIGHTING)
for l in self.viewer.lights:
if l.positional is True or l.visible in (False,0):
continue
if self.renderMode == GL_SELECT:
l.pickNum = self.pickNum
self.objPick.append(l)
self.pickNum = self.pickNum + 1
glLoadName(l.pickNum)
l.DrawDirectionalLight(self)
def drawWithCap(self, obj):
MY_CLIP_PLANE = obj.cap
# compute clip plane number
cpn = MY_CLIP_PLANE - GL.GL_CLIP_PLANE0
#GL.glPushAttrib(GL.GL_ENABLE_BIT | GL.GL_STENCIL_BUFFER_BIT |
# GL.GL_POLYGON_BIT | GL_CURRENT_BIT)
##
## SINGLE PASS
##
## GL.glDepthMask(0)
## GL.glColorMask(0,0,0,0)
## GL.glDisable(GL_CULL_FACE)
## GL.glEnable(GL.GL_STENCIL_TEST)
## GL.glEnable(GL.GL_STENCIL_TEST_TWO_SIDE_EXT)
## GL.glActiveStencilFaceEXT(GL.GL_BACK)
## GL.glStencilOp(GL.GL_KEEP, # stencil test fail
## GL.GL_KEEP, # depth test fail
## GL.GL_DECR_WRAP_EXT) # depth test pass
## GL.glStencilMask(~0)
## GL.glStencilFunc(GL_ALWAYS, 0, ~0)
## GL.glActiveStencilFaceEXT(GL.GL_FRONT)
## GL.glStencilOp(GL.GL.GL_KEEP, # stencil test fail
## GL.GL.GL_KEEP, # depth test fail
## GL.GL.GL_INCR_WRAP_EXT); # depth test pass
## GL.glStencilMask(~0)
## GL.glStencilFunc(GL.GL_ALWAYS, 0, ~0)
## obj.Draw()
## 2 passes version
GL.glEnable(GL.GL_CULL_FACE)
GL.glEnable(GL.GL_STENCIL_TEST)
glStencilMask(1)
GL.glEnable(GL.GL_DEPTH_TEST)
#GL.glDisable(GL.GL_DEPTH_TEST)
GL.glClear(GL.GL_STENCIL_BUFFER_BIT)
GL.glColorMask(GL.GL_FALSE, GL.GL_FALSE, GL.GL_FALSE, GL.GL_FALSE)
# first pass: increment stencil buffer value on back faces
GL.glStencilFunc(GL.GL_ALWAYS, 0, 0)
GL.glStencilOp(GL.GL_KEEP, GL.GL_KEEP, GL.GL_INCR)
GL.glPolygonMode(GL.GL_BACK, GL.GL_FILL)
GL.glCullFace(GL.GL_FRONT) # render back faces only
obj.Draw()
# second pass: decrement stencil buffer value on front faces
GL.glStencilOp(GL.GL_KEEP, GL.GL_KEEP, GL.GL_DECR)
GL.glPolygonMode(GL.GL_FRONT, GL.GL_FILL)
GL.glCullFace(GL.GL_BACK) # render front faces only
obj.Draw()
# FIXME this can create problems whent there are multiple geoms
GL.glClear(GL_DEPTH_BUFFER_BIT)
# drawing clip planes masked by stencil buffer content
#_gllib.glBindTexture(GL_TEXTURE_2D, 0)
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glColorMask(GL.GL_TRUE, GL.GL_TRUE, GL.GL_TRUE, GL.GL_TRUE)
GL.glDisable(MY_CLIP_PLANE)
GL.glDisable(GL.GL_CULL_FACE)
#GL.glStencilFunc(GL.GL_ALWAYS, 0, 1)
#GL.glStencilFunc(GL.GL_LESS, 0, 1)
#GL.glStencilFunc(GL.GL_NOTEQUAL, 0, 1)
GL.glStencilFunc(GL.GL_NOTEQUAL, 0, 1)
GL.glMaterialfv( GL.GL_FRONT, GL.GL_DIFFUSE, obj.capFrontColor)
GL.glMaterialfv( GL.GL_BACK, GL.GL_DIFFUSE, obj.capBackColor)
GL.glBegin(GL.GL_QUADS) #rendering the plane quad. Note, it should be
#big enough to cover all clip edge area.
GL.glNormal3fv( (1, 0, 0))
if obj.clipSide[cpn]==-1:
pts = [(0, 9999, -9999), (0, 9999, 9999),
(0, -9999, 9999), (0, -9999, -9999) ]
else:
pts = [ (0, -9999, -9999), (0, -9999, 9999),
(0, 9999, 9999), (0, 9999, -9999) ]
cp = self.viewer.clipP[cpn]
xpts = self.transformPoints(cp.translation, cp.rotation, pts)
#GL.glDrawBuffer(GL.GL_FRONT)
for p in xpts:
GL.glVertex3fv( p )
GL.glEnd()
#****** Rendering object *********
#GL.glPopAttrib()
GL.glDisable(GL.GL_STENCIL_TEST)
GL.glClear(GL_STENCIL_BUFFER_BIT)
GL.glEnable(MY_CLIP_PLANE) # enabling clip plane again
obj.SetupGL()
obj.Draw()
GL.glStencilFunc(GL.GL_ALWAYS, 0, 0)
glStencilMask(0)
def transformPoints(self, trans, rot, points):
tx,ty,tz = trans
pos = []
for xs,ys,zs in points:
x = rot[0]*xs + rot[4]*ys + rot[8]*zs + tx
y = rot[1]*xs + rot[5]*ys + rot[9]*zs + ty
z = rot[2]*xs + rot[6]*ys + rot[10]*zs + tz
pos.append( [x,y,z] )
return pos
def DrawOneObject(self, obj):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""set up clipping planes, activate scissors and call display function
for all instances of obj
"""
#print "Camera.DrawOneObject", obj
lIsInstancetransformable = isinstance(obj, Transformable)
if lIsInstancetransformable:
self.ActivateClipPlanes( obj.clipP, obj.clipSide )
if obj.scissor:
glDisable(GL_LIGHTING)
lViewport = glGetIntegerv(GL_VIEWPORT)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPushMatrix()
GL.glLoadIdentity()
GL.glOrtho(float(lViewport[0]),
float(lViewport[2]),
float(lViewport[1]),
float(lViewport[3]),
-1, 1)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPushMatrix()
GL.glLoadIdentity()
glEnable(GL_COLOR_LOGIC_OP)
glLogicOp(GL_XOR)
glBegin(GL_LINE_STRIP)
glVertex2f( float(obj.scissorX), float(obj.scissorY ))
glVertex2f( float(obj.scissorX+obj.scissorW), float(obj.scissorY ))
glVertex2f( float(obj.scissorX+obj.scissorW), float(obj.scissorY+obj.scissorH))
glVertex2f( float(obj.scissorX), float(obj.scissorY+obj.scissorH ))
glVertex2f( float(obj.scissorX), float(obj.scissorY ))
glEnd()
glDisable(GL_COLOR_LOGIC_OP)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPopMatrix()
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPopMatrix()
glEnable(GL_SCISSOR_TEST)
glScissor(obj.scissorX, obj.scissorY, obj.scissorW, obj.scissorH)
#glEnable(GL_LIGHTING)
if self.viewer is not None:
self.viewer.enableOpenglLighting()
if obj.drawBB: obj.DrawBoundingBox()
# hack to fix this inheritence problem without slowing down
# the "many object case (see Expensive inheritence pb above)
# MS oct 11 2001. removed this code since obj.shadModel is set to
# the proper value when it is inherited (see RenderMode()) and
# shading is called by SetupGL for each object
#if not obj.inheritShading and \
# obj.shading != GL_NONE:
# glShadeModel(obj.shading)
if (lIsInstancetransformable and obj.drawBB != viewerConst.ONLY) \
or isinstance(obj, Insert2d):
if lIsInstancetransformable and obj.texture:
glActiveTexture(GL_TEXTURE0)
_gllib.glBindTexture(GL_TEXTURE_2D, 0)
obj.texture.Setup()
if lIsInstancetransformable and obj.invertNormals is True \
and isinstance(obj, Ellipsoids) is False \
and isinstance(obj, Cylinders) is False \
and (isinstance(obj, Spheres) is True and DejaVu.enableVertexArray is True):
lCwIsOn = True
GL.glFrontFace(GL.GL_CW)
#print "GL.glGetIntegerv(GL.GL_FRONT_FACE)",GL.glGetIntegerv(GL.GL_FRONT_FACE)
else:
lCwIsOn = False
mi = 0
for m in obj.instanceMatricesFortran:
if lIsInstancetransformable and not obj.inheritMaterial:
obj.InitMaterial(mi)
obj.InitColor(mi)
mi = mi + 1
glPushMatrix()
glMultMatrixf(m)
if obj.immediateRendering or \
(self.viewer.tileRender and obj.needsRedoDpyListOnResize):
if hasattr(obj, "cap") and obj.cap:
self.drawWithCap(obj)
else:
obj.Draw()
#obj.Draw()
elif self.viewer.singleDpyList:
obj.Draw()
else:
obj.DisplayFunction()
glPopMatrix()
if lCwIsOn is True:
GL.glFrontFace(GL.GL_CCW)
#print obj.name, self.glError()
if lIsInstancetransformable and obj.texture:
glActiveTexture(GL_TEXTURE0);
_gllib.glBindTexture(GL_TEXTURE_2D, 0)
glDisable(obj.texture.dim)
if lIsInstancetransformable:
for c in obj.clipP: # disable object's clip planes
c._Disable()
if obj.scissor:
glDisable(GL_SCISSOR_TEST)
def Draw(self, obj, pushAttrib=True):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Draw obj and subtree below it
"""
#print "Camera.Draw", obj
assert obj.viewer is not None
# if object is not visible, all subtree is hidden --> we can return
if obj.getVisible() in [False, 0]: #not obj.visible:
return
if self.drawMode & 5: # immediateRendring draw mode
if obj.immediateRendering:
pass
elif (self.viewer.tileRender and obj.needsRedoDpyListOnResize):
pass
else:
return
glPushMatrix() # Protect our matrix
lIsInstanceTransformable = isinstance(obj, Transformable)
if lIsInstanceTransformable:
if not obj.inheritXform:
glPushMatrix()
glLoadIdentity()
glMultMatrixf(self.beforeRootTransformation)
obj.MakeMat()
# VERY expensive and I am not sure what I need it for
if pushAttrib:
glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT
| GL_POLYGON_BIT)
glDisable(GL_LIGHTING)
# required for the transparent box of AutoGrid not to affect the molecule's
# color binding. The box is FLAT shaded and this shade models gets propagated
# to the molecule preventing color interpolation over bonds.
# This shows that thi models of inheritence has serious limitations :(
# gl.glPushAttrib(GL_LIGHTING_BIT)
if lIsInstanceTransformable:
obj.SetupGL() # setup GL properties the can be inherited
# enable and display object's clipping planes that also
# clip its children
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
if obj.scissor:
glEnable(GL_SCISSOR_TEST)
glScissor(obj.scissorX, obj.scissorY, obj.scissorW, obj.scissorH)
if self.drawMode == 2:
# recusive call for children
# for o in obj.children: self.Draw(o)
mi = 0
for m in obj.instanceMatricesFortran:
if lIsInstanceTransformable and not obj.inheritMaterial:
obj.InitMaterial(mi)
obj.InitColor(mi)
mi = mi + 1
glPushMatrix()
glMultMatrixf(m)
map ( self.Draw, obj.children)
glPopMatrix()
# Should be done in a function to setup GL properties that cannot
# be inherited
# should actually only be done once since all transparent objects
# have to be drawn after all opaque objects for this to work
draw = 1
transp = obj.transparent #obj.isTransparent()
if obj.immediateRendering or \
(self.viewer.tileRender and obj.needsRedoDpyListOnResize):
if transp:
if not self.drawMode & 4: # only render if immediate & transp
draw = 0
else:
if not self.drawMode & 1: # only render if immediate & opaque
draw = 0
## if draw==1:
## print 'drawing immediate opaque object'
if draw and obj.visible:
if transp:
if self.drawTransparentObjects:
glEnable(GL_BLEND)
if not obj.getDepthMask():
glDepthMask(GL_FALSE)
glBlendFunc(obj.srcBlendFunc, obj.dstBlendFunc)
self.DrawOneObject(obj)
glDisable(GL_BLEND)
glDepthMask(GL_TRUE)
else:
self.hasTransparentObjects = 1
else: # was: elif not self.drawTransparentObjects:
self.DrawOneObject(obj)
# VERY Expensif
if pushAttrib:
glPopAttrib()
if lIsInstanceTransformable:
for c in obj.clipPI: # disable object's clip planes that are
c._Disable() # inherited by children
if obj.scissor:
glDisable(GL_SCISSOR_TEST)
if not obj.inheritXform:
glPopMatrix()
glPopMatrix() # Restore the matrix
def RedrawObjectHierarchy(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
glPushMatrix()
# setup GL state for root object
obj = self.viewer.rootObject
if self.drawBB: obj.DrawTreeBoundingBox()
if self.drawBB != viewerConst.ONLY:
# save the transformation before the root object
# used by some object who do not want to inherit transform
m = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
self.beforeRootTransformation = Numeric.reshape( m, (16,) )
obj.MakeMat() # root object transformation
# mod_opengltk
#m = glGetDoublev(GL_MODELVIEW_MATRIX).astype('f')
m = Numeric.array(glGetDoublev(GL_MODELVIEW_MATRIX)).astype('f')
self.rootObjectTransformation = Numeric.reshape( m, (16,) )
# no reason to push and pop attribute of root object
# glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT |
# GL_POLYGON_BIT)
#obj.InitColor() # init GL for color with ROOT color
#obj.InitMaterial() # init GL for material with ROOT material
obj.SetupGL() # setup GL with ROOT properties
if len(obj.clipPI):
self.ActivateClipPlanes( obj.clipPI, obj.clipSide )
# draw all object that do not want a display List
#print "self.viewer.noDpyListOpaque", self.viewer.noDpyListOpaque
if len(self.viewer.noDpyListOpaque):
self.drawMode = 1 # no dispaly list Opaque
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
#map( self.Draw, obj.children)
map( self.Draw, self.viewer.noDpyListOpaque )
glPopMatrix()
# for "Continuity" (ucsd - nbcr) as we don't have vertexArrays yet
if hasattr(self, 'vertexArrayCallback'):
self.vertexArrayCallback()
# when redraw is triggered by pick event self.viewer has been set
# to None
if self.dpyList and self.viewer.useMasterDpyList:
#print 'calling master list'
currentcontext = self.tk.call(self._w, 'contexttag')
if currentcontext != self.dpyList[1]:
warnings.warn("""RedrawObjectHierarchy failed because the current context is the wrong one""")
#print "currentcontext != self.viewer.dpyList[1]", currentcontext, self.viewer.dpyList[1]
else:
#print '#%d'%self.dpyList[0], currentcontext, "glCallList Camera2"
glCallList(self.dpyList[0])
else:
#print 'rebuilding master list'
if self.viewer.useMasterDpyList:
lNewList = glGenLists(1)
#lNewList = self.newList
lContext = self.tk.call(
self._w,
'contexttag' )
#print "lNewList StandardCamera.RedrawObjectHierarchy", lNewList, lContext, self.name
self.dpyList = (
lNewList,
lContext
)
glNewList(self.dpyList[0], GL_COMPILE)
#print '+%d'%self.dpyList[0], lContext, "glNewList Camera"
# call for each subtree with root in obj.children
# for o in obj.children: self.Draw(o)
self.drawMode = 2
self.drawTransparentObjects = 0
self.hasTransparentObjects = 0
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
map( self.Draw, obj.children)
glPopMatrix()
if self.hasTransparentObjects:
self.drawTransparentObjects = 1
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
map( self.Draw, obj.children)
glPopMatrix()
if self.viewer.useMasterDpyList:
#print '*%d'%GL.glGetIntegerv(GL.GL_LIST_INDEX), "glEndList Camera"
glEndList()
#print "self.viewer.dpyList", self.viewer.dpyList
if self.dpyList:
currentcontext = self.tk.call(self._w, 'contexttag')
if currentcontext != self.dpyList[1]:
warnings.warn("""RedrawObjectHierarchy failed because the current context is the wrong one""")
#print "currentcontext != self.viewer.dpyList[1]", currentcontext, self.viewer.dpyList[1]
else:
#print '#%d'%self.dpyList[0], currentcontext, "glCallList Camera3"
glCallList(self.dpyList[0])
# draw all object that do not want a display List
#print "self.viewer.noDpyListTransp", self.viewer.noDpyListTransp
if len(self.viewer.noDpyListTransp):
self.drawTransparentObjects = 1
self.drawMode = 4
for m in obj.instanceMatricesFortran:
glPushMatrix()
glMultMatrixf(m)
#map( self.Draw, obj.children)
map( self.Draw, self.viewer.noDpyListTransp )
glPopMatrix()
self.drawTransparentObjects = 0
## glPopAttrib()
for c in obj.clipPI:
c._Disable()
glPopMatrix()
def _RedrawCamera(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Actual drawing of lights, clipping planes and objects
"""
if self.stereoMode.startswith('SIDE_BY_SIDE'):
if self.viewer.tileRender:
glPushMatrix()
# setup GL state for camera
self.BuildTransformation() # camera transformation
self.SetupLights()
self.DrawAllDirectionalLights()
if self.imageRendered == 'RIGHT_EYE':
glTranslatef( float(-self.sideBySideTranslation), 0, 0 )
glRotatef( float(-self.sideBySideRotAngle), 0., 1., 0.)
elif self.imageRendered == 'LEFT_EYE':
glTranslatef( float(self.sideBySideTranslation), 0, 0 )
glRotatef( float(self.sideBySideRotAngle), 0., 1., 0.)
else:
assert False, 'self.imageRendered is not set correctly'
glViewport(0, 0, int(self.width), int(self.height))
glScalef( 1., 0.5, 1.)
self.RedrawObjectHierarchy()
glPopMatrix()
elif self.stereoMode.endswith('_CROSS'):
halfWidth = self.width/2
# setup GL state for camera
glPushMatrix()
self.BuildTransformation() # camera transformation
self.SetupLights() # set GL lights; moved from Light object to here
self.DrawAllDirectionalLights()
# render image for right eye
self.imageRendered = 'RIGHT_EYE'
glPushMatrix()
glTranslatef( float(-self.sideBySideTranslation), 0, 0 )
glRotatef( float(-self.sideBySideRotAngle), 0., 1., 0.)
glViewport(0, 0, int(halfWidth), int(self.height) )
glScalef( 1., 0.5, 1.)
self.RedrawObjectHierarchy()
glPopMatrix()
# render image for left eye
self.imageRendered = 'LEFT_EYE'
glPushMatrix()
glTranslatef( float(self.sideBySideTranslation), 0, 0 )
glRotatef( float(self.sideBySideRotAngle), 0., 1., 0.)
glScalef( 1., 0.5, 1.)
glViewport(int(halfWidth), 0, int(halfWidth), int(self.height))
self.RedrawObjectHierarchy()
glPopMatrix()
glPopMatrix()
glViewport(0, 0, int(self.width), int(self.height))
elif self.stereoMode.endswith('_STRAIGHT'):
halfWidth = self.width/2
# setup GL state for camera
glPushMatrix()
self.BuildTransformation() # camera transformation
self.SetupLights() # set GL lights; moved from Light object to here
self.DrawAllDirectionalLights()
# render image for left eye
self.imageRendered = 'LEFT_EYE'
glPushMatrix()
glTranslatef( float(self.sideBySideTranslation), 0, 0 )
glRotatef( float(self.sideBySideRotAngle), 0., 1., 0.)
glScalef( 1., 0.5, 1.)
glViewport(0, 0, halfWidth, self.height)
self.RedrawObjectHierarchy()
glPopMatrix()
# render image for right eye
self.imageRendered = 'RIGHT_EYE'
glPushMatrix()
glTranslatef( float(-self.sideBySideTranslation), 0, 0 )
glRotatef( float(-self.sideBySideRotAngle), 0., 1., 0.)
glViewport(int(halfWidth), 0, int(halfWidth), int(self.height))
glScalef( 1., 0.5, 1.)
self.RedrawObjectHierarchy()
glPopMatrix()
glPopMatrix()
glViewport(0, 0, self.width, self.height)
elif self.stereoMode.startswith('COLOR_SEPARATION'):
if self.stereoMode.endswith('_RED_BLUE'):
left = (GL_TRUE, GL_FALSE, GL_FALSE)
right = (GL_FALSE, GL_FALSE, GL_TRUE)
elif self.stereoMode.endswith('_BLUE_RED'):
left = (GL_FALSE, GL_FALSE, GL_TRUE)
right = (GL_TRUE, GL_FALSE, GL_FALSE)
elif self.stereoMode.endswith('_RED_GREEN'):
left = (GL_TRUE, GL_FALSE, GL_FALSE)
right = (GL_FALSE, GL_TRUE, GL_FALSE)
elif self.stereoMode.endswith('_GREEN_RED'):
left = (GL_FALSE, GL_TRUE, GL_FALSE)
right = (GL_TRUE, GL_FALSE, GL_FALSE)
elif self.stereoMode.endswith('_RED_GREENBLUE'):
left = (GL_TRUE, GL_FALSE, GL_FALSE)
right = (GL_FALSE, GL_TRUE, GL_TRUE)
elif self.stereoMode.endswith('_GREENBLUE_RED'):
left = (GL_FALSE, GL_TRUE, GL_TRUE)
right = (GL_TRUE, GL_FALSE, GL_FALSE)
elif self.stereoMode.endswith('_REDGREEN_BLUE'):
left = (GL_TRUE, GL_TRUE, GL_FALSE)
right = (GL_FALSE, GL_FALSE, GL_TRUE)
elif self.stereoMode.endswith('_BLUE_REDGREEN'):
left = (GL_FALSE, GL_FALSE, GL_TRUE)
right = (GL_TRUE, GL_TRUE, GL_FALSE)
glPushMatrix()
# setup GL state for camera
self.BuildTransformation() # camera transformation
self.SetupLights() # set GL lights; moved from Light object to here
self.DrawAllDirectionalLights()
# render image for left eye
self.imageRendered = 'MONO' #'LEFT_EYE'
glPushMatrix()
glTranslatef( float(self.sideBySideTranslation), 0, 0 )
glRotatef( float(self.sideBySideRotAngle), 0., 1., 0.)
glViewport(0, 0, int(self.width), int(self.height))
glColorMask(int(left[0]), int(left[1]), int(left[2]), GL_FALSE)
self.RedrawObjectHierarchy()
glPopMatrix()
self.drawHighlight()
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)
# render image for right eye
self.imageRendered = 'RIGHT_EYE'
glPushMatrix()
glTranslatef( float(-self.sideBySideTranslation), 0, 0 )
glRotatef( float(-self.sideBySideRotAngle), 0., 1., 0.)
glViewport(0, 0, int(self.width), int(self.height))
glColorMask(int(right[0]),int(right[1]),int(right[2]), GL_FALSE)
self.RedrawObjectHierarchy()
glPopMatrix()
self.drawHighlight()
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE)
glPopMatrix()
elif self.stereoMode == 'STEREO_BUFFERS':
glPushMatrix()
# setup GL state for camera
self.BuildTransformation() # camera transformation
self.SetupLights() # set GL lights; moved from Light object to here
self.DrawAllDirectionalLights()
# render image for left eye
self.imageRendered = 'LEFT_EYE'
glPushMatrix()
glTranslatef( float(self.sideBySideTranslation), 0, 0 )
glRotatef( float(self.sideBySideRotAngle), 0., 1., 0.)
glViewport(0, 0, int(self.width), int(self.height))
self.RedrawObjectHierarchy()
glPopMatrix()
self.drawHighlight()
# render image for right eye
self.imageRendered = 'RIGHT_EYE'
glDrawBuffer(GL_BACK_RIGHT)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT)
glPushMatrix()
glTranslatef( float(-self.sideBySideTranslation), 0, 0 )
glRotatef( float(-self.sideBySideRotAngle), 0., 1., 0.)
glViewport(0, 0, int(self.width), int(self.height))
self.RedrawObjectHierarchy()
glPopMatrix()
self.drawHighlight()
glPopMatrix()
glDrawBuffer(GL_BACK_LEFT)
else: # default to "Mono mode"
self.imageRendered = 'MONO'
glPushMatrix()
# setup GL state for camera
self.BuildTransformation() # camera transformation
self.SetupLights()
self.DrawAllDirectionalLights()
glViewport(0, 0, int(self.width), int(self.height))
self.RedrawObjectHierarchy()
glPopMatrix()
# def secondDerivative(self, im, width, height):
# return im.filter(sndDerivK)
def firstDerivative(self, im, width, height):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
fstDeriveV1K = ImageFilter.Kernel( (3,3), fstDeriveV1, self.d1scale)
c = im.filter(fstDeriveV1K)
fstDeriveV2K = ImageFilter.Kernel( (3,3), fstDeriveV2, self.d1scale)
d = im.filter(fstDeriveV2K)
fstDeriveH1K = ImageFilter.Kernel( (3,3), fstDeriveH1, self.d1scale)
e = im.filter(fstDeriveH1K)
fstDeriveH2K = ImageFilter.Kernel( (3,3), fstDeriveH2, self.d1scale)
f = im.filter(fstDeriveH2K)
result1 = ImageChops.add(c, d, 2.)
result2 = ImageChops.add(e, f, 2.)
result = ImageChops.add(result1, result2, 2.)
return result
## alternative adding numeric arrays seems slower
## t1 = time()
## c = im.filter(fstDeriveV1K)
## c = Numeric.fromstring(c.tostring(), Numeric.UInt8)
## d = im.filter(fstDeriveV2K)
## d = Numeric.fromstring(d.tostring(), Numeric.UInt8)
## e = im.filter(fstDeriveH1K)
## e = Numeric.fromstring(e.tostring(), Numeric.UInt8)
## f = im.filter(fstDeriveH2K)
## f = Numeric.fromstring(f.tostring(), Numeric.UInt8)
## result = Numeric.fabs(c) + Numeric.fabs(d) +\
## Numeric.fabs(e) + Numeric.fabs(f)
## result.shape = im.size
## result = Numeric.array( result )*0.25
## return result
def drawNPR(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
t1 = time()
if self.viewer.tileRender is False:
zbuf = self.GrabZBuffer(lock=False, flipTopBottom=False)
#imageZbuf = Image.fromstring('L', (self.width, self.height), zbuf.tostring() )
#imageZbuf.save("zbuf.png")
else:
zbuf = self.GrabZBuffer(lock=False, flipTopBottom=False,
zmin=self.viewer.tileRenderCtx.zmin,
zmax=self.viewer.tileRenderCtx.zmax
)
imageFinal = Image.new('L', (self.width+2, self.height+2) )
#padding
# the 4 corners
imageFinal.putpixel((0, 0), zbuf.getpixel((0, 0)) )
imageFinal.putpixel((0, self.height+1), zbuf.getpixel((0, self.height-1)) )
imageFinal.putpixel((self.width+1, 0), zbuf.getpixel((self.width-1, 0)) )
imageFinal.putpixel((self.width+1, self.height+1), zbuf.getpixel((self.width-1, self.height-1)) )
# the top and bottom line
for i in range(self.width):
imageFinal.putpixel((i+1, 0), zbuf.getpixel((i, 0)) )
imageFinal.putpixel((i+1, self.height+1), zbuf.getpixel((i, self.height-1)) )
# the left and right columns
for j in range(self.height):
imageFinal.putpixel((0, j+1), zbuf.getpixel((0, j)) )
imageFinal.putpixel((self.width+1, j+1), zbuf.getpixel((self.width-1, j)) )
# the main picture
imageFinal.paste( zbuf, (1 , 1) )
zbuf = imageFinal
d1strong = d2strong = None
useFirstDerivative = self.d1scale!=0.0
useSecondDerivative = self.d2scale!=0.0
if useFirstDerivative:
if self.viewer.tileRender:
d1 = self.firstDerivative(zbuf, self.width+2, self.height+2)
d1 = d1.crop((1,1,self.width+1,self.width+1))
else:
d1 = self.firstDerivative(zbuf, self.width, self.height)
#d1.save('first.jpg')
#d1strong = Numeric.fromstring(d1.tostring(),Numeric.UInt8)
#print 'first', min(d1.ravel()), max(d1.ravel()), Numeric.sum(d1.ravel())
#print self.d1cut, self.d1off
d1 = Numeric.fromstring(d1.tostring(),Numeric.UInt8)
#mini = min(d1)
#maxi = max(d1)
#print 'd1',mini, maxi
# d1strong = Numeric.clip(d1, self.d1cutL, self.d1cutH)
# d1strong = d1strong.astype('f')*self.d1off
#print 'd1',min(d1strong), max(d1strong)
#print 'first', d1strong.shape, min(d1strong.ravel()), max(d1strong.ravel()), Numeric.sum(d1strong.ravel())
# LOOKUP ramp
#print "self.d1ramp", len(self.d1ramp), self.d1ramp
#d1strong = Numeric.choose(d1.astype('B'), self.d1ramp )
d1strong = numpy.zeros(len(d1))
for index, elt in enumerate(d1.astype('B')):
d1strong[index] = self.d1ramp[elt]
#print 'firstramp', d1strong.shape, min(d1strong.ravel()), max(d1strong.ravel()), Numeric.sum(d1strong.ravel())
if useSecondDerivative:
#d2 = self.secondDerivative(zbuf, self.width, self.height)
sndDerivK = ImageFilter.Kernel( (3,3), sndDeriv, self.d2scale)
d2 = zbuf.filter(sndDerivK)
if self.viewer.tileRender:
d2 = d2.crop((1,1,self.width+1,self.width+1))
#d2.save('second.jpg')
#print 'second1', min(d2.ravel()), max(d2.ravel()), Numeric.sum(d2.ravel())
#print self.d2cut, self.d2off
d2 = Numeric.fromstring(d2.tostring(),Numeric.UInt8)
#mini = min(d2)
#maxi = max(d2)
#print 'd2',mini, maxi
d2strong = Numeric.clip(d2, self.d2cutL, self.d2cutH)
d2strong = d2strong.astype('f')*self.d2off
#d2strong = Numeric.where(Numeric.greater(d2,self.d2cutL),
# d2, 0)
#d2strong = Numeric.where(Numeric.less(d2strong,self.d2cutH),
# d2, 0)
#d2strong += self.d2off
#print 'd2',min(d2strong), max(d2strong)
#print 'second2', d2strong.shape, min(d2strong.ravel()), max(d2strong.ravel()), Numeric.sum(d2strong.ravel())
if useFirstDerivative and useSecondDerivative:
self.outline = Numeric.maximum(d1strong, d2strong)
#self.outline = (d1strong + d2strong)/2
#self.outlineim = ImageChops.add(d1strong, d2strong)
elif useFirstDerivative:
self.outline = d1strong
elif useSecondDerivative:
self.outline = d2strong
else:
self.outline = None
## working OpenGL version
## zbuf = self.GrabZBuffer(lock=False)
## self.ivi.setImage(zbuf)
## deriv = self.ivi.firstDerivative()
## d1strong = Numeric.where(Numeric.greater(deriv,self.d1cut),
## self.d1scale*(deriv+self.d1off), 0)
## deriv2 = self.ivi.secondDerivative()
## d2strong = Numeric.where(Numeric.greater(deriv2,self.d2cut),
## self.d2scale*(deriv2+self.d2off), 0)
## self.outline = Numeric.maximum(d1strong, d2strong)
## self.tk.call(self._w, 'makecurrent')
#print 'time NPR rendering', time()-t1
return
def displayNPR(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
t1 = time()
if self.outline is None:
return
lViewport = glGetIntegerv(GL_VIEWPORT)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(float(lViewport[0]),
float(lViewport[0]+lViewport[2]),
float(lViewport[1]),
float(lViewport[1]+lViewport[3]),
-1, 1)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glDisable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glBlendFunc(GL_DST_COLOR, GL_ZERO);
glRasterPos2f(0.0, 0.0)
self.outline = Numeric.fabs(self.outline-255)
self.outline = self.outline.astype('B')
# glActiveTexture(GL_TEXTURE0);
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
_gllib.glDrawPixels(self.width, self.height,
GL_LUMINANCE, GL_UNSIGNED_BYTE,
self.outline )
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
#print 'time NPR display', time()-t1
def RedrawAASwitch(self, *dummy):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
"""Redraw all the objects in the scene"""
glStencilMask(1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT)
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
glStencilFunc ( GL_ALWAYS, 0, 1 ) ;
glEnable ( GL_STENCIL_TEST ) ;
if not self.viewer.accumBuffersError and \
self.antiAliased and self.renderMode==GL_RENDER:
dist = math.sqrt(Numeric.add.reduce(self.direction*self.direction))
# jitter loop
if self.antiAliased>0:
sca = 1./self.antiAliased
accumContour = None
for i in range(self.antiAliased):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
if self.projectionType == self.PERSPECTIVE:
if self.viewer.tileRender:
tr = self.viewer.tileRenderCtx
left = tr.tileleft
right = tr.tileright
bottom = tr.tilebottom
top = tr.tiletop
else:
left=right=top=bottom=None
self.AccPerspective (self.jitter[i][0], self.jitter[i][1],
0.0, 0.0, dist, left, right, bottom, top)
self._RedrawCamera()
else:
W = self.right-self.left # width in world coordinates
H = self.top-self.bottom # height in world coordinates
glPushMatrix()
glTranslatef (self.jitter[i][0]*W/self.width,
self.jitter[i][1]*H/self.height,
0.0)
self._RedrawCamera()
glPopMatrix()
if i==0 and self.ssao :
self.copyDepth()
# we accumulate the back buffer
glReadBuffer(GL_BACK)
if i==0:
glAccum(GL_LOAD, self.accumWeigth)
else:
glAccum(GL_ACCUM, self.accumWeigth)
if self.contours and self._suspendNPR is False:
self.drawNPR()
if self.outline is not None:
if accumContour is None:
accumContour = self.outline.copy()
accumContour *= sca
else:
accumContour += sca*self.outline
glAccum (GL_RETURN, 1.0)
if self.contours and self._suspendNPR is False:
self.outline = accumContour
else: # plain drawing
if self.ssao : self.copy_depth_ssao = True
self._RedrawCamera()
if self.contours and self._suspendNPR is False:
self.drawNPR()
if self.contours and self._suspendNPR is False:
glViewport(0, 0, self.width, self.height)
self.displayNPR()
if self.stereoMode.startswith('COLOR_SEPARATION') is False \
and self.stereoMode != 'STEREO_BUFFERS':
self.drawHighlight()
if self.ssao :
self.drawSSAO()
glDisable(GL_STENCIL_TEST)
if self.drawThumbnailFlag:
self.drawThumbnail()
if self.swap:
self.tk.call(self._w, 'swapbuffers')
def setShaderSelectionContour(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#import pdb;pdb.set_trace()
#if DejaVu.enableSelectionContour is True:
# if GL.glGetString(GL.GL_VENDOR).find('Intel') >= 0:
# DejaVu.enableSelectionContour = False
# print "intel (even gma) gpu drivers don't handle properly the stencil with FBO"
if DejaVu.enableSelectionContour is True:
try:
## do not try to import this before creating the opengl context, it would fail.
from opengltk.extent import _glextlib
DejaVu.enableSelectionContour = True
except ImportError:
DejaVu.enableSelectionContour = False
print "could not import _glextlib"
#import pdb;pdb.set_trace()
if DejaVu.enableSelectionContour is True:
extensionsList = glGetString(GL_EXTENSIONS)
if extensionsList.find('GL_EXT_packed_depth_stencil') < 0:
DejaVu.enableSelectionContour = False
print "opengl extension GL_EXT_packed_depth_stencil is not present"
if DejaVu.enableSelectionContour is True:
f = _glextlib.glCreateShader(_glextlib.GL_FRAGMENT_SHADER)
# This shader performs a 9-tap Laplacian edge detection filter.
# (converted from the separate "edges.cg" file to embedded GLSL string)
self.fragmentShaderCode = """
uniform float contourSize;
uniform vec4 contourColor;
uniform sampler2D texUnit;
void main(void)
{
float lOffset = .001 * contourSize ; // (1./512.);
vec2 texCoord = gl_TexCoord[0].xy;
if ( ( texCoord [ 0 ] > lOffset ) // to suppress artifacts on frame buffer bounds
&& ( texCoord [ 1 ] > lOffset )
&& ( texCoord [ 0 ] < 1. - lOffset )
&& ( texCoord [ 1 ] < 1. - lOffset ) )
{
float c = texture2D(texUnit, texCoord)[0];
float bl = texture2D(texUnit, texCoord + vec2(-lOffset, -lOffset))[0];
float l = texture2D(texUnit, texCoord + vec2(-lOffset, 0.0))[0];
float tl = texture2D(texUnit, texCoord + vec2(-lOffset, lOffset))[0];
float t = texture2D(texUnit, texCoord + vec2( 0.0, lOffset))[0];
float tr = texture2D(texUnit, texCoord + vec2( lOffset, lOffset))[0];
float r = texture2D(texUnit, texCoord + vec2( lOffset, 0.0))[0];
float br = texture2D(texUnit, texCoord + vec2( lOffset, lOffset))[0];
float b = texture2D(texUnit, texCoord + vec2( 0.0, -lOffset))[0];
if ( 8. * (c + -.125 * (bl + l + tl + t + tr + r + br + b)) != 0. )
{
gl_FragColor = contourColor; //vec4(1., 0., 1., .7) ;
}
else
{
//due to bizarre ATI behavior
gl_FragColor = vec4(1., 0., 0., 0.) ;
}
}
}
"""
_glextlib.glShaderSource(f, 1, self.fragmentShaderCode, 0x7FFFFFFF)
_glextlib.glCompileShader(f)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetShaderiv(f, _glextlib.GL_COMPILE_STATUS, lStatus )
if lStatus == 0:
print "compile status", lStatus
charsWritten = 0
shaderInfoLog = '\0' * 2048
charsWritten, infoLog = _glextlib.glGetShaderInfoLog(f, len(shaderInfoLog),
charsWritten, shaderInfoLog)
print "shaderInfoLog", shaderInfoLog
DejaVu.enableSelectionContour = False
print "selection contour shader didn't compile"
else:
self.shaderProgram = _glextlib.glCreateProgram()
_glextlib.glAttachShader(self.shaderProgram,f)
_glextlib.glLinkProgram(self.shaderProgram)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.shaderProgram,
_glextlib.GL_LINK_STATUS,
lStatus )
if lStatus == 0:
print "link status", lStatus
DejaVu.enableSelectionContour = False
print "selection contour shader didn't link"
else:
_glextlib.glValidateProgram(self.shaderProgram)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.shaderProgram,
_glextlib.GL_VALIDATE_STATUS,
lStatus )
if lStatus == 0:
print "validate status", lStatus
DejaVu.enableSelectionContour = False
print "selection contour shader not validated"
else:
# Get location of the sampler uniform
self.texUnitLoc = int(_glextlib.glGetUniformLocation(self.shaderProgram, "texUnit"))
#print "selection contour shader successfully compiled and linked"
# Get location of the contourSize uniform
self.contourSizeLoc = int(_glextlib.glGetUniformLocation(self.shaderProgram, "contourSize"))
# Get location of the contourSize uniform
self.contourColorLoc = int(_glextlib.glGetUniformLocation(self.shaderProgram, "contourColor"))
## create a framebuffer to receive the texture
self.fb = 0
self.fb = _glextlib.glGenFramebuffersEXT(1, self.fb)
#print "self.fb", self.fb
lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
if lCheckMessage != _glextlib.GL_FRAMEBUFFER_COMPLETE_EXT: # 0x8CD5
print 'glCheckFramebufferStatusEXT %x'%lCheckMessage
DejaVu.enableSelectionContour = False
def drawHighlight(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# lStencil = numpy.zeros(self.width*self.height, dtype='uint32')
# GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
# _gllib.glReadPixels( 0, 0, self.width, self.height,
# GL.GL_STENCIL_INDEX, GL.GL_UNSIGNED_INT,
# lStencil)
# print "lStencil", lStencil[0] # background is 254 # fill is 255
# lStencilImage = Image.fromstring('L', (self.width, self.height),
# lStencil.astype('uint8').tostring() )
# lStencilImage.save("lStencil.png")
# zbuf = self.GrabZBuffer(lock=False, flipTopBottom=False)
# imageZbuf = Image.fromstring('L', (self.width, self.height), zbuf.tostring() )
# imageZbuf.save("lZbuff.png")
# to draw only the highlight zone from the stencil buffer
GL.glEnable(GL.GL_STENCIL_TEST)
glStencilMask(0)
glStencilFunc(GL_EQUAL, 1, 1)
glPushMatrix()
glLoadIdentity()
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
lViewport = glGetIntegerv(GL_VIEWPORT)
glOrtho(float(lViewport[0]),
float(lViewport[0]+lViewport[2]),
float(lViewport[1]),
float(lViewport[1]+lViewport[3]),
-1, 1)
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
# glActiveTexture(GL_TEXTURE0);
## here we apply the patterned highlight
if DejaVu.selectionPatternSize >= 3:
#glEnable(GL_COLOR_LOGIC_OP)
#glLogicOp(GL_AND)
glEnable(GL_TEXTURE_2D)
_gllib.glBindTexture(GL_TEXTURE_2D, self.textureName)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glBegin(GL_POLYGON)
glTexCoord2f(0., 0.)
glVertex2i(0, 0)
lTexWidth = float(self.width)/DejaVu.selectionPatternSize # determine how big the pattern will be
lTexHeight = float(self.height)/DejaVu.selectionPatternSize
glTexCoord2f(lTexWidth, 0.)
glVertex2i(self.width, 0)
glTexCoord2f(lTexWidth, lTexHeight)
glVertex2i(self.width, self.height)
glTexCoord2f(0., lTexHeight)
glVertex2i(0, self.height)
glEnd()
glDisable(GL_BLEND)
glDisable(GL_TEXTURE_2D)
#glDisable(GL_COLOR_LOGIC_OP)
if DejaVu.enableSelectionContour is True \
and DejaVu.selectionContourSize != 0:
from opengltk.extent import _glextlib
#import pdb;pdb.set_trace()
## copying the current stencil to a texture
_gllib.glBindTexture(GL_TEXTURE_2D, self.stencilTextureName )
glCopyTexImage2D(GL_TEXTURE_2D, 0, _glextlib.GL_DEPTH_STENCIL_EXT, 0, 0,
self.width, self.height, 0)
## switch writting to the FBO (Frame Buffer Object)
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, self.fb )
#lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
#print 'glCheckFramebufferStatusEXT 0 %x'%lCheckMessage
## attaching the current stencil to the FBO (Frame Buffer Object)
_glextlib.glFramebufferTexture2DEXT(_glextlib.GL_FRAMEBUFFER_EXT,
_glextlib.GL_DEPTH_ATTACHMENT_EXT,
GL_TEXTURE_2D, self.stencilTextureName,0)
#lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
#print 'glCheckFramebufferStatusEXT 1 %x'%lCheckMessage
_glextlib.glFramebufferTexture2DEXT(_glextlib.GL_FRAMEBUFFER_EXT,
_glextlib.GL_STENCIL_ATTACHMENT_EXT,
GL_TEXTURE_2D, self.stencilTextureName, 0)
#lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
#print 'glCheckFramebufferStatusEXT 2 %x'%lCheckMessage
## attaching the texture to be written as FBO
_gllib.glBindTexture(GL_TEXTURE_2D, self.contourTextureName )
_gllib.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height,
0, GL_RGBA, GL.GL_FLOAT, 0 )
_glextlib.glFramebufferTexture2DEXT(_glextlib.GL_FRAMEBUFFER_EXT,
_glextlib.GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D, self.contourTextureName, 0)
#lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
#print 'glCheckFramebufferStatusEXT 3 %x'%lCheckMessage
## verifying that everything gets attached to the FBO
lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
if lCheckMessage != _glextlib.GL_FRAMEBUFFER_COMPLETE_EXT: # 0x8CD5
print 'glCheckFramebufferStatusEXT %x'%lCheckMessage
DejaVu.enableSelectionContour = False
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, 0 )
print 'opengl frame buffer object not available, selection contour is now disabled.'
#print 'you may need to set enableSelectionContour to False in the following file:'
#print '~/.mgltools/(version numer)/DejaVu/_dejavurc'
else:
## writing the stencil to the texture / FBO
glClear(GL_COLOR_BUFFER_BIT)
glBegin(GL_POLYGON)
glVertex2i(0, 0)
glVertex2i(self.width, 0)
glVertex2i(self.width, self.height)
glVertex2i(0, self.height)
glEnd()
## switch writing to the regular frame buffer (normaly the back buffer)
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, 0 )
## here we obtain the contour of the stencil copied in the texture and draw it
from opengltk.extent import _glextlib
_glextlib.glUseProgram( self.shaderProgram )
_glextlib.glUniform1i( self.texUnitLoc, 0)
_glextlib.glUniform1f( self.contourSizeLoc, float(DejaVu.selectionContourSize))
_glextlib.glUniform4f( self.contourColorLoc,
DejaVu.selectionContourColor[0],
DejaVu.selectionContourColor[1],
DejaVu.selectionContourColor[2],
DejaVu.selectionContourColor[3]
)
glEnable(GL_BLEND)
glStencilFunc(GL_NOTEQUAL, 1, 1) #so the contour is drawn only outside of the highlighted area
glBegin(GL_POLYGON)
glTexCoord2i(0, 0)
glVertex2i(0, 0)
glTexCoord2i(1, 0)
glVertex2i(self.width, 0)
glTexCoord2i(1, 1)
glVertex2i(self.width, self.height)
glTexCoord2i(0, 1)
glVertex2i(0, self.height)
glEnd()
glDisable(GL_BLEND)
_glextlib.glUseProgram( 0 )
# to protect our texture, we bind the default texture while we don't use it
_gllib.glBindTexture(GL_TEXTURE_2D, 0)
glEnable(GL_DEPTH_TEST)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
glStencilMask(1)
glStencilFunc ( GL_ALWAYS, 0, 1 )
#===============================================================================
# SSAO Shader
#===============================================================================
def setTextureSSAO(self):
self.depthtextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.depthtextureName]),
numpy.array([1.]))
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthtextureName);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
#_gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, self.width,
# self.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None);
#SSAO depthexture
self.illumtextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.illumtextureName]),
numpy.array([1.]))
_gllib.glBindTexture (GL_TEXTURE_2D, self.illumtextureName);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
#_gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, self.width,
# self.height, 0, GL_LUMINANCE, GL_UNSIGNED_INT, None);
#SSAO depthexture
self.rendertextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.rendertextureName]),
numpy.array([1.]))
_gllib.glBindTexture (GL_TEXTURE_2D, self.rendertextureName);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
#_gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, self.width,
# self.height, 0, GL_RGB, GL_UNSIGNED_INT, None);
#depth mask texture
self.depthmasktextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.depthmasktextureName]),
numpy.array([1.]))
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthmasktextureName);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri (GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
#_gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, self.width,
# self.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None);
#SSAO randomtexture
#
# self.randomTexture = Texture()
# import Image
# img = Image.open(DejaVu.__path__[0]+os.sep+"textures"+os.sep+"random_normals.png")
# self.randomTexture.Set(enable=1, image=img)
self.randomtextureName = int(glGenTextures(1)[0])
glPrioritizeTextures(numpy.array([self.randomtextureName]),
numpy.array([1.]))
# _gllib.glBindTexture (GL_TEXTURE_2D, self.randomtextureName);
# glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
# glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
# glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
# glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
# glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
# _gllib.glTexImage2D (GL_TEXTURE_2D, 0, self.randomTexture.format,
# self.randomTexture.width, self.randomTexture.height,
# 0, self.randomTexture.format, GL_UNSIGNED_INT,
# self.randomTexture.image);
_gllib.glBindTexture (GL_TEXTURE_2D,0)
def setShaderSSAO(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# if not DejaVu.enableSSAO : #this is case there is no _glextlib
# return
try:
## do not try to import this before creating the opengl context, it would fail.
from opengltk.extent import _glextlib
except ImportError:
DejaVu.enableSSAO = False
print "could not import _glextlib, SSAO disable"
#import pdb;pdb.set_trace()
if DejaVu.enableSSAO is True:
vendor = glGetString(GL_VENDOR)
render = glGetString(GL_RENDERER)
extensionsList = glGetString(GL_EXTENSIONS)
if extensionsList.find('GL_EXT_packed_depth_stencil') < 0:
DejaVu.enableSSAO = False
print "opengl extension not present, SSAO disable"
if vendor.find("Mesa") !=-1 or vendor.find("MESA") != -1 :
print "MESA Driver found, SSAO disable"
DejaVu.enableSSAO = False
if render.find("Mesa") !=-1 or render.find("MESA") != -1 :
print "MESA Driver found, SSAO disable"
DejaVu.enableSSAO = False
if DejaVu.enableSSAO is True:
try :
self.setTextureSSAO()
except :
DejaVu.enableSSAO = False
print "opengl / texture problem,SSAO disable"
self.ssao = False
return
# self.setDefaultSSAO_OPTIONS()
f = _glextlib.glCreateShader(_glextlib.GL_FRAGMENT_SHADER)
sfile = open(os.path.join(DejaVu.__path__[0], "shaders", "fragSSAO"))
lines = sfile.readlines()
sfile.close()
self.fragmentSSAOShaderCode=""
for l in lines :
self.fragmentSSAOShaderCode+=l
v = _glextlib.glCreateShader(_glextlib.GL_VERTEX_SHADER)
sfile = open(os.path.join(DejaVu.__path__[0], "shaders", "vertSSAO"))
lines = sfile.readlines()
sfile.close()
self.vertexSSAOShaderCode=""
for l in lines :
self.vertexSSAOShaderCode+=l
lStatus = 0x7FFFFFFF
_glextlib.glShaderSource(v, 1, self.vertexSSAOShaderCode, lStatus)
_glextlib.glCompileShader(v)
_glextlib.glShaderSource(f, 1, self.fragmentSSAOShaderCode, lStatus)
_glextlib.glCompileShader(f)
lStatus1 = _glextlib.glGetShaderiv(f, _glextlib.GL_COMPILE_STATUS, lStatus )
#print "SSAO compile status frag: %s"%lStatus,
lStatus2 = _glextlib.glGetShaderiv(v, _glextlib.GL_COMPILE_STATUS, lStatus )
#print " vertex: %s"%lStatus
if lStatus1 == 0 or lStatus2 == 0:
# print "compile status", lStatus
charsWritten = 0
shaderInfoLog = '\0' * 2048
charsWritten, infoLog = _glextlib.glGetShaderInfoLog(f, len(shaderInfoLog),
charsWritten, shaderInfoLog)
print "shaderInfoLog", shaderInfoLog
DejaVu.enableSSAO = False
print "SSAO shader didn't compile"
else:
self.shaderSSAOProgram = _glextlib.glCreateProgram()
_glextlib.glAttachShader(self.shaderSSAOProgram,v)
_glextlib.glAttachShader(self.shaderSSAOProgram,f)
_glextlib.glLinkProgram(self.shaderSSAOProgram)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.shaderSSAOProgram,
_glextlib.GL_LINK_STATUS,
lStatus )
if lStatus == 0:
# print "link status", lStatus
log = ""
charsWritten = 0
progInfoLog = '\0' * 2048
charsWritten, infoLog = _glextlib.glGetProgramInfoLog(self.shaderSSAOProgram, len(progInfoLog),
charsWritten, progInfoLog)
DejaVu.enableSSAO = False
print "SSAO shader didn't link"
print "log ",progInfoLog
else:
_glextlib.glValidateProgram(self.shaderSSAOProgram)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.shaderSSAOProgram,
_glextlib.GL_VALIDATE_STATUS,
lStatus )
if lStatus == 0:
print "SSAO shader did not validate, status:", lStatus
DejaVu.enableSSAO = False
print "enableSSAO not validated"
else:
# Get location
self.SSAO_LOCATIONS = {
'RandomTexture': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'RandomTexture' ),
'DepthTexture': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'DepthTexture' ),
'RenderedTexture': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'RenderedTexture' ),
'LuminanceTexture': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'LuminanceTexture' ),
'DepthMaskTexture': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'DepthMaskTexture' ),
'RenderedTextureWidth': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'RenderedTextureWidth' ),
'RenderedTextureHeight': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'RenderedTextureHeight' ),
'realfar': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'realfar' ),
#'realnear': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'realnear' ),
# 'fogS': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'fogS' ),
# 'fogE': _glextlib.glGetUniformLocation( self.shaderSSAOProgram, 'fogE' ),
}
for k in self.SSAO_OPTIONS :
self.SSAO_LOCATIONS[k] = _glextlib.glGetUniformLocation( self.shaderSSAOProgram, k )
def setDefaultSSAO_OPTIONS(self):
try :
from opengltk.extent import _glextlib
except :
DejaVu.enableSSAO = False
print "could not import _glextlib, SSAO disabled"
self.SSAO_OPTIONS={'far': [300.0,0.,1000.,"float"],
'near': [self.near,0.,100.,"float"],
'method':[self.ssao_method,0,1,"int"],
'fix':[0,0,1,"int"],
'do_noise':[0,0,1,"int"],
'fog':[0,0,1,"int"],
'use_fog':[1,0,1,"int"],
'use_mask_depth':[self.use_mask_depth,0,1,"int"],
'only_depth':[0,0,1,"int"],
'mix_depth':[0,0,1,"int"],
'only_ssao':[0,0,1,"int"],
'show_mask_depth':[0,0,1,"int"],
'scale':[1.0,1.0,100.0,"float"],
'samples': [6,1,8,"int"],
'rings': [6,1,8,"int"],
'aoCap': [1.2,0.0,10.0,"float"],
'aoMultiplier': [100.0,1.,500.,"float"],
'depthTolerance': [0.0,0.0,1.0,"float"],
'aorange':[60.0,1.0,500.0,"float"],
'negative':[0,0,1,"int"],
'correction':[6.0,0.0,1000.0,"float"],
#'force_real_far':[0,0,1,"int"],
}
self.SSAO_OPTIONS["near"][0] = 2.0
self.Set(near = 2.0)
self.SSAO_OPTIONS_ORDER = [
'use_fog','only_ssao','only_depth','mix_depth',
'negative','do_noise','near','far','scale','rings',
'samples','aoCap','aoMultiplier',
'aorange','depthTolerance','correction','use_mask_depth','fix']
def copyDepth(self):
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthtextureName);
glCopyTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT, 0, 0, self.width,
self.height, 0);
self.copy_depth_ssao = False
def copyBuffer(self, depthmask=False):
if depthmask :
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthmasktextureName);
glCopyTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT, 0, 0, self.width,
self.height, 0);
return
if self.copy_depth_ssao :
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthtextureName);
glCopyTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT, 0, 0, self.width,
self.height, 0);
_gllib.glBindTexture (GL_TEXTURE_2D, self.illumtextureName);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, self.width,
self.height, 0);
_gllib.glBindTexture (GL_TEXTURE_2D, self.rendertextureName);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, self.width,
self.height, 0);
_gllib.glBindTexture (GL_TEXTURE_2D, 0);
def drawSSAO(self,combine=0):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if DejaVu.enableSSAO is True and self.ssao:
#if not self.AR.use_mask:
self.copyBuffer()
from opengltk.extent import _glextlib
import numpy
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, 0 )
_glextlib.glUseProgram( self.shaderSSAOProgram )
glActiveTexture(GL_TEXTURE3);
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthtextureName);
_glextlib.glUniform1i(self.SSAO_LOCATIONS['DepthTexture'],3)
glActiveTexture(GL_TEXTURE4);
_gllib.glBindTexture (GL_TEXTURE_2D, self.rendertextureName);
_glextlib.glUniform1i(self.SSAO_LOCATIONS['RenderedTexture'],4)
glActiveTexture(GL_TEXTURE5);
_gllib.glBindTexture (GL_TEXTURE_2D, self.illumtextureName);
_glextlib.glUniform1i(self.SSAO_LOCATIONS['LuminanceTexture'],5)
glActiveTexture(GL_TEXTURE6);
_gllib.glBindTexture (GL_TEXTURE_2D, self.randomtextureName);
_glextlib.glUniform1i(self.SSAO_LOCATIONS['RandomTexture'],6)
glActiveTexture(GL_TEXTURE7);
_gllib.glBindTexture (GL_TEXTURE_2D, self.depthmasktextureName);
_glextlib.glUniform1i(self.SSAO_LOCATIONS['DepthMaskTexture'],7)
_glextlib.glUniform1f(self.SSAO_LOCATIONS['RenderedTextureWidth'],self.width)
_glextlib.glUniform1f(self.SSAO_LOCATIONS['RenderedTextureHeight'],self.height)
_glextlib.glUniform1f(self.SSAO_LOCATIONS['realfar'],self.far)
#_glextlib.glUniform1f(self.SSAO_LOCATIONS['realnear'],self.near)
for k in self.SSAO_OPTIONS:
if len(self.SSAO_OPTIONS[k]) == 5 :
self.SSAO_OPTIONS[k][0] = self.SSAO_OPTIONS[k][-1].get()
val = self.SSAO_OPTIONS[k][0]
if k == "far" :
val = self.far + 230.
if len(self.SSAO_OPTIONS[k]) == 5 :
val = self.SSAO_OPTIONS[k][-1].get()
if k == "fog" :
val = int(self.fog.enabled)
if len(self.SSAO_OPTIONS[k]) == 5 :
self.SSAO_OPTIONS[k][-1].set(val)
if self.SSAO_OPTIONS[k][3] == "float":
_glextlib.glUniform1f(self.SSAO_LOCATIONS[k],val)
else :
_glextlib.glUniform1i(self.SSAO_LOCATIONS[k],val)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT)
self.drawTexturePolygon()
self.endSSAO()
def endSSAO(self):
if DejaVu.enableSSAO is True :
from opengltk.extent import _glextlib
_glextlib.glUseProgram(0)
glActiveTexture(GL_TEXTURE0);
_gllib.glBindTexture (GL_TEXTURE_2D, 0);
# _gllib.glBindTexture (GL_TEXTURE_2D,GL_TEXTURE0)
def drawTexturePolygon(self):
glPushMatrix()
glLoadIdentity()
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
lViewport = glGetIntegerv(GL_VIEWPORT)
glOrtho(float(lViewport[0]),
float(lViewport[0]+lViewport[2]),
float(lViewport[1]),
float(lViewport[1]+lViewport[3]),
-1, 1)
glEnable(GL_BLEND)
# glEnable(GL_TEXTURE_2D)
# if self.dsT == 0 :
# _gllib.glBindTexture (GL_TEXTURE_2D, self.depthtextureName);
# elif self.dsT == 1 :
# _gllib.glBindTexture (GL_TEXTURE_2D, self.illumtextureName);
# else :
# _gllib.glBindTexture (GL_TEXTURE_2D, self.rendertextureName);
glBegin(GL_POLYGON)
glTexCoord2i(0, 0)
glVertex2i(0, 0)
glTexCoord2i(1, 0)
glVertex2i(self.width, 0)
glTexCoord2i(1, 1)
glVertex2i(self.width, self.height)
glTexCoord2i(0, 1)
glVertex2i(0, self.height)
glEnd()
glDisable(GL_BLEND)
_gllib.glBindTexture (GL_TEXTURE_2D, 0);
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
## def DrawImage(self, imarray, mode='RGB', format=GL.GL_UNSIGNED_BYTE,
## filter=None, swap=False):
## """Draw an array of pixel in the camera
## """
## if imarray is None:
## return
## GL.glViewport(0, 0, self.width, self.height)
## GL.glMatrixMode(GL.GL_PROJECTION)
## GL.glPushMatrix()
## GL.glLoadIdentity()
## GL.glOrtho(0, self.width, 0, self.height, -1.0, 1.0)
## GL.glMatrixMode(GL.GL_MODELVIEW)
## GL.glPushMatrix()
## GL.glLoadIdentity()
## GL.glRasterPos2i( 0, 0)
## GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
## if not swap:
## GL.glDrawBuffer(GL.GL_BACK)
## if filter:
## GL.glEnable(GL.GL_CONVOLUTION_2D)
## GL.glConvolutionFilter2D(GL.GL_CONVOLUTION_2D, GL.GL_LUMINANCE,
## 3, 3, GL.GL_LUMINANCE, GL.GL_FLOAT,
## filter)
## if mode=='RGB':
## _gllib.glDrawPixels( self.width, self.height,
## GL.GL_RGB, format, imarray)
## elif mode in ['L','P']:
## _gllib.glDrawPixels( self.width, self.height,
## GL.GL_LUMINANCE, format, imarray)
## GL.glMatrixMode(GL.GL_PROJECTION)
## GL.glPopMatrix()
## GL.glMatrixMode(GL.GL_MODELVIEW)
## GL.glPopMatrix()
## GL.glDisable(GL.GL_CONVOLUTION_2D)
## GL.glFlush()
## if swap:
## self.tk.call(self._w, 'swapbuffers')
## def secondDerivative(self, imarray, mode='RGB', format=GL.GL_UNSIGNED_BYTE,
## swap=False):
## sndDeriv = Numeric.array([ [-0.125, -0.125, -0.125,],
## [-0.125, 1.0, -0.125,],
## [-0.125, -0.125, -0.125,] ], 'f')
## self.DrawImage(imarray, mode, format, sndDeriv, swap)
## if not swap:
## buffer=GL.GL_BACK
## deriv = self.GrabFrontBufferAsArray(lock=False, buffer=buffer)
## return Numeric.fabs(deriv).astype('B')
## def firstDerivative(self, imarray, mode='RGB', format=GL.GL_UNSIGNED_BYTE,
## swap=False):
## if not swap:
## buffer=GL.GL_BACK
## else:
## buffer=GL.GL_FRONT
## fstDeriveV = Numeric.array([ [-0.125, -0.25, -0.125],
## [ 0.0 , 0.0, 0.0 ],
## [0.125, 0.25, 0.125] ], 'f')
## self.DrawImage(imarray, mode, format, fstDeriveV, swap)
## derivV = self.GrabFrontBufferAsArray(lock=False, buffer=buffer)
## if derivV is None:
## return None
## fstDeriveV = Numeric.array([ [ 0.125, 0.25, 0.125],
## [ 0.0 , 0.0, 0.0 ],
## [-0.125, -0.25, -0.125] ], 'f')
## self.DrawImage(imarray, mode, format, fstDeriveV, swap)
## derivV += self.GrabFrontBufferAsArray(lock=False, buffer=buffer)
## derivV = Numeric.fabs(derivV*0.5)
## fstDeriveH = Numeric.array([ [-0.125, 0.0, 0.125],
## [-0.25 , 0.0, 0.25 ],
## [-0.125, 0.0, 0.125] ], 'f')
## self.DrawImage(imarray, mode, format, fstDeriveH, swap)
## derivH = self.GrabFrontBufferAsArray(lock=False, buffer=buffer)
## fstDeriveH = Numeric.array([ [ 0.125, 0.0, -0.125],
## [ 0.25 , 0.0, -0.25 ],
## [ 0.125, 0.0, -0.125] ], 'f')
## self.DrawImage(imarray, mode, format, fstDeriveH, swap)
## derivH += self.GrabFrontBufferAsArray(lock=False, buffer=buffer)
## derivH = Numeric.fabs(derivH*0.5)
## return derivH+derivV.astype('B')
def Redraw(self, *dummy):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if self.selectDragRect:
return
if not self.initialized:
return
if not self.visible:
return
# was causing very slow update of light source
# This function shoudl force redrawing and hence not
# wait for other things to happen
#self.update_idletasks()
# At this point We expect no interruption after this
# and this OpenGL context should remain the current one until
# we swap buffers
self.tk.call(self._w, 'makecurrent')
#glPushAttrib(GL_ALL_ATTRIB_BITS)
if not self.viewer.tileRender:
# only setup camera projection if we are not rendering tiles
# when tiles are rendered the projection is set by the tile
# renderer tr.beginTile() method
if self.projectionType==self.ORTHOGRAPHIC:
self.PerspectiveToOrthogonal()
else:
self.SetupProjectionMatrix()
if self.renderMode == GL_RENDER:
# This activate has to be done here, else we get a
# GLXBadContextState on the alpha. If we are in
# GL_SELECT mode we did already an activate in DoPick
# here we need to restore the camrea's GLstate
if self.viewer and len(self.viewer.cameras) > 1:
#self.SetupProjectionMatrix()
self.fog.Set(enabled=self.fog.enabled)
r,g,b,a = self.backgroundColor
glClearColor(r, g, b, a )
self.RedrawAASwitch()
while 1:
errCode = glGetError()
if not errCode: break
errString = gluErrorString(errCode)
print 'GL ERROR: %d %s' % (errCode, errString)
def glError(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
while 1:
errCode = glGetError()
if not errCode: return
errString = gluErrorString(errCode)
print 'GL ERROR: %d %s' % (errCode, errString)
def SetupLights(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
""" loops over the lights and sets the direction and/or position of a
light only if it is enabled and the flag is set to positive. Also, if
there is more than one camera, it always sets the lights that are on"""
for l in self.viewer.lights:
if l.enabled is True:
if len(self.viewer.cameras) > 1:
if l.positional is True:
glLightfv(l.num, GL_POSITION, l.position)
glLightfv(l.num, GL_SPOT_DIRECTION,
l.spotDirection)
else: # directional
glLightfv(l.num, GL_POSITION, l.direction)
else:
if l.positional is True:
if l.posFlag:
glLightfv(l.num, GL_POSITION, l.position)
l.posFlag = 0
if l.spotFlag:
glLightfv(l.num, GL_SPOT_DIRECTION,
l.spotDirection)
l.spotFlag = 0
else: #directional
if l.dirFlag:
#rot = Numeric.reshape(self.rotation, (4,4))
#dir = Numeric.dot(l.direction, rot).astype('f')
#glLightfv(l.num, GL_POSITION, dir)
glLightfv(l.num, GL_POSITION, l.direction)
l.dirFlag = 0
#self.posLog.append(l.direction)
#print 'setting light to ',l.direction
## l.posFlag = 0
## l.spotFlag = 0
def activeStereoSupport(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
try:
root = Tkinter.Tk()
root.withdraw()
loadTogl(root)
Tkinter.Widget(root, 'togl', (), {'stereo':'native'} )
#currentcontext = self.tk.call(self._w, 'contexttag')
#print "StandardCamera.activeStereoSupport currentcontext", currentcontext
if GL.glGetIntegerv(GL.GL_STEREO)[0] > 0:
lReturn = True
else:
#print 'Stereo buffering is not available'
lReturn = False
Tkinter.Widget(root, 'togl', (), {'stereo':'none'} )
return lReturn
except Exception, e:
if str(e)=="Togl: couldn't get visual":
#print 'Stereo buffering is not available:', e
lReturn = False
elif str(e)=="Togl: couldn't choose stereo pixel format":
#print 'Stereo buffering is not available:', e
lReturn = False
else:
print 'something else happend',e
lReturn = False
Tkinter.Widget(root, 'togl', (), {'stereo':'none'} )
return lReturn
try:
import pymedia.video.vcodec as vcodec
class RecordableCamera(StandardCamera):
"""Subclass Camera to define a camera supporting saving mpg video
"""
def __init__(self, master, screenName, viewer, num, check=1,
cnf={}, **kw):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
StandardCamera.__init__( self, *(master, screenName, viewer, num,
check, cnf), **kw)
# this attribute can be 'recording', 'autoPaused', 'paused' or 'stopped'
self.videoRecordingStatus = 'stopped'
self.videoOutputFile = None
self.pendingAutoPauseID = None
self.pendingRecordFrameID = None
self.encoder = None
self.autoPauseDelay = 1 # auto pause after 1 second
self.pauseLength = 15 # if recording pauses automatically
# add self.pauseLength frames will be added
# when recording resumes
self.videoRecorder = None
self.nbRecordedframes = 0
self.vidimage = None
def setVideoOutputFile(self, filename='out.mpg'):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# open the file
self.videoOutputFile = open( filename, 'wb' )
assert self.videoOutputFile, 'ERROR, failed to open file: '+filename
def setVideoParameters(self, width=None, height=None, pauseLength=0,
autoPauseDelay=1, outCodec = 'mpeg1video'):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# make sure image is dimensions are even
if width is None:
width = self.width
w = self.videoFrameWidth = width - width%2
if height is None:
height = self.height
h = self.videoFrameHeight = height - height%2
if h != self.height or w != self.width:
self.Set(width=w, height=h)
## FIXME here we should lock the size of the Camera
##
params= { 'type': 0, 'gop_size': 12, 'frame_rate_base': 125,
'max_b_frames': 0, 'width': w, 'height': h,
'frame_rate': 2997,'deinterlace': 0, #'bitrate': 9800000,
'id': vcodec.getCodecID(outCodec)
}
## params= { 'type': 0, 'gop_size': 12, 'frame_rate_base': 125,
## 'max_b_frames': 0, 'width': w, 'height': h,
## 'frame_rate': 2997,'deinterlace': 0, 'bitrate': 2700000,
## 'id': vcodec.getCodecID( 'mpeg1video' )
## }
if outCodec== 'mpeg1video':
params['bitrate']= 2700000
else:
params['bitrate']= 9800000
self.encoder = vcodec.Encoder( params )
self.pauseLength = pauseLength
self.autoPauseDelay = autoPauseDelay
def start(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
# toggle to recording mode
if self.videoOutputFile is None or self.encoder is None:
return
self.videoRecordingStatus = 'recording'
self.nbRecordedframes = 0
self.viewer.master.after(1, self.recordFrame)
def recordFrame(self, force=False):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
if not self.viewer.hasRedrawn and not force:
return
root = self.viewer.master
if self.videoRecordingStatus=='paused':
self.pendingRecordFrameID = root.after(1, self.recordFrame)
return
## if self.videoRecordingStatus=='autopaused':
## # add frames for pause
## #print 'adding %d pause frames --------------', self.pauseLength
## imstr = self.lastFrame.tostring()
## for i in range(self.pauseLength):
## bmpFrame = vcodec.VFrame(
## vcodec.formats.PIX_FMT_RGB24, self.lastFrame.size,
## (imstr, None, None))
## yuvFrame = bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P)
## self.videoOutputFile.write(
## self.encoder.encode(yuvFrame).data)
## self.videoRecordingStatus = 'recording'
if self.videoRecordingStatus=='recording' or force:
if self.pendingAutoPauseID:
print 'auto pause id', self.pendingAutoPauseID
root.after_cancel(self.pendingAutoPauseID)
self.pendingAutoPauseID = None
# if DejaVu.enableSSAO is True and self.ssao :#and self.vidimage is not None:
# image = self.GrabFrontBuffer(lock=False)
# else :
image = self.GrabFrontBuffer(lock=False)
# FIXME this resizing can be avoided if camera size is locked
image = image.resize((self.videoFrameWidth,
self.videoFrameHeight))
self.lastFrame = image
bmpFrame = vcodec.VFrame(
vcodec.formats.PIX_FMT_RGB24, image.size,
(self.lastFrame.tostring(), None, None))
yuvFrame = bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P)
self.videoOutputFile.write(self.encoder.encode(yuvFrame).data)
#self.pendingAutoPauseID = root.after(self.autoPauseDelay*1000,
# self.autoPause)
self.viewer.hasRedrawn = False
self.pendingRecordFrameID = root.after(1, self.recordFrame)
self.nbRecordedframes += 1
def Redraw(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
StandardCamera.Redraw(self)
self.viewer.hasRedrawn = True
self.recordFrame()
def autoPause(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#print 'autoPause =========================='
self.videoRecordingStatus = 'autoPaused'
if self.pendingRecordFrameID:
root = self.viewer.master
root.after_cancel(self.pendingRecordFrameID)
self.pendingAutoPauseID = None
def pause(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
#print 'pause =========================='
self.videoRecordingStatus = 'paused'
if self.pendingRecordFrameID:
root = self.viewer.master
root.after_cancel(self.pendingRecordFrameID)
self.pendingAutoPauseID = None
def stop(self):
if __debug__:
if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
self.videoRecordingStatus = 'stopped'
self.videoOutputFile.close()
root = self.viewer.master
if self.pendingAutoPauseID:
root.after_cancel(self.pendingAutoPauseID)
if self.pendingRecordFrameID:
root.after_cancel(self.pendingRecordFrameID)
Camera = RecordableCamera
except ImportError:
Camera = StandardCamera
```
#### File: MGLToolsPckgs/DejaVu/Cylinders.py
```python
import numpy
import numpy.oldnumeric as Numeric, math, sys
from numpy.oldnumeric import array
from opengltk.OpenGL import GL
from opengltk.extent.utillib import solidCylinder
import DejaVu
from DejaVu.IndexedGeom import IndexedGeom
import datamodel, viewerConst
from viewerFns import checkKeywords
from mglutil.math.rotax import rotax
from colorTool import glMaterialWithCheck, resetMaterialMemory
from Materials import Materials
try:
from opengltk.extent.utillib import glDrawCylinderSet
except:
glDrawCylinderSet = None
class Cylinders(IndexedGeom):
"""Class for sets of cylinders
"""
keywords = IndexedGeom.keywords + [
'radii',
'quality'
]
def getState(self, full=False):
state = IndexedGeom.getState(self, full)
state['quality'] = self.quality
if full:
rad = self.vertexSet.radii.array
if len(rad):
state['radii'] = rad
return state
def __init__(self, name=None, check=1, **kw):
if not kw.get('shape'):
kw['shape'] = (0,3) # default shape for sphere set
self.culling = GL.GL_BACK
self.inheritCulling = 0
self.frontPolyMode = GL.GL_FILL
self.inheritFrontPolyMode = viewerConst.NO
self.lighting = viewerConst.YES
self.realFMat = Materials() # used in RedoDisplayList to build
self.realBMat = Materials() # used in RedoDisplayList to build
# material taking getFrom into account
self.quality = None
self.cyldraw = self.cyldrawWithSharpColorBoundaries
apply( IndexedGeom.__init__, (self, name, check), kw)
assert len(self.vertexSet.vertices.ashape)==2
if hasattr(self, 'oneRadius') is False:
self.oneRadius = viewerConst.YES
self.vertexSet.radii = datamodel.ScalarProperties(
'radii', [1.], datatype=viewerConst.FPRECISION)
self._modified = False
self.useGlDrawCylinderSet = 1
def Set(self, check=1, redo=1, updateOwnGui=True, **kw):
"""set data for this object
check=1 : verify that all the keywords present can be handle by this func
redo=1 : append self to viewer.objectsNeedingRedo
updateOwnGui=True : allow to update owngui at the end this func
"""
redoFlags = 0
# Exceptionnaly this has to be before the call to Geom.Set
# because we want to override the treatment of it by Geom.Set
invertNormals = kw.get('invertNormals')
if invertNormals is not None:
kw.pop('invertNormals')
if self.invertNormals != invertNormals:
self.invertNormals = invertNormals
redoFlags |= self._redoFlags['redoDisplayListFlag']
redoFlags |= apply( IndexedGeom.Set, (self, check, 0), kw)
rad = kw.get('radii')
if rad is not None:
redoFlags |= self._redoFlags['redoDisplayListFlag']
try:
rad = float(rad)
self.oneRadius = viewerConst.YES
self.vertexSet.radii = datamodel.ScalarProperties('radii',
[rad], datatype=viewerConst.FPRECISION)
except: # it is not a number, so it has to be a sequence
l = len(rad)
import types
if type(rad) == types.StringType:
raise TypeError, "bad value for radii"
elif l==len(self.vertexSet.vertices):
self.oneRadius = viewerConst.NO
self.vertexSet.radii = datamodel.ScalarProperties(
'radii', rad, datatype=viewerConst.FPRECISION)
elif l in (1, 2):
self.oneRadius = viewerConst.YES
self.vertexSet.radii = datamodel.ScalarProperties(
'radii', [rad], datatype=viewerConst.FPRECISION)
else:
raise ValueError, "bad value for radii"
v=kw.get('vertices')
if rad is not None or v is not None and \
hasattr(self.vertexSet, 'radii'):
self.vertexSet.radii.PropertyStatus(len(self.vertexSet))
if self.vertexSet.radii.status < viewerConst.COMPUTED:
self.oneRadius = viewerConst.YES
else:
self.oneRadius = viewerConst.NO
quality = kw.pop('quality', None)
if quality is not None or self.quality not in [1,2,3,4,5]:
if quality in [1,2,3,4,5]:
self.quality = quality
else:
if len(self.vertexSet.vertices.array) < 500:
self.quality = 5
elif len(self.vertexSet.vertices.array) < 5000:
self.quality = 4
elif len(self.vertexSet.vertices.array) < 50000:
self.quality = 3
elif len(self.vertexSet.vertices.array) < 100000:
self.quality = 2
else:
self.quality = 1
self.v, self.n = self._cylinderTemplate()
redoFlags |= self._redoFlags['redoDisplayListFlag']
return self.redoNow(redo, updateOwnGui, redoFlags)
def Draw(self):
#print "Cylinders.Draw"
#import traceback;traceback.print_stack()
# for some reason if I do not set this always on MacOSX only the first
# cylinder gets the right color
if sys.platform=='darwin' \
or DejaVu.preventIntelBug_BlackTriangles is True:
self.checkMat = False
else:
self.checkMat = True
if len(self.vertexSet.vertices)==0 or len(self.faceSet.faces)==0:
return
if self.inheritMaterial:
fp = None
bp = None
face = None
else:
mat = self.materials[GL.GL_FRONT]
rmat = self.realFMat
bind = [10,10,10,10]
for pInd in range(4):
bind[pInd], rmat.prop[pInd] = mat.GetProperty(pInd)
if rmat.binding[pInd] == viewerConst.OVERALL:
glMaterialWithCheck( GL.GL_FRONT,
viewerConst.propConst[pInd],
rmat.prop[pInd][0])
if pInd==1:
GL.glColor4fv(rmat.prop[pInd][0])
pInd = 4 # FIXME mat.GetProperty does not handle shininess
if rmat.binding[pInd] == viewerConst.OVERALL:
glMaterialWithCheck( GL.GL_FRONT,
viewerConst.propConst[pInd],
rmat.prop[pInd][0])
rmat.prop[4] = mat.prop[4]
rmat.prop[5] = mat.prop[5]
rmat.binding[:4] = bind
rmat.binding[4:] = rmat.binding[4:]
fp = rmat
# fp = self.materials[GL.GL_FRONT]
if fp:
if self.frontAndBack:
face = GL.GL_FRONT_AND_BACK
bp = None
else:
face = GL.GL_FRONT
mat = self.materials[GL.GL_BACK]
rmat = self.realBMat
bind = [10,10,10,10]
for pInd in range(4):
bind[pInd], rmat.prop[pInd]=mat.GetProperty(pInd)
if rmat.binding[pInd] == viewerConst.OVERALL:
glMaterialWithCheck( GL.GL_BACK,
viewerConst.propConst[pInd],
rmat.prop[pInd][0])
rmat.prop[4] = mat.prop[4]
rmat.prop[5] = mat.prop[5]
rmat.binding[:4] = bind
rmat.binding[4:] = rmat.binding[4:]
bp = rmat
c = self.vertexSet.vertices.array
if glDrawCylinderSet:
radii = self.vertexSet.radii.array
fmat = None
fbind = None
bmat = None
bbind = None
if fp:
fmat = fp.prop[0:5]
fbind = fp.binding[0:5]
if bp:
bmat = bp.prop[0:5]
bbind = bp.binding[0:5]
highlight = None
if len(self.highlight) > 0:
highlight = self.highlight
if self.getSharpColorBoundaries() in [True, 1]:
return glDrawCylinderSet(c, self.faceSet.faces.array, radii,
fmat, bmat, fbind, bbind,
self.frontAndBack, self.quality,
self.invertNormals,
highlight=highlight,
sharpColorBoundaries=1)
else:
v1 = self.v[:,0,:].astype("f")
v2 = self.v[:,1,:].astype("f")
return glDrawCylinderSet(c, self.faceSet.faces.array, radii,
fmat, bmat, fbind, bbind,
self.frontAndBack, self.quality,
self.invertNormals,
sharpColorBoundaries=0,
npoly = self.npoly,
vertx = v1, verty=v2,
norms = self.n)
if self.getSharpColorBoundaries() in [True, 1]:
self.cyldraw = self.cyldrawWithSharpColorBoundaries
else:
self.cyldraw = self.cyldrawWithInterpolatedColors
if self.oneRadius == viewerConst.NO:
radii = self.vertexSet.radii.array
else:
radius = self.vertexSet.radii.array[0]
pickName = 0
for i in xrange(len(self.faceSet.faces.array)):
#print 'CYLINDERS', i, '********************************',
for j in xrange(len(self.faceSet.faces.array[i])-1):
vi1 = self.faceSet.faces.array[i][j]
vi2 = self.faceSet.faces.array[i][j+1]
if fp:
fpp1 = [None,None,None,None,None]
fpp2 = [None,None,None,None,None]
for m in (0,1,2,3,4):
if fp.binding[m] == viewerConst.PER_VERTEX:
fpp1[m] = fp.prop[m][vi2]
fpp1[m] = array(fpp1[m],copy=1)
fpp2[m] = fp.prop[m][vi1]
fpp2[m] = array(fpp2[m],copy=1)
elif fp.binding[m] == viewerConst.PER_PART:
fpp2[m] = fpp1[m] = fp.prop[m][i]
fpp1[m] = array(fpp1[m],copy=1)
fpp2[m] = array(fpp2[m],copy=1)
else:
fpp1 = fpp2 = None
if bp and not self.frontAndBack:
bpp1 = [None,None,None,None,None]
bpp2 = [None,None,None,None,None]
for m in (0,1,2,3,4):
if bp.binding[m] == viewerConst.PER_VERTEX:
bpp1[m] = bp.prop[m][vi2]
bpp1[m] = array(bpp1[m],copy=1)
bpp2[m] = bp.prop[m][vi1]
bpp2[m] = array(bpp2[m],copy=1)
elif bp.binding[m] == viewerConst.PER_PART:
bpp2[m] = bpp1[m] = bp.prop[m][i]
bpp1[m] = array(bpp1[m],copy=1)
bpp2[m] = array(bpp2[m],copy=1)
else:
bpp1 = bpp2 = None
GL.glPushName(pickName)
if len(self.highlight) > 0:
if self.oneRadius:
self.cyldraw(c[vi1], c[vi2],
radius, radius,
fpp1, bpp1, fpp2, bpp2, face,
highlightX=self.highlight[vi1],
highlightY=self.highlight[vi2])
else:
if vi1 < vi2:
self.cyldraw(c[vi1], c[vi2],
radii[vi2], radii[vi1],
fpp1, bpp1, fpp2, bpp2, face,
highlightX=self.highlight[vi1],
highlightY=self.highlight[vi2])
else:
self.cyldraw(c[vi1], c[vi2],
radii[vi1], radii[vi2],
fpp1, bpp1, fpp2, bpp2, face,
highlightX=self.highlight[vi1],
highlightY=self.highlight[vi2])
else:
if self.oneRadius:
self.cyldraw(c[vi1], c[vi2],
radius, radius,
fpp1, bpp1, fpp2, bpp2, face)
else:
if vi1 < vi2:
self.cyldraw(c[vi1], c[vi2],
radii[vi2], radii[vi1],
fpp1, bpp1, fpp2, bpp2, face)
else:
self.cyldraw(c[vi1], c[vi2],
radii[vi1], radii[vi2],
fpp1, bpp1, fpp2, bpp2, face)
GL.glPopName()
pickName = pickName +1
#print 'CYLINDERS done'
return 1
def cyldrawWithSharpColorBoundaries(self,
x, y, radx, rady,
colxf=None, colxb=None,
colyf=None, colyb=None, face=None,
highlightX=0, highlightY=0):
# determine scale and rotation of template
import math
sz=0.0
for i in (0,1,2):
sz=sz+(x[i]-y[i])*(x[i]-y[i])
if sz <= 0.0: return
sz = math.sqrt(sz)
sz2 = sz * .5
valueCos = (y[2]-x[2])/sz
valueCos = min(valueCos, 1)
valueCos = max(valueCos, -1)
rx = -180.0*math.acos(valueCos)/math.pi
dx = y[0]-x[0]
dy = y[1]-x[1]
if math.fabs(dx) < 0.00001 and math.fabs(dy) < 0.00001:
rz = 0.0
else:
rz = -180.0*math.atan2(dx,dy)/math.pi
GL.glPushMatrix()
GL.glTranslatef(float(x[0]),float(x[1]),float(x[2]))
if rz<=180.0 and rz >=-180.0:
GL.glRotatef(float(rz), 0., 0., 1.)
GL.glRotatef(float(rx), 1., 0., 0.)
if colyf:
for m in (0,1,2,3,4):
if colyf[m] is not None:
glMaterialWithCheck( face, viewerConst.propConst[m],
colyf[m], check=self.checkMat)
if colyf[1] is not None:
GL.glColor4fv(colyf[1])
if colyb and face!=GL.GL_FRONT_AND_BACK:
for m in (0,1,2,3,4):
if colyb[m] is not None:
self.checkMat = 0
glMaterialWithCheck( GL.GL_BACK,
viewerConst.propConst[m],
colyb[m], check=self.checkMat)
# this tests (colxf==colyf)
self.checkMat = 1
idem = (highlightX == highlightY)
if idem is True:
if colxf is None:
if colyf is not None:
idem = False
else:
if colyf is None:
idem = False
else:
lencol = len(colxf)
if lencol != len(colyf):
idem = False
else:
for i in range(lencol):
if colxf[i] is not None:
if bool(numpy.alltrue(colxf[i] == colyf[i])) is False:
idem = False
break
if idem is True:
if colxb is None:
if colyb is not None:
idem = False
else:
if colyb is None:
idem = False
else:
lencol = len(colxb)
if lencol != len(colyb):
idem = False
else:
for i in range(lencol):
if colxb[i] is not None:
if bool(numpy.alltrue(colxb[i] == colyb[i])) is False:
idem = False
break
quality = self.quality * 5
if idem is True:
if highlightX != 0:
GL.glStencilFunc(GL.GL_ALWAYS, 1, 1)
solidCylinder(float(rady), float(radx), sz, quality, 1, self.invertNormals)
GL.glStencilFunc(GL.GL_ALWAYS, 0, 1)
else:
solidCylinder(float(rady), float(radx), sz, quality, 1, self.invertNormals)
else:
midRadius = (radx + rady) * .5
if highlightX != 0:
GL.glStencilFunc(GL.GL_ALWAYS, 1, 1)
solidCylinder(midRadius, float(radx), sz2, quality, 1, self.invertNormals)
GL.glStencilFunc(GL.GL_ALWAYS, 0, 1)
else:
solidCylinder(midRadius, float(radx), sz2, quality, 1, self.invertNormals)
GL.glTranslatef(0, 0, float(sz2))
if colxf:
for m in (0,1,2,3,4):
if colxf[m] is not None:
glMaterialWithCheck( face, viewerConst.propConst[m],
colxf[m], check=self.checkMat )
if colxf[1] is not None:
GL.glColor4fv(colxf[1])
if colxb and face!=GL.GL_FRONT_AND_BACK:
for m in (0,1,2,3,4):
if colxb[m] is not None:
glMaterialWithCheck( GL.GL_BACK,
viewerConst.propConst[m],
colxb[m], check=self.checkMat )
if highlightY != 0:
GL.glStencilFunc(GL.GL_ALWAYS, 1, 1)
solidCylinder(float(rady), midRadius, sz2, quality, 1, self.invertNormals)
GL.glStencilFunc(GL.GL_ALWAYS, 0, 1)
else:
solidCylinder(float(rady), midRadius, sz2, quality, 1, self.invertNormals)
GL.glPopMatrix()
def cyldrawWithInterpolatedColors(self,
x, y, radx, rady, colxf=None, colxb=None,
colyf=None, colyb=None, face=None, **kw):
# draw a cylinder going from x to y with radii rx, and ry and materials
# colxf and colxb for front and back mterial in x
# colyf and colyb for front and back mterial in y
# face can be GL_FRONT_AND_BACK or something else
# determine scale and rotation of template
import math
sz=0.0
for i in (0,1,2): sz=sz+(x[i]-y[i])*(x[i]-y[i])
if sz <= 0.0: return
sz = math.sqrt(sz)
valueCos = (y[2]-x[2])/sz
valueCos = min(valueCos, 1)
valueCos = max(valueCos, -1)
rx = -180.0*math.acos(valueCos)/math.pi
dx = y[0]-x[0]
dy = y[1]-x[1]
if math.fabs(dx) < 0.00001 and math.fabs(dy) < 0.00001:
rz = 0.0
else:
rz = -180.0*math.atan2(dx,dy)/math.pi
GL.glPushMatrix()
GL.glTranslatef(float(x[0]),float(x[1]),float(x[2]))
if rz<=180.0 and rz >=-180.0: GL.glRotatef(float(rz), 0., 0., 1.)
GL.glRotatef(float(rx), 1., 0., 0.)
# draw cylinder
GL.glBegin(GL.GL_QUAD_STRIP)
for i in range(self.npoly+1):
if self.invertNormals:
GL.glNormal3fv(-self.n[i])
else:
GL.glNormal3fv(self.n[i])
if colxf:
for m in (0,1,2,3,4):
if colxf[m] is not None:
#print "colxf[m]",type(colxf[m])
#print 'AAAAA', colxf[m]
glMaterialWithCheck( face, viewerConst.propConst[m],
colxf[m], check=self.checkMat )
if colxf[1] is not None:
GL.glColor4fv(colxf[1])
if colxb and face!=GL.GL_FRONT_AND_BACK:
for m in (0,1,2,3,4):
if colxb[m] is not None:
glMaterialWithCheck( GL.GL_BACK,
viewerConst.propConst[m],
colxb[m], check=self.checkMat )
vx = self.v[i][0]
GL.glVertex3f(float(vx[0]*radx), float(vx[1]*radx), float(vx[2]*sz))
if colyf:
for m in (0,1,2,3,4):
if colyf[m] is not None:
#print 'BBBBB', colyf[m]
glMaterialWithCheck( face, viewerConst.propConst[m],
colyf[m], check=self.checkMat )
if colyf[1] is not None:
GL.glColor4fv(colyf[1])
if colyb and face!=GL.GL_FRONT_AND_BACK:
for m in (0,1,2,3,4):
if colyb[m] is not None:
glMaterialWithCheck( GL.GL_BACK,
viewerConst.propConst[m],
colyb[m], check=self.checkMat )
vy = self.v[i][1]
GL.glVertex3f(float(vy[0]*rady), float(vy[1]*rady), float(vy[2]*sz))
GL.glEnd()
GL.glPopMatrix()
def _cylinderTemplate(self):
npoly = self.quality * 5
v = Numeric.zeros( ((npoly+1),2,3), 'f')
n = Numeric.zeros( ((npoly+1),3), 'f')
self.npoly = npoly
a = -math.pi # starting angle
d = 2*math.pi / npoly # increment
for i in range(npoly+1):
n[i][0] = v[i][0][0] = v[i][1][0] = math.cos(a)
n[i][1] = v[i][0][1] = v[i][1][1] = math.sin(a)
n[i][2] = v[i][1][2] = 0.0
v[i][0][2] = 1.0
a=a+d
return v,n
def _cylinderTemplateDaniel(self, quality=None):
""" This template doesn't put the last point over the first point
as done in the other template. In addition, it computes and
returns face indices. I don't compute normals
This template is used by asIndexedyPolygons()"""
if quality is None:
quality = self.quality * 5
import numpy.oldnumeric as Numeric, math
v = Numeric.zeros( ((quality),2,3), 'f')
n = Numeric.zeros( ((quality),3), 'f')
f = []
a = -math.pi # starting angle
d = 2*math.pi / quality # increment
# compute vertices
for i in range(quality):
v[i][0][0] = v[i][1][0] = math.cos(a)
v[i][0][1] = v[i][1][1] = math.sin(a)
v[i][1][2] = 0.0
v[i][0][2] = 1.0
a=a+d
lV = len(v)
# compute template cylinder faces
for i in range(lV-1): # cylinder body
f.append([i, i+1, lV+i+1])
f.append([lV+i+1, lV+i, i])
f.append([lV-1, 0, lV]) #close last point to first
f.append([lV-1, lV, lV+i+1])
for i in range(lV-2): # cylinder bottom cap
f.append([0, i+2 ,i+1])
for i in range(lV-2): # cylinder top cap
f.append([lV+i+1, lV+i+2, lV])
return v, f
def asIndexedPolygons(self, run=1, quality=None, radius=None, **kw):
""" run=0 returns 1 if this geom can be represented as an
IndexedPolygon and None if not. run=1 returns the IndexedPolygon
object."""
#print "Cylinders.asIndexedPolygons", quality
if run==0:
return 1 # yes, I can be represented as IndexedPolygons
import numpy.oldnumeric as Numeric, math
from mglutil.math.transformation import Transformation
if quality in [1,2,3,4,5]:
quality = quality
elif quality < 0 and self.quality in [2,3,4,5]:
quality = self.quality - 2
else:
quality = self.quality - 1
quality *= 5
# make a copy of the cylinderTemplate
tmpltVertices, tmpltFaces = self._cylinderTemplateDaniel(\
quality=quality)
centers = self.vertexSet.vertices.array
faces = self.faceSet.faces.array
tmpltVertices = Numeric.array(tmpltVertices).astype('f')
tmpltFaces = Numeric.array(tmpltFaces).astype('f')
addToFaces = Numeric.ones((tmpltFaces.shape)) * 2*len(tmpltVertices)
VV = [] # this list stores all vertices of all cylinders
FF = [] # this list stores all faces of all cylinders
# now loop over all cylinders in self
for index in xrange(len(faces)):
# tv temporarily stores the transformed unit cylinder vertices
tv = tmpltVertices.__copy__()
pt0 = centers[faces[index][0]] # bottom of cylinder
pt1 = centers[faces[index][1]] # top of cylinder
# get radius for cylinder
if radius is not None:
radx = rady = radius #override radii
elif self.oneRadius:
radx = rady = radius = self.vertexSet.radii.array[0]
else:
radx = self.vertexSet.radii.array[faces[index][1]]
rady = self.vertexSet.radii.array[faces[index][0]]
# determine scale and rotation of current cylinder
sz=0.0
for nbr in (0,1,2): sz=sz+(pt0[nbr]-pt1[nbr])*(pt0[nbr]-pt1[nbr])
if sz <= 0.0: return
sz = math.sqrt(sz)
rx = -180.0*math.acos((pt1[2]-pt0[2])/sz)/math.pi
dx = pt1[0]-pt0[0]
dy = pt1[1]-pt0[1]
if math.fabs(dx) < 0.00001 and math.fabs(dy) < 0.00001:
rz = 0.0
else:
rz = -180.0*math.atan2(dx,dy)/math.pi
# prepare rotations matrices of current cylinder
Rx = Transformation(quaternion=[1,0,0,rx])
if rz<=180.0 and rz >=-180.0:
Rz = Transformation(quaternion=[0,0,1,rz])
R = Rz * Rx
else: R = Rx
r = R.getMatrix()
k = 0
for v in tmpltVertices: # I DO NOT use Numeric.matrixmultiply
# here, in order to gain significant speed
v0x, v0y, v0z = v[0] # saves some lookups
v1x, v1y, v1z = v[1]
tv[k][0]=\
([r[0][0]*v0x*radx+r[1][0]*v0y*radx+r[2][0]*v0z*sz+pt0[0],
r[0][1]*v0x*radx+r[1][1]*v0y*radx+r[2][1]*v0z*sz+pt0[1],
r[0][2]*v0x*radx+r[1][2]*v0y*radx+r[2][2]*v0z*sz+pt0[2]])
tv[k][1]=\
([r[0][0]*v1x*rady+r[1][0]*v1y*rady+r[2][0]*v1z+pt0[0],
r[0][1]*v1x*rady+r[1][1]*v1y*rady+r[2][1]*v1z+pt0[1],
r[0][2]*v1x*rady+r[1][2]*v1y*rady+r[2][2]*v1z+pt0[2]])
k = k + 1
ctv = None
ctv = Numeric.concatenate( (tv[:,1], tv[:,0] ) )
# now add the data to the big lists
VV.extend(list(ctv))
FF.extend(list(tmpltFaces))
# increase face indices by lenght of vertices
tmpltFaces = tmpltFaces + addToFaces
VV = Numeric.array(VV).astype('f')
FF = Numeric.array(FF).astype('f')
# FIXME: should I compute normals?
# now we can build the IndexedPolygon geom
from DejaVu.IndexedPolygons import IndexedPolygons
cylGeom = IndexedPolygons("cyl", vertices=VV,
faces=FF, visible=1,
invertNormals=self.invertNormals)
# copy Cylinders materials into cylGeom
matF = self.materials[GL.GL_FRONT]
matB = self.materials[GL.GL_BACK]
cylGeom.materials[GL.GL_FRONT].binding = matF.binding[:]
cylGeom.materials[GL.GL_FRONT].prop = matF.prop[:]
cylGeom.materials[GL.GL_BACK].binding = matB.binding[:]
cylGeom.materials[GL.GL_BACK].prop = matB.prop[:]
# if binding per vertex:
if cylGeom.materials[GL.GL_FRONT].binding[1] == viewerConst.PER_VERTEX:
newprop = []
props = cylGeom.materials[GL.GL_FRONT].prop[1]
for i in xrange(len(faces)):
for j in xrange(len(faces[i])-1):
vi1 = self.faceSet.faces.array[i][j]
vi2 = self.faceSet.faces.array[i][j+1]
colx = props[vi2]
coly = props[vi1]
# add second color to first half of cyl vertices
for k in range(len(tmpltVertices)):
newprop.append(coly)
# add first color to second half of cyl vertices
for l in range(len(tmpltVertices)):
newprop.append(colx)
cylGeom.materials[GL.GL_FRONT].prop[1] = newprop
# and finally...
#print "Cylinders.asIndexedPolygons out", quality
return cylGeom
class CylinderArrows(Cylinders):
"""Class for sets of 3D arrows draw using cylinders"""
keywords = Cylinders.keywords + [
'headLength',
'headRadius',
]
def __init__(self, name=None, check=1, **kw):
if __debug__:
if check:
apply( checkKeywords, (name,self.keywords), kw)
apply( Cylinders.__init__, (self, name, 0), kw)
self.headLength = 1.
self.headRadius = 2.
def Draw(self):
# for some reason, under Mac OS X, if I do not always set he material
# only the first cylinder gets the right color (MS)
if sys.platform=='darwin' \
or DejaVu.preventIntelBug_BlackTriangles is True:
self.checkMat = False
else:
self.checkMat = True
if len(self.vertexSet.vertices) == 0:
return
if self.inheritMaterial:
fp = None
bp = None
face = None
else:
mat = self.materials[GL.GL_FRONT]
rmat = self.realFMat
bind = [10,10,10,10]
for pInd in range(4):
bind[pInd], rmat.prop[pInd] = mat.GetProperty(pInd)
rmat.prop[4] = mat.prop[4]
rmat.prop[5] = mat.prop[5]
rmat.binding[:4] = bind
rmat.binding[4:] = rmat.binding[4:]
fp = rmat
# fp = self.materials[GL.GL_FRONT]
if fp:
if self.frontAndBack:
face = GL.GL_FRONT_AND_BACK
bp = None
else:
face = GL.GL_FRONT
mat = self.materials[GL.GL_BACK]
rmat = self.realBMat
bind = [10,10,10,10]
for pInd in range(4):
bind[pInd], rmat.prop[pInd]=mat.GetProperty(pInd)
rmat.prop[4] = mat.prop[4]
rmat.prop[5] = mat.prop[5]
rmat.binding[:4] = bind
rmat.binding[4:] = rmat.binding[4:]
bp = rmat
c = self.vertexSet.vertices.array
if self.oneRadius == viewerConst.NO:
radii = self.vertexSet.radii.array
else:
radius = self.vertexSet.radii.array[0]
pickName = 0
for i in xrange(len(self.faceSet.faces.array)):
#print 'CYLINDERS', i, '********************************'
for j in xrange(len(self.faceSet.faces.array[i])-1):
vi1 = self.faceSet.faces.array[i][j]
vi2 = self.faceSet.faces.array[i][j+1]
if fp:
fpp1 = [None,None,None,None,None]
fpp2 = [None,None,None,None,None]
for m in (0,1,2,3,4):
if fp.binding[m] == viewerConst.PER_VERTEX:
fpp1[m] = fp.prop[m][vi2]
fpp1[m] = array(fpp1[m],copy=1)
fpp2[m] = fp.prop[m][vi1]
fpp2[m] = array(fpp2[m],copy=1)
elif fp.binding[m] == viewerConst.PER_PART:
fpp2[m] = fpp1[m] = fp.prop[m][i]
fpp1[m] = array(fpp1[m],copy=1)
fpp2[m] = array(fpp2[m],copy=1)
else:
fpp1 = fpp2 = None
if bp and not self.frontAndBack:
bpp1 = [None,None,None,None,None]
bpp2 = [None,None,None,None,None]
for m in (0,1,2,3,4):
if bp.binding[m] == viewerConst.PER_VERTEX:
bpp1[m] = bp.prop[m][vi2]
bpp1[m] = array(bpp1[m],copy=1)
bpp2[m] = bp.prop[m][vi1]
bpp2[m] = array(bpp2[m],copy=1)
elif bp.binding[m] == viewerConst.PER_PART:
bpp2[m] = bpp1[m] = bp.prop[m][i]
bpp1[m] = array(bpp1[m],copy=1)
bpp2[m] = array(bpp2[m],copy=1)
else:
bpp1 = bpp2 = None
GL.glPushName(pickName)
# compute point at base of cone
vect = [c[vi2][0]-c[vi1][0],
c[vi2][1]-c[vi1][1],
c[vi2][2]-c[vi1][2]]
norm = 1./math.sqrt(vect[0]*vect[0]+vect[1]*vect[1]+vect[2]*vect[2])
vect = [vect[0]*norm, vect[1]*norm, vect[2]*norm]
headBase = [c[vi2][0]-self.headLength*vect[0],
c[vi2][1]-self.headLength*vect[1],
c[vi2][2]-self.headLength*vect[2]]
if self.oneRadius:
# cylinder
self.cyldraw(c[vi1], headBase,
radius, radius,
fpp1, bpp1, fpp2, bpp2, face)
# cone
self.cyldraw(headBase, c[vi2],
0.0, radius*self.headRadius,
fpp1, bpp1, fpp2, bpp2, face)
else:
if vi1 < vi2:
self.cyldraw(c[vi1], c[vi2],
radii[vi2], radii[vi1],
fpp1, bpp1, fpp2, bpp2, face)
else:
self.cyldraw(c[vi1], c[vi2],
radii[vi1], radii[vi2],
fpp1, bpp1, fpp2, bpp2, face)
GL.glPopName()
pickName = pickName +1
#print 'CYLINDERS done'
return 1
```
#### File: DejaVu/scenarioInterface/actor.py
```python
from Scenario2.actor import Actor, CustomActor
from Scenario2.datatypes import DataType
from Scenario2.interpolators import Interpolator, FloatScalarInterpolator,\
BooleanInterpolator
from SimPy.Simulation import now
import numpy.oldnumeric as Numeric
## class ActionWithRedraw(Action):
## # subclass Action to have these actions set a redraw flag in the director
## # so that the redraw process only triggers a redraw if something changed
## def __init__(self, *args, **kw):
## Action.__init__(self, *args, **kw)
## self.postStep_cb = (self.setGlobalRedrawFlag, (), {})
## def setGlobalRedrawFlag(self):
## #print 'setting needs redraw at', now(), self._actor().name
## self._actor()._maa().needsRedraw = True
class RedrawActor(Actor):
def __init__(self, vi, *args, **kw):
Actor.__init__(self, "redraw", vi)
#self.addAction( Action() )
self.visible = False
self.recording = False
self.scenarioname = "DejaVuScenario"
self.guiVar = None
def setValueAt(self, frame=None, off=0):
self.setValue()
def setValue(self, value=None):
needsRedraw = True
if self._maa:
if self._maa().needsRedraw == False:
needsRedraw = False
if self._maa()._director and self._maa()._director().needsRedraw:
needsRedraw = True
if not needsRedraw: return
#print "oneRedraw from redraw actor"
self.object.OneRedraw()
# handle recording a frame if need be
camera = self.object.currentCamera
if hasattr(camera, 'videoRecordingStatus'):
if camera.videoRecordingStatus == 'recording':
camera.recordFrame()
def onAddToDirector(self):
gui = self._maa().gui
if gui:
try:
from DejaVu.Camera import RecordableCamera
isrecordable = True
except:
isrecordable = False
if isrecordable:
camera = self.object.currentCamera
if isinstance(camera, RecordableCamera):
gui.createRecordMovieButton()
def startRecording(self, file):
camera = self.object.currentCamera
camera.setVideoOutputFile(file)
camera.setVideoParameters()
camera.videoRecordingStatus = 'recording'
def stopRecording(self):
self.object.currentCamera.stop()
def clone(self):
return RedrawActor( self.object )
def getActorName(object, propname):
# create a name for object's actor
objname = object.name
import string
if hasattr(object, "fullName"):
names = object.fullName.split("|")
if len(names)> 1:
objname = string.join(names[1:], ".")
if objname.count(" "):
# remove whitespaces from the object's name
objname = string.join(objname.split(), "")
return "%s.%s"%(objname, propname)
class DejaVuActor(CustomActor):
"""
class for DejaVu actors.
initialValue= None - initial value of the object's attribute (object.name),
interp = None - interpolator class,
setFunction = None - function to set the value on the object,
if None, object.Set(name=value) will be used
setMethod: method of the object to be called at each time step.
The function will be called using obj.method(value)
getFunction = None - function that can be called to get the
current value of the attribute (object.name)
The function and its arguments have to be specified as a
3-tuple (func, *args, **kw). It will be called using
func(*(object,)+args), **kw) if it is a function
or func(*args, **kw) if it is a method;
if None, getattr(object, name) will be used to get the value
to set the value and getattr(geom, name) to get the value
"""
def __init__(self, name, object, initialValue=None, datatype=None,
interp=None, setFunction=None, setMethod=None,
getFunction=None):
assert isinstance(name, str)
self.varname = name
if not getFunction:
if hasattr(object, name):
getFunction = (getattr, (name,), {})
actorname = getActorName(object, name)
## objname = object.name
## if objname.count(" "):
## # remove whitespaces from the object's name
## import string
## objname = string.join(objname.split(), "")
CustomActor.__init__(self, actorname, object,
initialValue, datatype, interp, setFunction=setFunction, setMethod=setMethod, getFunction=getFunction)
if self.hasGetFunction:
self.recording = True
self.guiVar = None
self.scenarioname = "DejaVuScenario"
def setValue(self, value):
if self.setFunction:
self.setFunction( *(self, value) )
elif self.setMethod:
self.setMethod(value)
else:
self.object.Set( **{self.varname:value} )
def setValueAt(self, frame, off=0):
#print 'GGGGGGGGGGGGGGG', self.name
value = self.actions.getValue(frame-off)
if value != 'Nothing There':
self.setValue(value)
maa = self._maa()
maa.needsRedraw = True
#print 'HHHHHHHHHHHHHHHHHH', maa.name
## if maa._director is not None:
## print maa._director(), 'LLLLLLLLLLLLLLLL'
## maa._director().needsRedraw = True
def clone(self):
if self.setMethod is not None:
setMethod = self.setMethod.__name__
else:
setMethod = None
datatype = None
if self.datatype is not None:
datatype = self.datatype.__class__
newActor = self.__class__(
self.varname, self.object, initialValue=self.initialValue,
datatype=datatype, interp=self.interp,
setFunction=self.setFunction, setMethod=setMethod)
newActor.getFuncTuple = self.getFuncTuple
if self.getFuncTuple:
newActor.hasGetFunction = True
newActor.behaviorList.easeIn = self.behaviorList.easeIn
newActor.behaviorList.easeOut = self.behaviorList.easeOut
newActor.behaviorList.constant = self.behaviorList.constant
return newActor
from interpolators import MaterialInterpolator
from Scenario2.datatypes import FloatType, IntType, BoolType,IntVectorType,\
FloatVectorType, IntVarType, FloatVarType, VarVectorType
class DejaVuCameraActor(DejaVuActor):
def __init__(self, name, object, initialValue=None, datatype=DataType,
interp=BooleanInterpolator, setFunction=None,
setMethod=None, getFunction=None):
assert hasattr(object, 'viewer')
self.cameraind = 0
for i, c in enumerate(object.viewer.cameras):
if c == object:
self.cameraind=i
break
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp, setFunction=setFunction, setMethod=setMethod,
getFunction=getFunction)
def getCameraObject(self):
vi = self.object.viewer
camera = vi.cameras[self.cameraind]
if camera != self.object:
self.object = camera
if self.setMethod is not None:
method = getattr(self.object, self.setMethod.__name__)
self.setMethod = method
return camera
def setValue(self, value):
self.getCameraObject()
DejaVuActor.setValue(self, value)
def getValueFromObject(self):
self.getCameraObject()
return DejaVuActor.getValueFromObject(self)
class DejaVuGeomVisibilityActor(DejaVuActor):
"""
Actor to set geometry visibility flag
when set to 1 we need to make sure each parent's visibility flag is 1
else the object will not appear
"""
def __init__(self, name, object, initialValue=None, datatype=DataType,
interp=BooleanInterpolator, setFunction=None,
setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=self.getValue)
def setValue(self, value):
obj = self.object
self.object.Set( visible = value)
if value: # set all parents visibility to 1
while obj.parent:
obj = obj.parent
obj.Set( visible=value )
#else:
# for child in obj.AllObjects():
# if child!=self:
# child.Set( visible = value)
def getValue(self):
# MS: maybe we should return 0 if 1 parent is not visible
return self.object.visible
class DejaVuGeomEnableClipPlaneActor(DejaVuActor):
"""
Actor to enable clipping plane for a geometry
"""
def __init__(self, name, object, initialValue=None, datatype=DataType,
interp=None, setFunction=None,
setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=None)
def setValue(self, value):
if not value:
return
geom = self.object
for clip in value:
assert len(clip) == 4
if clip[3] == True:
#print "addclipplane:", clip[0], clip[0].num
geom.AddClipPlane(clip[0], clip[1], clip[2])
else:
#print "removeClipPlane:", clip[0], clip[0].num
geom.RemoveClipPlane(clip[0])
def getValue(self):
geom = self.object
val = []
clip = []
inh = False
if len(geom.clipP): clip = geom.clipP
elif len(geom.clipPI):
clip = geom.clipPI
inh = True
for cp in clip:
val.append([cp, geom.clipSide[cp.num], inh, True])
return val
class DejaVuMaterialActor(DejaVuActor):
def __init__(self, name, object, initialValue=None, datatype=DataType,
interp=MaterialInterpolator, setFunction=None, setMethod=None, getFunction=None, mode="front"):
self.mode = mode
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=self.getValue)
self.hasGetFunction = True
def setValue(self, value):
object = self.object
## i=0
## for v,name in zip(value, ('ambi', 'emis', 'spec', 'shini')):
## #if self.activeVars[i]:
## object.Set(propName=name, materials=v, transparent='implicit', redo=1)
## i +=1
mat = [ value[0], None, value[1], value[2], value[3], None]
mask = [1, 0, 1, 1, 1, 0]
if self.mode == "front":
object.Set(rawMaterialF=mat, matMask=mask,transparent='implicit', redo=1)
else:
object.Set(rawMaterialB=mat, matMask=mask,transparent='implicit', redo=1)
def getValue(self):
if self.mode == "front":
mat = self.object.materials[1028].prop
else:
mat = self.object.materials[1029].prop
return [mat[0], mat[2], mat[3], mat[4]]
def compareValues(self, oldval, newval):
vvt = VarVectorType()
fvt = FloatVectorType()
for i in range(3):
if not vvt.isEqual(oldval[i], newval[i]):
return False
if not fvt.isEqual(oldval[3], newval[3]):
return False
return True
def clone(self):
newactor = DejaVuActor.clone(self)
newactor.mode = self.mode
newactor.hasGetFunction = self.hasGetFunction
return newactor
from Scenario2.interpolators import FloatVectorInterpolator, VarVectorInterpolator
class DejaVuScissorActor(DejaVuActor):
""" This actor manages resizing of DejaVu object's scissor"""
def __init__(self, name, object, initialValue=None, datatype=FloatVectorType,
interp=FloatVectorInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype, interp, getFunction=self.getValue)
self.hasGetFunction = True
self.varnames = ['scissorH', 'scissorW', 'scissorX', 'scissorY']
self.activeVars = ['scissorH', 'scissorW', 'scissorX', 'scissorY']
def setValue(self, value):
object = self.object
kw = {}
for i, var in enumerate (self.varnames):
if var in self.activeVars:
kw[var] = value[i]
object.Set(**kw)
def getValue(self):
obj = self.object
return [float(obj.scissorH), float(obj.scissorW),
float(obj.scissorX), float(obj.scissorY)]
from Scenario2.interpolators import RotationInterpolator
from mglutil.math.transformation import UnitQuaternion, Transformation
from mglutil.math.rotax import mat_to_quat
from DejaVu.Camera import Camera
from math import cos, acos, sin, pi
from Scenario2.interpolators import matToQuaternion, quatToMatrix
class DejaVuRotationActor(DejaVuActor):
"""
This actor manages rotation of DejaVu object by setting the rotation
"""
def __init__(self, name, object, initialValue=None, datatype=FloatVectorType,
interp=RotationInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype, interp, getFunction=self.getValue)
self.hasGetFunction = True
## def setValue(self, value):
## object = self.object
## q = (value[0], Numeric.array(value[1:], 'f'))
## t = Transformation(quaternion=q)
## object.Set(rotation = t.getRotMatrix(shape=(16,), transpose=1))
## if isinstance(object, Camera):
## object.Redraw()
## def getValue(self):
## obj = self.object
## value = self.object.rotation
## if len(value)==16:
## q = UnitQuaternion(mat_to_quat(value))
## value = [q.real, q.pure[0], q.pure[1], q.pure[2]]
## #print "in DejaVuRotationActor.getValue: ", value
## return value
def setValue(self, value):
object = self.object
mat = quatToMatrix(value)
#object._setRotation(mat)
object.Set(rotation=mat)
if isinstance(object, Camera):
object.Redraw()
def getValue(self):
mat = self.object.rotation
quat = matToQuaternion(mat)
return quat
class DejaVuConcatRotationActor(DejaVuRotationActor):
"""
This actor manages rotation of DejaVu object by concatenating the rotation
"""
def __init__(self, name, object, initialValue=None,
datatype=FloatVectorType,
interp=RotationInterpolator, setFunction=None,
setMethod=None, getFunction=None):
DejaVuRotationActor.__init__(
self, name, object, initialValue, datatype, interp,
getFunction=self.getValue)
self.hasGetFunction = True
def setValue(self, value):
object = self.object
mat = quatToMatrix(value)
object.ConcatRotation(mat)
if isinstance(object, Camera):
object.Redraw()
from mglutil.math.rotax import rotax
import math
from DejaVu.scenarioInterface.interpolators import RotationConcatInterpolator
class DejaVuAxisConcatRotationActor(DejaVuActor):
"""
This actor manages rotation of DejaVu object by concatenating the rotation
"""
def __init__(self, name, object, initialValue=None,
datatype=FloatVectorType, axis=(0,1,0),
interp=RotationConcatInterpolator, setFunction=None,
setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp)
self.axis = axis
self.hasGetFunction = False
def setValue(self, value):
#print 'Rotate by', value
mat = rotax( (0,0,0), self.axis, value*math.pi/180.)
object = self.object
object.ConcatRotation(mat.flatten())
if isinstance(object, Camera):
object.Redraw()
def clone(self):
newactor = DejaVuActor.clone(self)
newactor.axis = self.axis
newactor.hasGetFunction = self.hasGetFunction
return newactor
class DejaVuClipZActor(DejaVuCameraActor):
""" This actor manages the near and far camera's atributes"""
def __init__(self, name, object, initialValue=None, datatype=FloatVectorType,
interp=FloatVectorInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuCameraActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=self.getValue)
self.hasGetFunction = True
self.varnames = ['near', 'far']
self.activeVars = ['near', 'far']
def setValue(self, value):
camera = self.getCameraObject()
kw = {}
for i, var in enumerate (self.varnames):
if var in self.activeVars:
kw[var] = value[i]
camera.Set(**kw)
camera.Redraw()
def getValue(self):
c = self.getCameraObject()
return Numeric.array([c.near, c.far,], "f")
class DejaVuFogActor(DejaVuCameraActor):
""" This actor manages the start and end atributes of camera's fog"""
def __init__(self, name, object, attr='start', initialValue=None, datatype=FloatType,
interp=FloatScalarInterpolator, setFunction=None, setMethod=None, getFunction=None):
from DejaVu.Camera import Fog
if isinstance(object, Fog):
assert object.camera is not None
object = object.camera()
self.attr = attr
DejaVuCameraActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=self.getValue)
self.hasGetFunction = True
def setValue(self, value):
camera = self.getCameraObject()
kw = {self.attr: value}
camera.fog.Set(**kw)
#camera.Redraw()
def getValue(self):
c = self.getCameraObject()
return getattr(c.fog, self.attr)
def clone(self):
newactor = DejaVuCameraActor.clone(self)
newactor.attr = self.attr
return newactor
from Scenario2.interpolators import FloatVarScalarInterpolator
from interpolators import LightColorInterpolator
class DejaVuLightColorActor(DejaVuActor):
def __init__(self, name, object, initialValue=None, datatype = DataType, interp = LightColorInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype, interp,
getFunction=self.getValue)
self.varnames = ['ambient', 'diffuse', 'specular']
self.activeVars = ['ambient', 'diffuse', 'specular']
self.hasGetFunction = True
def setValue(self, value):
object = self.object
kw = {}
for v,name in zip(value, ('ambient', 'diffuse', 'specular')):
if name in self.activeVars:
kw[name] = v
object.Set(**kw)
def getValue(self):
obj = self.object
return [obj.ambient, obj.diffuse, obj.specular]
def compareValues(self, oldval, newval):
fvt = FloatVectorType()
for i in range(3):
if not fvt.isEqual(oldval[i], newval[i]):
return False
return True
class DejaVuSpheresRadiiActor(DejaVuActor):
""" This actor manages the raduis attribute of spheres"""
def __init__(self, name, object, initialValue=None, datatype=FloatVarType,
interp=FloatVarScalarInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue,
datatype=datatype, interp=interp,
getFunction=self.getValue)
self.hasGetFunction = True
self.varnames = ['radii']
self.activeVars = ['radii']
def setValue(self, value):
object = self.object
object.Set(radii=value)
def getValue(self):
object = self.object
if object.oneRadius:
return object.radius
else:
return object.vertexSet.radii.array.ravel()
from interpolators import TransformInterpolator
class DejaVuTransformationActor(DejaVuActor):
def __init__(self, name, object, initialValue=None, datatype=DataType,
interp=TransformInterpolator, setFunction=None, setMethod=None, getFunction=None):
DejaVuActor.__init__(self, name, object, initialValue, datatype,
interp, getFunction=self.getValue)
self.hasGetFunction = True
def setValue(self, value):
object = self.object
rotation = quatToMatrix(value[0])
redo = False
if object != object.viewer.rootObject:
# need to rebuild display list if the object is not root
redo = True
object.Set(rotation=rotation,translation = value[1],scale = value[2],
pivot = value[3], redo=redo)
def getValue(self):
obj = self.object
rotation = matToQuaternion(obj.rotation)
return [rotation, obj.translation[:], obj.scale[:], obj.pivot[:] ]
def compareValues(self, oldval, newval):
fvt = FloatVectorType()
for i in range(len(oldval)):
if not fvt.isEqual(oldval[i], newval[i]):
return False
return True
def clone(self):
newactor = DejaVuActor.clone(self)
newactor.hasGetFunction = self.hasGetFunction
return newactor
def getAllSubclasses(klass):
# recursively build a list of all sub-classes
bases = klass.__bases__
klassList = list(bases)
for k in bases:
klassList.extend( getAllSubclasses(k) )
return klassList
import inspect
from actorsDescr import actorsDescr
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
from Scenario2.interpolators import FloatScalarInterpolator, IntScalarInterpolator
def getAnimatableAttributes(object):
# return two dicts that contain a dict for each attribute of object
# that can be animated. The first dict is for attribute foudn in
# actorsDescr, the second is for attributes picked up on the fly
# merge the dict of attribute for all base classes
d1 = {}
for klass, d2 in actorsDescr.items():
if isinstance(object, klass):
d1.update(d2)
d2 = {}
# find all attribute that are float
attrs = inspect.getmembers(object, lambda x: isinstance(x, float))
for name,value in attrs:
if d1.has_key(name): continue
d2[name] = {
'interp': FloatScalarInterpolator,
'interpKw': {'values':[value, value]},
'valueWidget': ThumbWheel,
'valueWidgetKw': {'type': 'float', 'initialValue':value},
}
# find all attribute that are bool or int
attrs = inspect.getmembers(object, lambda x: isinstance(x, int))
for name,value in attrs:
if d1.has_key(name): continue
d2[name] = {
'interp': IntScalarInterpolator,
'interpKw': {'values':[value, value]},
'valueWidget': ThumbWheel,
'valueWidgetKw': {'type':'int', 'initialValue':value},
}
return d1, d2
def getDejaVuActor(object, attribute):
# return a DejaVu Actor given a DejaVu object and attribute name
baseClasses = [object.__class__]
baseClasses.extend( getAllSubclasses(object.__class__) )
#print 'getDejaVuActor', object,attribute
for klass in baseClasses:
d1 = actorsDescr.get(klass, None)
if d1:
d2 = d1.get(attribute, None)
if d2:
actorCalss, args, kw = d2['actor']
args = (attribute,object) + args
actor = actorCalss( *args, **kw )
return actor
## else: # attribute not found in dictionary
## if attribute in object.keywords: # it is setable
## if hasattr(object, attribute):
## actor = DejaVuActorSetGetattr(
## object, name=actorName, setName=attribute,
## getName=attribute)
## else:
## return None # FIXME
## else:
return None
```
#### File: MGLToolsPckgs/DejaVu/StickerImage.py
```python
import os
import Image
from copy import deepcopy
from opengltk.extent import _gllib
from opengltk.OpenGL import GL
from DejaVu.Insert2d import Insert2d
class StickerQuad(Insert2d):
keywords = Insert2d.keywords + [
'color',
]
def __init__(self, name='StickerPylgon', check=1, **kw):
#print "StickerImage.__init__"
self.color = [1,1,1,1]
apply(Insert2d.__init__, (self, name, check), kw)
self.needsRedoDpyListOnResize = True
def Set(self, check=1, redo=1, updateOwnGui=True, **kw):
"""set data for this object
check=1 : verify that all the keywords present can be handle by this func
redo=1 : append self to viewer.objectsNeedingRedo
updateOwnGui=True : allow to update owngui at the end this func
"""
#print "Insert2d.Set"
redoFlags = apply( Insert2d.Set, (self, check, 0), kw)
val = kw.pop( 'transparent', None)
if not val is None:
redoFlags |= self._setTransparent(val)
anchor = kw.get( 'anchor')
if anchor \
and (anchor[0] >= 0.) and (anchor[0] <= 1.) \
and (anchor[1] >= 0.) and (anchor[1] <= 1.):
self.anchor = anchor
redoFlags |= self._redoFlags['redoDisplayListFlag']
position = kw.get( 'position')
if position:
self.position = position
redoFlags |= self._redoFlags['redoDisplayListFlag']
size = kw.get( 'size')
if size:
self.size = size
redoFlags |= self._redoFlags['redoDisplayListFlag']
color = kw.get( 'color')
if color:
print color
self.color = color
print self.color
redoFlags |= self._redoFlags['redoDisplayListFlag']
return self.redoNow(redo, updateOwnGui, redoFlags)
def Draw(self):
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPushMatrix()
GL.glLoadIdentity()
Insert2d.Draw(self)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPushMatrix()
GL.glLoadIdentity()
GL.glDisable(GL.GL_DEPTH_TEST)
GL.glDisable(GL.GL_LIGHTING);
width = self.size[0]
height = self.size[1]
fullWidth = self.viewer.currentCamera.width
fullHeight = self.viewer.currentCamera.height
# we want the anchor of the image to be at the given position
posxFromLeft = self.position[0] * fullWidth - self.anchor[0] * width
posyFrombottom = (1.-self.position[1]) * fullHeight - (1.-self.anchor[1]) * height
#print "posxFromLeft, posyFrombottom", posxFromLeft, posyFrombottom
GL.glColor4fv(self.color)
xo, yo = self.position
dx, dy = self.size
GL.glBegin(GL.GL_QUADS);
GL.glVertex2f(xo, yo)
GL.glVertex2f(xo+dx, yo)
GL.glVertex2f(xo+dx, yo+dy)
GL.glVertex2f(xo, yo+dy)
GL.glEnd()
# used for picking
# self.polygonContour = [ (posxFromLeft, posyFrombottom),
# (posxFromLeft+width, posyFrombottom),
# (posxFromLeft+width, posyFrombottom+height),
# (posxFromLeft, posyFrombottom+height)
# ]
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glEnable(GL.GL_LIGHTING);
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPopMatrix()
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPopMatrix()
return 1
class StickerImage(Insert2d):
keywords = Insert2d.keywords + [
'image',
]
def __init__(self, name='StickerImage', check=1, **kw):
#print "StickerImage.__init__"
self.image = None
apply(Insert2d.__init__, (self, name, check), kw)
self.needsRedoDpyListOnResize = True
def Set(self, check=1, redo=1, updateOwnGui=True, **kw):
"""set data for this object:
check=1 : verify that all the keywords present can be handle by this func
redo=1 : append self to viewer.objectsNeedingRedo
updateOwnGui=True : allow to update owngui at the end this func
"""
#print "StickerImage.Set"
redoFlags = apply( Insert2d.Set, (self, check, 0), kw)
image = kw.get('image')
if image is not None:
kw.pop('image')
self.image = image
self.size[0] = self.image.size[0]
self.size[1] = self.image.size[1]
redoFlags |= self._redoFlags['redoDisplayListFlag']
return self.redoNow(redo, updateOwnGui, redoFlags)
def Draw(self):
#print "StickerImage.Draw", self
if self.image is None:
return
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPushMatrix()
GL.glLoadIdentity()
Insert2d.Draw(self)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPushMatrix()
GL.glLoadIdentity()
GL.glDisable(GL.GL_DEPTH_TEST)
GL.glDisable(GL.GL_LIGHTING);
width = self.size[0]
height = self.size[1]
fullWidth = self.viewer.currentCamera.width
fullHeight = self.viewer.currentCamera.height
# we want the anchor of the image to be at the given position
posxFromLeft = self.position[0] * fullWidth - self.anchor[0] * width
posyFrombottom = (1.-self.position[1]) * fullHeight - (1.-self.anchor[1]) * height
#print "posxFromLeft, posyFrombottom", posxFromLeft, posyFrombottom
# used for picking
self.polygonContour = [ (posxFromLeft, posyFrombottom),
(posxFromLeft+width, posyFrombottom),
(posxFromLeft+width, posyFrombottom+height),
(posxFromLeft, posyFrombottom+height)
]
# this accept negative values were GL.glRasterPos2f(x,y) doesn't
GL.glRasterPos2f(0, 0)
_gllib.glBitmap(0, 0, 0, 0, posxFromLeft, posyFrombottom, 0)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
if self.image.mode == 'RGBA':
_gllib.glDrawPixels(self.image.size[0], self.image.size[1],
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE,
self.image.tostring() )
elif self.image.mode == 'RGB':
_gllib.glDrawPixels(self.image.size[0], self.image.size[1],
GL.GL_RGB, GL.GL_UNSIGNED_BYTE,
self.image.tostring() )
elif self.image.mode == 'L':
_gllib.glDrawPixels(self.image.size[0], self.image.size[1],
GL.GL_LUMINANCE, GL.GL_UNSIGNED_BYTE,
self.image.tostring() )
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glPopMatrix()
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glPopMatrix()
return 1
def setSize(self, event, redo=1):
"""the trackball transmit the translation info
"""
pass
```
#### File: MGLToolsPckgs/DejaVu/testcsg3.py
```python
from OpenCSG import opencsglib as OpenCSG
import numpy.oldnumeric as Numeric
## from DejaVu.Spheres import Spheres
class DejaVuPrimitive(OpenCSG.PythonPrimitive):
def __init__(self, geom):
apply( OpenCSG.PythonPrimitive.__init__, (self, self.render, OpenCSG.Intersection, 0))
# does not work for some reason
#OpenCSG.PythonPrimitive(self.render, OpenCSG.Intersection, 1)
self.geom = geom
self.dpyListCSG = None
def redoDisplayListCSG(self):
if self.dpyListCSG is not None:
GL.glDeleteLists(1, self.dpyListCSG)
g = self.geom
self.dpyListCSG = GL.glGenLists(1)
GL.glNewList(self.dpyListCSG, GL.GL_COMPILE)
## if isinstance(g, Spheres):
## g.DisplayFunction()
## else:
self.drawpolygons()
GL.glEndList()
def drawpolygons(self):
g = self.geom
vertices = g.getVertices()
faces = g.getFaces()
normals = g.getFNormals()
GL.glDisable(GL.GL_CULL_FACE)
for i,f in enumerate(faces):
GL.glBegin(GL.GL_POLYGON)
GL.glNormal3fv(normals[i])
for vi in f:
GL.glVertex3fv(vertices[vi])
GL.glEnd()
i+=1
def render(self, mode='render'):
# call with mode='csg' to render simple shape to setup Zbuffer for CSG
# call with mode='render' to render by calling geom's draw function
if self.geom:
#import traceback
#print traceback.print_stack()
#print self.geom
#print "========================================================="
root = self.geom.viewer.rootObject
instance = [0]
p = self.geom.parent
while p:
instance.append(0)
p = p.parent
#mat = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f')
#print 'mat OK', mat
GL.glPushMatrix()
GL.glLoadIdentity()
self.geom.viewer.currentCamera.BuildTransformation()
self.geom.BuildMat(self.geom, root, True, instance)
#mat = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f')
#print 'mat PB', mat
#print 'render ', mode, self.geom
if mode=='csg':
if self.dpyListCSG is None:
self.redoDisplayListCSG()
GL.glCallList(self.dpyListCSG)
elif mode=='render':
obj = self.geom
if not obj.inheritMaterial:
obj.InitMaterial(0)
obj.InitColor(0)
obj.DisplayFunction()
GL.glPopMatrix()
from DejaVu.Geom import Geom
from opengltk.OpenGL import GL
from DejaVu.viewerFns import checkKeywords
class OpenCSGGeom(Geom):
keywords = Geom.keywords + [
'primitives',
'algo',
'depthalgo',
]
def __init__(self, name=None, check=1, **kw):
if __debug__:
if check:
apply( checkKeywords, (name,self.keywords), kw)
apply( Geom.__init__, (self, name, 0), kw )
self.primitives = OpenCSG.PrimitiveVector() # C++ primitives
self.pyprimitives = [] # python subclasses used to call python implementation or render
self.algo = OpenCSG.Goldfeather
self.depthalgo = OpenCSG.DepthComplexitySampling
self.Set(culling='none', algo=OpenCSG.Goldfeather,
depthalgo=OpenCSG.DepthComplexitySampling)
def clearPrimitives(self):
## for p in self.pyprimitives:
## if p.dpyListCSG:
## print 'AAAAAAAAAAAAAAA', p.geom
## print 'AAAAAAAAAAAAAAA', p.dpyListCSG, p.geom.dpyList
## GL.glDeleteLists(1, p.dpyListCSG )
## p.dpyListCSG = None
self.primitives.clear()
self.pyprimitives = []
def setPrimitives(self, *args):
self.clearPrimitives()
for g in args:
assert isinstance(g, Geom)
prim = DejaVuPrimitive(g)
#self.primitives.append(prim)
OpenCSG.PrimitiveVector_add(self.primitives, prim)
self.pyprimitives.append(prim)
def Set(self, check=1, redo=1, **kw):
"""Set primitives"""
if __debug__:
if check:
apply( checkKeywords, (self.name,self.keywords), kw)
apply( Geom.Set, (self, 0, 0), kw)
p = kw.get( 'primitives')
if p:
assert isinstance(p, OpenCSG.PythonPrimitiveVector)
self.primitives = p
a = kw.get( 'algo')
if a:
if a =='automatic':
a = OpenCSG.Automatic
elif a== 'goldfeather':
a = OpenCSG.Goldfeather
elif a == 'scs':
a = OpenCSG.SCS
assert a in (OpenCSG.Automatic, OpenCSG.Goldfeather, OpenCSG.SCS)
self.algo = a
d = kw.get( 'depthalgo')
if d:
if d =='DepthComplexitySampling':
d = OpenCSG.DepthComplexitySampling
elif d== 'NoDepthComplexitySampling':
d = OpenCSG.NoDepthComplexitySampling
elif d == 'OcclusionQuery':
d = OpenCSG.OcclusionQuery
assert d in (OpenCSG.DepthComplexitySampling,
OpenCSG.NoDepthComplexitySampling,
OpenCSG.OcclusionQuery)
self.depthalgo = d
def Draw(self):
GL.glEnable(GL.GL_DEPTH_TEST);
GL.glClear( GL.GL_STENCIL_BUFFER_BIT)
GL.glDisable(GL.GL_FOG)
#GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)
OpenCSG.render(self.primitives, self.algo, self.depthalgo)
GL.glDepthFunc(GL.GL_EQUAL)
# FIXME should only enable fog if it is on in camera
GL.glEnable(GL.GL_FOG)
self.SetupGL()
for p in self.pyprimitives:
p.render()
GL.glDepthFunc(GL.GL_LESS);
o=0
a = 20
vertices = [ (o, o, o), (o, a, o), (a, a, o), (a, o, o),
(o, o, a), (o, a, a), (a, a, a), (a, o, a) ]
facesInward = [ (3,2,1,0), (7,6,2,3), (5,6,7,4), (0,1,5,4), (2,6,5,1), (4,7,3,0)]
facesOutward = [ (0,1,2,3), (3,2,6,7), (4,7,6,5), (4,5,1,0), (1,5,6,2), (0,3,7,4)]
faces = facesOutward
normals = [(0,0,1), (-1,0,0), (0,0,-1), (1,0,0), (0,-1,0), (0,1,0)]
from DejaVu.IndexedPolygons import IndexedPolygons
clipBox = IndexedPolygons('clipBox', vertices=vertices, faces=faces, fnormals=normals,
frontPolyMode='line', shading='flat')
self.readMolecule('/home/annao/python/dev23/1crn.pdb', ask=0, parser=None, log=0)
#self.readMolecule('/home/annao/python/dev23/cv.pdb', ask=0, parser=None, log=0)
self.browseCommands('msmsCommands', commands=None, log=0, package='Pmv')
#self.computeMSMS("1crn;cv", 'MSMS-MOL', perMol=1, density=4.6, log=0, pRadius=1.5)
self.computeMSMS("1crn", 'MSMS-MOL', perMol=1, density=4.6, log=0, pRadius=1.5)
srf1 = self.Mols[0].geomContainer.geoms['MSMS-MOL']
#srf2 = self.Mols[1].geomContainer.geoms['MSMS-MOL']
cpk1 = self.Mols[0].geomContainer.geoms['cpk']
#cpk2 = self.Mols[1].geomContainer.geoms['cpk']
self.colorByResidueType("1crn;cv", ['MSMS-MOL'], log=0)
#self.displayMSMS("1crn;cv", negate=True, only=False, surfName=['MSMS-MOL'], log=0, nbVert=1)
#self.displayCPK("1crn;cv", cpkRad=0.0, scaleFactor=1.0, only=False, negate=False, quality=17)
#self.showMolecules(['cv'], negate=True, log=0)
#self.colorByAtomType("1crn;cv", ['cpk'], log=0)
srf1.Set(frontPolyMode='line', visible=False)
#srf2.Set(frontPolyMode='line')
err = OpenCSG.glewInit()
print "glewInit status: ", err
g = OpenCSGGeom('inter')
g.setPrimitives(srf1, clipBox)
#g.setPrimitives(srf1, srf2)
#g.setPrimitives(cpk1, clipBox)
g.Set(immediateRendering=True, lighting=True)
self.GUI.VIEWER.AddObject(clipBox)
self.GUI.VIEWER.AddObject(g)
#g.primitives[1].setOperation(OpenCSG.Subtraction)
```
#### File: DejaVu/VisionInterface/DejaVuWidgets.py
```python
import numpy.oldnumeric as Numeric
import Tkinter, Pmw
from NetworkEditor.widgets import TkPortWidget, PortWidget
from DejaVu.colorMap import ColorMap
from DejaVu.ColormapGui import ColorMapGUI
from DejaVu.colorTool import RGBRamp
from DejaVu.ColorWheel import ColorWheel
from mglutil.gui.BasicWidgets.Tk.colorWidgets import ColorEditor
from mglutil.util.callback import CallBackFunction
class NEDejaVuGeomOptions(PortWidget):
"""widget allowing to configure a DejaVuGeometry
Handle all things that can be set to a finite list of values in a Geometry
"""
configOpts = PortWidget.configOpts.copy()
ownConfigOpts = {}
ownConfigOpts['initialValue'] = {
'defaultValue':{}, 'type':'dict',
}
configOpts.update(ownConfigOpts)
def __init__(self, port, **kw):
# call base class constructor
apply( PortWidget.__init__, (self, port), kw)
self.booleanProps = [
'disableTexture',
'faceNormals',
'inheritBackPolyMode',
'inheritCulling',
'inheritFrontPolyMode',
'inheritLighting'
'inheritStippleLines',
'inheritLineWidth',
'inheritMaterial',
'inheritPointWidth',
'inheritStipplePolygons',
'inheritShading',
'inheritSharpColorBoundaries',
'inheritXform',
'invertNormals',
'lighting',
'protected',
'scissor',
'sharpColorBoundaries',
'vertexNormals',
'visible',
]
from DejaVu import viewerConst
self.choiceProps = {
'frontPolyMode':viewerConst.Front_POLYGON_MODES_keys,
'backPolyMode':viewerConst.Back_POLYGON_MODES_keys,
'shading':viewerConst.SHADINGS.keys(),
'culling':viewerConst.CULLINGS.keys(),
}
self.frame = Tkinter.Frame(self.widgetFrame, borderwidth=3,
relief = 'ridge')
self.propWidgets = {} # will hold handle to widgets created
self.optionsDict = {} # widget's value
import Pmw
items = self.booleanProps + self.choiceProps.keys()
w = Pmw.Group(self.frame, tag_text='Add a Property Widget')
self.chooser = Pmw.ComboBox(
w.interior(), label_text='', labelpos='w',
entryfield_entry_width=20, scrolledlist_items=items,
selectioncommand=self.addProp)
self.chooser.pack(padx=2, pady=2, expand='yes', fill='both')
w.pack(fill = 'x', expand = 1, side='top')
w = Pmw.Group(self.frame, tag_text='Property Widgets')
self.propWidgetMaster = w.interior()
w.pack(fill='both', expand = 1, side='bottom')
# configure without rebuilding to avoid enless loop
apply( self.configure, (False,), kw)
self.frame.pack(expand='yes', fill='both')
if self.initialValue is not None:
self.set(self.initialValue, run=0)
self._setModified(False) # will be set to True by configure method
def addProp(self, prop):
if self.propWidgets.has_key(prop):
return
l = Tkinter.Label(self.propWidgetMaster, text=prop)
l.grid(padx=2, pady=2, row=len(self.propWidgets)+1, column=0,
sticky='e')
if prop in self.booleanProps:
var = Tkinter.IntVar()
var.set(0)
cb = CallBackFunction( self.setBoolean, (prop, var))
widget = Tkinter.Checkbutton(self.propWidgetMaster,
variable=var, command=cb)
self.propWidgets[prop] = (widget, var)
self.setBoolean( (prop, var) )
else:
items = self.choiceProps[prop]
var = None
cb = CallBackFunction( self.setChoice, (prop,))
widget = Pmw.ComboBox(
self.propWidgetMaster, entryfield_entry_width=15,
scrolledlist_items=items, selectioncommand=cb)
self.propWidgets[prop] = (widget, var)
self.setChoice( (prop,), items[0] )
widget.grid(row=len(self.propWidgets), column=1, sticky='w')
def setBoolean(self, args):
prop, var = args
self.optionsDict[prop] = var.get()
if self.port.node.paramPanel.immediateTk.get():
self.scheduleNode()
def setChoice(self, prop, value):
self.optionsDict[prop[0]] = value
self.propWidgets[prop[0]][0].selectitem(value)
if self.port.node.paramPanel.immediateTk.get():
self.scheduleNode()
def set(self, valueDict, run=1):
self._setModified(True)
for k,v in valueDict.items():
self.addProp(k)
if k in self.booleanProps:
self.propWidgets[k][1].set(v)
self.setBoolean( (k, self.propWidgets[k][1]) )
else:
self.setChoice((k,), v)
self._newdata = True
if run:
self.scheduleNode()
def get(self):
return self.optionsDict
def configure(self, rebuild=True, **kw):
action, rebuildDescr = apply( PortWidget.configure, (self, 0), kw)
# this methods just creates a resize action if width changes
if self.widget is not None:
if 'width' in kw:
action = 'resize'
if action=='rebuild' and rebuild:
action, rebuildDescr = self.rebuild(rebuildDescr)
if action=='resize' and rebuild:
self.port.node.autoResize()
return action, rebuildDescr
class NEColorMap(PortWidget):
# description of parameters that can only be used with the widget's
# constructor
configOpts = PortWidget.configOpts.copy()
ownConfigOpts = {
'mini':{'type':'float', 'defaultValue':None},
'maxi':{'type':'float', 'defaultValue':None},
#'ramp':{'defaultValue':None},
'filename':{'type':'string', 'defaultValue':''},
'viewer':{'defaultValue':None},
}
configOpts.update( ownConfigOpts )
def configure(self, rebuild=True, **kw):
action, rebuildDescr = apply( PortWidget.configure, (self, 0), kw)
# handle ownConfigOpts entries
if self.widget is not None:
widgetOpts = {}
# handle viewer first so that legend exists if min or max is set
viewer = kw.get('viewer', None)
if viewer:
if self.widget.viewer != viewer:
self.widget.SetViewer(viewer)
for k, v in kw.items():
if k=='viewer':
continue
elif k=='mini' or k=='maxi':
apply( self.widget.update, (), {k:v} )
elif k=='filename':
self.widget.read(v)
def __init__(self, port, **kw):
# create all attributes that will not be created by configure because
# they do not appear on kw
for key in self.ownConfigOpts.keys():
v = kw.get(key, None)
if v is None: # self.configure will not do anyting for this key
setattr(self, key, self.ownConfigOpts[key]['defaultValue'])
# get all arguments handled this widget and not by PortWidget
widgetcfg = {}
for k in self.ownConfigOpts.keys():
if k in kw:
widgetcfg[k] = kw.pop(k)
# we build 2 widgets here, let's do the first:
cmkw = {} # dict for ColorMap keywords
ramp = widgetcfg.pop('ramp', None)
#if ramp is None:
#ramp = RGBRamp(size=16)
#cmkw['ramp'] = ramp
cmkw['mini'] = widgetcfg.pop('mini', None)
cmkw['maxi'] = widgetcfg.pop('maxi', None)
# create an instance of the ColorMap which is required to instanciate
# the ColorMapGUI (i.e. the widget)
cM = apply( ColorMap, ('cmap',), cmkw)
# call base class constructor
apply( PortWidget.__init__, ( self, port), kw)
# create the widget
widgetcfg['master'] = self.widgetFrame
widgetcfg['modifyMinMax'] = True
#try: #tries to assign viewer when called from Pmv
# widgetcfg['viewer'] = self.vEditor.vf.GUI.VIEWER
#except:
# pass
self.widget = apply( ColorMapGUI, (cM,), widgetcfg)
# we call cmCallback because cm passed the color map as an argument
# and node.schedule takes no argument
self.widget.addCallback(self.cmCallback)
# configure without rebuilding to avoid enless loop
#apply( self.configure, (False,), widgetcfg)
if self.initialValue:
self.set(self.initialValue, run=0)
self.modified = False # will be set to True by configure method
# and destroy the Apply and Dismiss buttons of the ColorMapGUI
self.widget.dismiss.forget()
self.widget.apply.forget()
self.widget.frame2.forget()
# overwrite the paramPanel Appply button method to call
# the ColorMapGUI apply_cb() method
if hasattr(self.port.node, 'paramPanel'):
self.port.node.paramPanel.applyFun = self.apply_cb
## def __init__(self, port=None, master=None, visibleInNodeByDefault=0,
## visibleInNode=0, value=None, callback=None, **kw):
## PortWidget.__init__(self, port, master, visibleInNodeByDefault,
## visibleInNode, callback)
## cmkw = {} # dict for ColorMap keywords
## cmkw['ramp'] = RGBRamp() #default ramp, can be overwritten below
## for k in kw.keys():
## if k in ['ramp', 'geoms', 'filename', 'mini', 'maxi']:
## cmkw[k] = kw[k]
## del kw[k]
## # create an instance of the ColorMap which is required to instanciate
## # the ColorMapGUI
## cM = apply( ColorMap, ('cmap',), cmkw)
## # instanciate the ColorMapGUI
## kw['master'] = self.top
## self.cm = apply( ColorMapGUI, (cM,), kw)
## # and destroy the Apply and Dismiss buttons of the ColorMapGUI
## self.cm.dismiss.forget()
## self.cm.apply.forget()
## self.cm.frame2.forget()
## # add callback. Note, we do not call scheduleNode because this would
## # lead to recursion problem
## #self.cm.addCallback(self.port.node.schedule)
## # we call cmCallback because cm passed the color map as an argument
## # and node.schedule takes no argument
## self.cm.addCallback(self.cmCallback)
## if value is not None:
## self.set(value, run=0)
## # overwrite the paramPanel Appply button method to call
## # the ColorMapGUI apply_cb() method
## if hasattr(self.port.node, 'paramPanel'):
## self.port.node.paramPanel.applyFun = self.apply_cb
def onUnbind(self):
legend = self.widget.legend
if legend is not None:
viewer = legend.viewer
if viewer is not None:
legend.protected = False
viewer.RemoveObject(legend)
legend = None
def onDelete(self):
self.onUnbind()
def cmCallback(self, cmap):
self.port.node.schedule()
def apply_cb(self, event=None):
if self.widget is not None:
self._setModified(True)
# overwrite the paramPanel Appply button method to call
# the ColorMapGUI apply_cb() method
self.widget.apply_cb(event)
self._newdata = 1
self.port.node.schedule()
def set(self, value, run=1):
#import pdb;pdb.set_trace()
self._setModified(True)
if isinstance(value, dict):
apply(ColorMapGUI.configure,(self.widget,),value)
else:
self.widget.set(value)
self._newdata = 1
if run:
self.port.node.schedule()
def get(self):
return self.widget
def getDataForSaving(self):
# this method is called when a network is saved and the widget
# value needs to be saved
cfg = PortWidget.getDescr(self)
cfg['name'] = self.widget.name
cfg['ramp'] = self.widget.ramp
cfg['mini'] = self.widget.mini
cfg['maxi'] = self.widget.maxi
return cfg
def getDescr(self):
cfg = PortWidget.getDescr(self)
# the whole colormap is the widget value and
# is returned by self.get() !
#cfg['name'] = self.widget.name
#cfg['ramp'] = self.widget.ramp
#cfg['mini'] = self.widget.mini
#cfg['maxi'] = self.widget.maxi
return cfg
class NEColorWheel(PortWidget):
# description of parameters that can only be used with the widget's
# constructor
configOpts = PortWidget.configOpts.copy()
ownConfigOpts = {
'width':{'min':20, 'max':500, 'defaultValue':75, 'type':'int'},
'height':{'min':20, 'max':500, 'defaultValue':75, 'type':'int'},
'circles':{'min':2, 'max':20, 'defaultValue':5, 'type':'int'},
'stripes':{'min':2, 'max':40, 'defaultValue':20, 'type':'int'},
}
configOpts.update( ownConfigOpts )
def __init__(self, port, **kw):
# create all attributes that will not be created by configure because
# they do not appear on kw
for key in self.ownConfigOpts.keys():
v = kw.get(key, None)
if v is None: # self.configure will not do anyting for this key
setattr(self, key, self.ownConfigOpts[key]['defaultValue'])
# get all arguments handled by this widget and not by PortWidget
widgetcfg = {}
for k in self.ownConfigOpts.keys():
if k in kw:
widgetcfg[k] = kw.pop(k)
# call base class constructor
apply( PortWidget.__init__, ( self, port), kw)
# create the widget
self.widget = apply( ColorWheel, (self.widgetFrame,), widgetcfg)
self.widget.AddCallback(self.cwCallback)
# configure without rebuilding to avoid enless loop
#apply( self.configure, (False,), widgetcfg)
if self.initialValue:
self.set(self.initialValue, run=0)
self.modified = False # will be set to True by configure method
## def __init__(self, port=None, master=None, visibleInNodeByDefault=0,
## visibleInNode=0, value=None, callback=None, **kw):
## PortWidget.__init__(self, port, master, visibleInNodeByDefault,
## visibleInNode, callback)
## self.cw = apply( ColorWheel, (self.top,), kw)
## if value is not None:
## self.set(value, run=0)
## self.cw.AddCallback(self.scheduleNode)
def cwCallback(self, color):
self._newdata = 1
self.scheduleNode()
def set(self, value, run=1):
self.widget.Set(value, mode='RGB')
self._newdata = 1
if run:
self.scheduleNode()
#self.port.node.schedule()
def get(self, mode='RGB'):
value = self.widget.Get(mode)
value = list( Numeric.array(value) )
return value
def getDescr(self):
cfg = PortWidget.getDescr(self)
cfg['width'] = self.widget.width
cfg['height'] = self.widget.height
cfg['circles'] = self.widget.circles
cfg['stripes'] = self.widget.stripes
cfg['wheelPad'] = self.widget.wheelPad
cfg['immediate'] = self.widget.immediate
cfg['wysiwyg'] = self.widget.wysiwyg
return cfg
## def configure(self, **kw):
## if len(kw)==0:
## cfg = PortWidget.configure(self)
## cfg['immediate'] = self.cw.immediate
## cfg['wysiwyg'] = self.cw.wysiwyg
## return cfg
## else:
## if kw.has_key('immediate'):
## self.cw.setImmediate(kw['immediate'])
## elif kw.has_key('wysiwyg'):
## self.cw.setWysiwyg(kw['wysiwyg'])
class NEColorEditor(PortWidget):
# description of parameters that can only be used with the widget's
# constructor
configOpts = PortWidget.configOpts.copy()
ownConfigOpts = {
'mode':{'defaultValue':'RGB', 'type':'string',
'validValues':['RGB', 'HSV', 'HEX']},
'immediate':{'defaultValue':True, 'type':'boolean'},
}
configOpts.update( ownConfigOpts )
def __init__(self, port, **kw):
# create all attributes that will not be created by configure because
# they do not appear on kw
for key in self.ownConfigOpts.keys():
v = kw.get(key, None)
if v is None: # self.configure will not do anyting for this key
setattr(self, key, self.ownConfigOpts[key]['defaultValue'])
# get all arguments handled by this widget and not by PortWidget
widgetcfg = {}
for k in self.ownConfigOpts.keys():
if k in kw:
widgetcfg[k] = kw.pop(k)
# call base class constructor
apply( PortWidget.__init__, ( self, port), kw)
# create the widget
self.widget = apply( ColorEditor, (self.widgetFrame,), widgetcfg)
self.widget.cbManager.AddCallback(self.cwCallback)
self.widget.pack()
# configure without rebuilding to avoid enless loop
#apply( self.configure, (False,), widgetcfg)
if self.initialValue:
self.set(self.initialValue, run=0)
self.modified = False # will be set to True by configure method
## def __init__(self, port=None, master=None, visibleInNodeByDefault=0,
## visibleInNode=0, value=None, callback=None, **kw):
## PortWidget.__init__(self, port, master, visibleInNodeByDefault,
## visibleInNode, callback)
## self.cw = apply( ColorWheel, (self.top,), kw)
## if value is not None:
## self.set(value, run=0)
## self.cw.AddCallback(self.scheduleNode)
def cwCallback(self, color):
self._newdata = 1
self.scheduleNode()
def set(self, value, run=1):
if value is not None:
self._setModified(True)
self.widget.set(value, mode='RGB')
self._newdata = 1
if run:
self.port.node.schedule()
def get(self, mode='RGB'):
value = self.widget.get(mode='RGB')
value = list( Numeric.array(value) )
return value
def getDescr(self):
cfg = PortWidget.getDescr(self)
cfg['mode'] = self.widget.mode
cfg['immediate'] = self.widget.immediate
return cfg
```
#### File: MGLToolsPckgs/geomutils/efitlib.py
```python
import _efitlib
import new
new_instancemethod = new.instancemethod
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import types
try:
_object = types.ObjectType
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
del types
class ellipsoid(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, ellipsoid, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, ellipsoid, name)
__repr__ = _swig_repr
__swig_setmethods__["name"] = _efitlib.ellipsoid_name_set
__swig_getmethods__["name"] = _efitlib.ellipsoid_name_get
if _newclass:name = _swig_property(_efitlib.ellipsoid_name_get, _efitlib.ellipsoid_name_set)
__swig_setmethods__["position"] = _efitlib.ellipsoid_position_set
__swig_getmethods__["position"] = _efitlib.ellipsoid_position_get
if _newclass:position = _swig_property(_efitlib.ellipsoid_position_get, _efitlib.ellipsoid_position_set)
__swig_setmethods__["axis"] = _efitlib.ellipsoid_axis_set
__swig_getmethods__["axis"] = _efitlib.ellipsoid_axis_get
if _newclass:axis = _swig_property(_efitlib.ellipsoid_axis_get, _efitlib.ellipsoid_axis_set)
__swig_setmethods__["orientation"] = _efitlib.ellipsoid_orientation_set
__swig_getmethods__["orientation"] = _efitlib.ellipsoid_orientation_get
if _newclass:orientation = _swig_property(_efitlib.ellipsoid_orientation_get, _efitlib.ellipsoid_orientation_set)
__swig_setmethods__["inv_orientation"] = _efitlib.ellipsoid_inv_orientation_set
__swig_getmethods__["inv_orientation"] = _efitlib.ellipsoid_inv_orientation_get
if _newclass:inv_orientation = _swig_property(_efitlib.ellipsoid_inv_orientation_get, _efitlib.ellipsoid_inv_orientation_set)
__swig_setmethods__["tensor"] = _efitlib.ellipsoid_tensor_set
__swig_getmethods__["tensor"] = _efitlib.ellipsoid_tensor_get
if _newclass:tensor = _swig_property(_efitlib.ellipsoid_tensor_get, _efitlib.ellipsoid_tensor_set)
def getPosition(*args): return _efitlib.ellipsoid_getPosition(*args)
def getAxis(*args): return _efitlib.ellipsoid_getAxis(*args)
def getOrientation(*args): return _efitlib.ellipsoid_getOrientation(*args)
def __init__(self, *args):
this = _efitlib.new_ellipsoid(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _efitlib.delete_ellipsoid
__del__ = lambda self : None;
ellipsoid_swigregister = _efitlib.ellipsoid_swigregister
ellipsoid_swigregister(ellipsoid)
class efit_info(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, efit_info, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, efit_info, name)
__repr__ = _swig_repr
__swig_setmethods__["weightflag"] = _efitlib.efit_info_weightflag_set
__swig_getmethods__["weightflag"] = _efitlib.efit_info_weightflag_get
if _newclass:weightflag = _swig_property(_efitlib.efit_info_weightflag_get, _efitlib.efit_info_weightflag_set)
__swig_setmethods__["covarflag"] = _efitlib.efit_info_covarflag_set
__swig_getmethods__["covarflag"] = _efitlib.efit_info_covarflag_get
if _newclass:covarflag = _swig_property(_efitlib.efit_info_covarflag_get, _efitlib.efit_info_covarflag_set)
__swig_setmethods__["volumeflag"] = _efitlib.efit_info_volumeflag_set
__swig_getmethods__["volumeflag"] = _efitlib.efit_info_volumeflag_get
if _newclass:volumeflag = _swig_property(_efitlib.efit_info_volumeflag_get, _efitlib.efit_info_volumeflag_set)
__swig_setmethods__["matrixflag"] = _efitlib.efit_info_matrixflag_set
__swig_getmethods__["matrixflag"] = _efitlib.efit_info_matrixflag_get
if _newclass:matrixflag = _swig_property(_efitlib.efit_info_matrixflag_get, _efitlib.efit_info_matrixflag_set)
__swig_setmethods__["nocenterflag"] = _efitlib.efit_info_nocenterflag_set
__swig_getmethods__["nocenterflag"] = _efitlib.efit_info_nocenterflag_get
if _newclass:nocenterflag = _swig_property(_efitlib.efit_info_nocenterflag_get, _efitlib.efit_info_nocenterflag_set)
__swig_setmethods__["noscaleflag"] = _efitlib.efit_info_noscaleflag_set
__swig_getmethods__["noscaleflag"] = _efitlib.efit_info_noscaleflag_get
if _newclass:noscaleflag = _swig_property(_efitlib.efit_info_noscaleflag_get, _efitlib.efit_info_noscaleflag_set)
__swig_setmethods__["nosortflag"] = _efitlib.efit_info_nosortflag_set
__swig_getmethods__["nosortflag"] = _efitlib.efit_info_nosortflag_get
if _newclass:nosortflag = _swig_property(_efitlib.efit_info_nosortflag_get, _efitlib.efit_info_nosortflag_set)
__swig_setmethods__["count"] = _efitlib.efit_info_count_set
__swig_getmethods__["count"] = _efitlib.efit_info_count_get
if _newclass:count = _swig_property(_efitlib.efit_info_count_get, _efitlib.efit_info_count_set)
__swig_setmethods__["cov_scale"] = _efitlib.efit_info_cov_scale_set
__swig_getmethods__["cov_scale"] = _efitlib.efit_info_cov_scale_get
if _newclass:cov_scale = _swig_property(_efitlib.efit_info_cov_scale_get, _efitlib.efit_info_cov_scale_set)
__swig_setmethods__["ell_scale"] = _efitlib.efit_info_ell_scale_set
__swig_getmethods__["ell_scale"] = _efitlib.efit_info_ell_scale_get
if _newclass:ell_scale = _swig_property(_efitlib.efit_info_ell_scale_get, _efitlib.efit_info_ell_scale_set)
def __init__(self, *args):
this = _efitlib.new_efit_info(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _efitlib.delete_efit_info
__del__ = lambda self : None;
efit_info_swigregister = _efitlib.efit_info_swigregister
efit_info_swigregister(efit_info)
fitEllipse = _efitlib.fitEllipse
vec_normalize = _efitlib.vec_normalize
vec_centroid = _efitlib.vec_centroid
vec_dot = _efitlib.vec_dot
vec_magsq = _efitlib.vec_magsq
vec_mag = _efitlib.vec_mag
vec_distancesq = _efitlib.vec_distancesq
vec_distance = _efitlib.vec_distance
vec_max = _efitlib.vec_max
vec_length = _efitlib.vec_length
vec_ctos = _efitlib.vec_ctos
vec_stoc = _efitlib.vec_stoc
vec_sub = _efitlib.vec_sub
vec_copy = _efitlib.vec_copy
vec_add = _efitlib.vec_add
vec_scale = _efitlib.vec_scale
vec_zero = _efitlib.vec_zero
vec_cross = _efitlib.vec_cross
vec_mult = _efitlib.vec_mult
vec_offset = _efitlib.vec_offset
vec_rand = _efitlib.vec_rand
vec_average = _efitlib.vec_average
vec_transform = _efitlib.vec_transform
vec_ftransform = _efitlib.vec_ftransform
mat_jacobi = _efitlib.mat_jacobi
quat_to_mat = _efitlib.quat_to_mat
mat_to_quat = _efitlib.mat_to_quat
```
#### File: BasicWidgets/Tk/graphtool.py
```python
from Tkinter import *
import Tkinter
import tkFileDialog
import types,os
from mglutil.util.callback import CallBackFunction
from mglutil.util.callback import CallbackManager
from mglutil.util.misc import ensureFontCase
import numpy.oldnumeric as Numeric
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
import Pmw
from Pmw import *
from mglutil.util.misc import deepCopySeq
class GraphApp:
# Initialization
def __init__(self,master=None,callback=None,continuous=1):
self.master=master
self.callback = None
self.callbacks = CallbackManager()
self.canvas=canvas = Canvas(self.master,width=345,height=320,bg='white')
self.toolbar = Frame(master) # Create Toolbar
self.toolbar.pack(side='top', expand=1, fill='both')
self.menuFrame1 = Tkinter.Frame(self.toolbar, relief='raised', borderwidth=3)
self.menuFrame1.pack(side='top', expand=1, fill='x')
self.filebutton = Tkinter.Menubutton(self.menuFrame1, text='File')
self.filebutton.pack(side='left')
self.filemenu = Tkinter.Menu(self.filebutton, {})
self.filemenu.add_command(label='Read', command=self.read_cb)
self.filemenu.add_command(label='Write', command=self.write_cb)
self.filebutton['menu'] = self.filemenu
self.editbutton = Tkinter.Menubutton(self.menuFrame1, text='Edit')
self.editbutton.pack(side='left', anchor='w')
self.editmenu = Tkinter.Menu(self.editbutton, {})
self.editmenu.add_command(label='Reset to first in history', command=self.resetAll_cb)
self.editmenu.add_command(label='Step back in history loop', command=self.stepBack_cb)
self.editmenu.add_command(label='Default Curve', command=self.defaultcurve_cb)
self.editmenu.add_command(label='Invert Curve',command=self.invertGraph)
self.histvar=IntVar()
self.histvar.set(1)
self.editmenu.add_checkbutton(label='Histogram',var=self.histvar,command=self.drawHistogram)
self.editbutton['menu'] = self.editmenu
self.optionType = IntVar()
self.updatebutton = Tkinter.Menubutton(self.menuFrame1, text='Update')
self.updatebutton.pack(side='left', anchor='w')
self.updatemenu = Tkinter.Menu(self.updatebutton,{} )
for v,s in {0:'Continuous',1:'MouseButtonUp',2:'Update'}.items():
self.updatemenu.add_radiobutton(label=s,
var=self.optionType,
value = v,command=self.calloption)
if continuous==1:
self.optionType.set(0)
self.updatebutton['menu'] = self.updatemenu
#Curve Type
self.CurveType = IntVar()
self.CurveType.set(0)
self.Smooth=1
self.curvebutton = Tkinter.Menubutton(self.menuFrame1, text='Curve')
self.curvebutton.pack(side='left', anchor='w')
self.curvemenu = Tkinter.Menu(self.curvebutton,{} )
for v,s in {0:'Smooth',1:'Freehand'}.items():
self.curvemenu.add_radiobutton(label=s,
var=self.CurveType,
value = v,command=self.curveoption)
self.curvebutton['menu'] = self.curvemenu
f1 = Tkinter.Frame(self.master)
f1.pack(side='bottom', fill='both', expand=1)
self.d1scalewheellab=Label(f1,text="Sensitivity")
self.d1scalewheellab.pack(side="left")
self.d1scalewheel=ThumbWheel(width=100, height=26,wheelPad=4,master=f1,labcfg={'fg':'black', 'side':'left', 'text':'Test:'},wheelLabcfg1={'font':(ensureFontCase('times'),14,'bold')},wheelLabcfg2={'font':(ensureFontCase('times'),14,'bold')},canvascfg={'bg':'blue'},min = 0.0,max = 1.0,precision =4,showlabel =0,value =0.013,continuous =0,oneTurn =0.01,size = 200)
self.d1scalewheel.pack(side="left")
#tooltip
self.balloon = Pmw.Balloon(f1)
self.balloon.bind(self.d1scalewheel,"cutoff value for differences in Z xoordinates,small values generate more contours")
self.Updatebutton=Button(f1,text=' Update ',command=self.Update)
self.Updatebutton.pack(side=LEFT)
self.Quitbutton=Button(f1,text=' Dismiss ',command=self.dismiss_cb)
self.Quitbutton.pack(side=RIGHT)
self.canvas.bind("<Button-1>", self.OnCanvasClicked)
self.canvas.bind("<B1-Motion>", self.OnCanvasMouseDrag)
self.canvas.bind("<ButtonRelease-1>", self.OnCanvasMouseUp)
self.canvas.config(closeenough=2.0)
self.canvas.pack(side=BOTTOM, fill=BOTH,expand=1)
self.startpoint=(px,py)=(50,275)
self.endpoint=(px1,py1)=(305,20)
self.newpoints=[(px,py),(px1,py1)]
self.canvas.create_rectangle([(px-1,py),(px1+1,py1)],fill='white',outline="black",width=1)
self.canvas.create_text(46,281,text=0,anchor=N)
#Drawing Graph Sheet
for i in range(1,6):
x=50+i*50
canvas.create_line(x,280,x,275,width=1)
canvas.create_text(x,281,text='%d' %(50*i),anchor=N)
for i in range(1,5):
x=50+i*50
canvas.create_line(x,275,x,20,width=1,fill="gray80")
for i in range(1,6):
y=275-i*50
canvas.create_line(45,y,50,y,width=1)
canvas.create_text(44,y,text='%d' %(50*i),anchor=E)
for i in range(1,5):
y=275-i*50
canvas.create_line(50,y,305,y,width=1,fill="gray80")
(x,y)=self.newpoints[0]
(x1,y1)=self.newpoints[-1]
self.curline=canvas.create_line(self.newpoints,fill='black',width=1)
#GRAY SCALE
grays=[]
for i in range(0,100,1):
grays.append("gray"+"%d" %i)
#grays.reverse()
#bottom one
x1=48
x2=51
self.canvas.create_rectangle([(50,315),(307,300)],fill='white',outline="black",width=0.5)
for a in grays:
if x1>306:
x1=x2=306
self.canvas.create_rectangle([(x1+2.5,314),(x2+2.5,301)],fill=a,outline=a,width=1)
x1=x1+2.5
x2=x2+2.5
#left one
y1=274
y2=271
self.canvas.create_rectangle([(20,275),(5,20)],fill='black',outline="black",width=0.5)
for a in grays:
if y1>275:
y1=y2=275
self.canvas.create_rectangle([(19,y1-2.5),(6,y2-2.5)],fill=a,outline=a,width=1)
y1=y1-2.5
y2=y2-2.5
self.oldpoints=[]
self.canvas.configure(cursor='cross')
self.curovals=[]
self.default_points=[(50,275),(88, 238), (101, 150), (154, 78), (75, 271),(305,20)]
# now set the constructor options correctly using the configure method
apply( self.configure, (),{'callback':callback,'continuous':continuous})
self.continuous=continuous
self.mousebuttonup=0
self.update=0
self.range_points=[]
self.history=[]
self.bars=[]
self.default_ramp=[]
self.histvalues=[]
def calloption(self):
tag=self.optionType.get()
self.continuous=0
self.mousebuttonup=0
self.update=0
if tag==0:
self.continuous=1
elif tag==1:
self.mousebuttonup=1
elif tag==2:
self.update=1
def curveoption(self):
tag=self.CurveType.get()
self.Smooth=0
self.Freehand=0
if tag==0:
self.Smooth=1
self.canvas.delete(self.curline)
self.curline=self.canvas.create_line(self.getControlPoints(),smooth=1)
elif tag==1:
self.Freehand=1
self.canvas.delete(self.curline)
self.curline=self.canvas.create_line(self.getControlPoints())
def OnCanvasClicked(self,event):
"""Appends last drag point to controlpoint list if not appended by mouseleave func.
when clicked on any controlpoint removes control point and draws line with remaining
control points."""
self.CLICK_NODRAG=1
if self.history!=[]:
if self.history[-1][1]!=self.d1scalewheel.get():
self.history[-1]=(self.history[-1][0],self.d1scalewheel.get())
if hasattr(self,"curx"):
if (self.curx,self.cury) :#not in [self.startpoint,self.endpoint]:
(self.ox,self.oy)=(self.curx,self.cury)
if (self.ox,self.oy) not in self.oldpoints:
self.oldpoints.append((self.ox,self.oy))
if hasattr(self,"curoval"):
self.curovals.append(self.curoval)
self.OrgX=event.x
self.OrgY=event.y
CtlPoints=[]
xcoords=[]
ycoords=[]
#Limiting points not to cross
self.limit_xcoord=[]
for i in range(0,10):
xcoords.append(self.OrgX-i)
ycoords.append(self.OrgY-i)
xcoords.append(self.OrgX+i)
ycoords.append(self.OrgY+i)
if xcoords!=[] and ycoords!=[]:
for x in xcoords:
for y in ycoords:
CtlPoints.append((x,y))
self.range_points=self.oldpoints
self.range_points.sort()
for c in CtlPoints:
if c in self.range_points:
index_c=self.range_points.index(c)
if index_c<len(self.range_points)-1:
self.limit_xcoord.append(self.range_points[index_c+1])
if index_c>0:
self.limit_xcoord.append(self.range_points[index_c-1])
return
else:
self.limit_xcoord.append(self.startpoint)
return
elif index_c==len(self.range_points)-1:
self.limit_xcoord.append(self.range_points[index_c-1])
self.limit_xcoord.append(self.endpoint)
return
self.newd1ramp= self.caluculate_ramp()
def OnCanvasMouseUp(self,event):
CtlPoints=[]
xcoords=[]
ycoords=[]
if hasattr(self,"curx"):
(self.ox,self.oy)=(self.curx,self.cury)
if (self.ox,self.oy) not in self.oldpoints :#not in [self.startpoint,self.endpoint] :
self.oldpoints.append((self.ox,self.oy))
if hasattr(self,"curoval"):
if self.curoval not in self.curovals:
self.curovals.append(self.curoval)
if self.CLICK_NODRAG==1:
#finding out points around the selected point
for i in range(0,10):
xcoords.append(self.OrgX-i)
ycoords.append(self.OrgY-i)
xcoords.append(self.OrgX+i)
ycoords.append(self.OrgY+i)
if xcoords!=[] and ycoords!=[]:
for x in xcoords:
for y in ycoords:
CtlPoints.append((x,y))
for c in CtlPoints:
if c in self.oldpoints:
ind=self.oldpoints.index(c)
op=self.oldpoints[ind]
if ind>0:
prev_oldpoint=self.oldpoints[ind-1]
else:
prev_oldpoint=self.endpoint
del self.oldpoints[ind]
for co in self.curovals:
ov_point1=self.canvas.coords(co)
if len(ov_point1)!=0:
ov_point=(int(ov_point1[0]+2),int(ov_point1[1]+2))
if ov_point==c and ov_point not in [self.startpoint,self.endpoint]:
self.canvas.delete(co)
self.curovals.remove(co)
if hasattr(self,"curx"):
if ov_point==(self.curx,self.cury):
(self.curx,self.cury)=prev_oldpoint
self.draw()
if self.mousebuttonup:
self.newd1ramp=self.caluculate_ramp()
self.callbacks.CallCallbacks(self.newd1ramp)
self.history.append((deepCopySeq(self.oldpoints),self.d1scalewheel.get()))
def OnCanvasMouseDrag(self,event):
self.CLICK_NODRAG=0
CtlPoints=[]
xcoords=[]
ycoords=[]
#making active clickrange to be ten points around clicked point
for i in range(0,10):
xcoords.append(self.OrgX-i)
ycoords.append(self.OrgY-i)
xcoords.append(self.OrgX+i)
ycoords.append(self.OrgY+i)
if xcoords!=[] and ycoords!=[]:
for x in xcoords:
for y in ycoords:
CtlPoints.append((x,y))
for c in CtlPoints:
if c in self.oldpoints:
ind=self.oldpoints.index(c)
op=self.oldpoints[ind]
del self.oldpoints[ind]
for co in self.curovals:
ov_point1=self.canvas.coords(co)
if len(ov_point1)!=0:
ov_point=(int(round(ov_point1[0],3))+2,int(round(ov_point1[1],3))+2)
if ov_point==c :
self.canvas.delete(co)
self.curovals.remove(co)
self.curx=dx=event.x
self.cury=dy=event.y
self.draw()
def draw(self):
"""Draws line,ovals with current controlpoints. """
new1points=[]
curve_points=[]
self.smoothened_points=[]
if self.CLICK_NODRAG==0:
dx=self.curx
dy=self.cury
else:
(dx,dy)=(self.curx,self.cury)=(self.endpoint)
###Limiting xcoords of the current point not to cross adjacent points
if hasattr(self,"limit_xcoord"):
if self.limit_xcoord!=[]:
self.limit_xcoord.sort()
if (self.curx,self.cury) not in [self.startpoint,self.endpoint]:
if (self.curx,self.cury)< self.limit_xcoord[0]:
if self.curx<=self.limit_xcoord[0][0] and self.cury<self.limit_xcoord[0][1]:
dx=self.curx=self.limit_xcoord[0][0]+1
if self.curx<=self.limit_xcoord[0][0] and self.cury>self.limit_xcoord[0][1]:
dx=self.curx=self.limit_xcoord[0][0]
if (self.curx,self.cury)> self.limit_xcoord[1]:
if self.curx>=self.limit_xcoord[1][0] and self.cury>self.limit_xcoord[1][1]:
dx=self.curx=self.limit_xcoord[1][0]-1
if self.curx>=self.limit_xcoord[1][0] and self.cury<self.limit_xcoord[1][1]:
dx=self.curx=self.limit_xcoord[1][0]
#Limit graph with in the axis
if self.curx not in range(50,305):
if self.curx<50:
self.curx=dx=50
else:
self.curx=dx=305
if self.cury not in range(20,275):
if self.cury<20:
self.cury=dy=20
else:
self.cury=dy=275
#adding start,end points
new1points.append(self.startpoint)
new1points.append(self.endpoint)
#adding current point to list
if (dx,dy) not in new1points and (dx,dy) not in [self.startpoint,self.endpoint]:
new1points.append((dx,dy))
#adding oldpoints to list
if hasattr(self,"ox"):
for op in self.oldpoints:
if op not in new1points:
new1points.append(op)
new1points.sort()
#removing oval point that is on drag
if hasattr(self,"curoval"):
if self.curoval not in self.curovals:
self.canvas.delete(self.curoval)
self.canvas.delete(self.curline)
#if points that start with 50 or 51 or 305,304 other than start ,end
#points exists remove start or end points
#remove ovals
#finding oval for start point and endpoint
for i in new1points:
if i[0]==51 or i[0]==50:
if i!=self.startpoint:
if self.startpoint in new1points:
new1points.remove(self.startpoint)
###removing start point oval
x = 50
y = 275
st_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if st_oval_1:
for so in st_oval_1:
if so!=[]:
st_oval=so
st_oval_coords=self.canvas.coords(st_oval)
if (int(st_oval_coords[0]+2),int(st_oval_coords[1]+2))==self.startpoint:
self.canvas.delete(st_oval)
if st_oval in self.curovals:
self.curovals.remove(st_oval)
for i in new1points:
if i[0]==304 or i[0]==305:
if i!=self.endpoint :
if self.endpoint in new1points:
new1points.remove(self.endpoint)
###removing end point oval
x = 305
y = 20
end_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if end_oval_1:
for eo in end_oval_1:
if eo!=[]:
end_oval=eo
end_oval_coords=self.canvas.coords(end_oval)
if (int(end_oval_coords[0]+2),int(end_oval_coords[1]+2))==self.endpoint:
self.canvas.delete(end_oval)
if end_oval in self.curovals:
self.curovals.remove(end_oval)
new1points.sort()
for (x,y) in new1points:
curve_points.append(x)
curve_points.append(y)
self.smoothened_points= self.smooth(curve_points)
#drawing line
if len(self.smoothened_points)>2:
if self.Smooth:
self.curline=self.canvas.create_line(self.smoothened_points)
else:
self.curline=self.canvas.create_line(curve_points)
else:
if curve_points[0]==50 or 51:
if self.Smooth:
self.curline=self.canvas.create_line(curve_points,smooth=1)
else:
self.curline=self.canvas.create_line(curve_points)
else:
self.curline=self.canvas.create_line(self.startpoint,self.endpoint)
##Adding oval when start or end point in new1points
coval_coords=[]
for i in self.curovals:
coval_coords.append(self.canvas.coords(i))
if self.endpoint in new1points:
co=self.canvas.create_oval(self.endpoint[0]-2,self.endpoint[-1]-2,self.endpoint[0]+2,self.endpoint[-1]+2,width=1,outline='black',fill='black')
endco_coords =self.canvas.coords(co)
if endco_coords not in coval_coords:
self.curovals.append(co)
if self.startpoint in new1points:
co=self.canvas.create_oval(self.startpoint[0]-2,self.startpoint[-1]-2,self.startpoint[0]+2,self.startpoint[-1]+2,width=1,outline='black',fill='black')
startco_coords=self.canvas.coords(co)
if startco_coords not in coval_coords:
self.curovals.append(co)
#drawing ovals
if (self.curx,self.cury)!=self.endpoint:
self.curoval=self.canvas.create_oval(self.curx-2,self.cury-2,self.curx+2,self.cury+2,width=1,outline='black',fill='black')
if (self.curx,self.cury)==self.endpoint and self.endpoint in new1points:
self.curoval=self.canvas.create_oval(self.curx-2,self.cury-2,self.curx+2,self.cury+2,width=1,outline='black',fill='black')
self.newd1ramp= self.caluculate_ramp()
if self.continuous:
self.callbacks.CallCallbacks(self.newd1ramp)
######## convert coordinates to ramp##################
def caluculate_ramp(self):
"""
"""
dramp=[]
mypoints=[]
mynewpoints=[]
self.oldpoints.sort()
calcpoints=[]
#if self.continuous :
if hasattr(self,"curx"):
if (self.curx,self.cury) not in self.oldpoints and (self.curx,self.cury) not in [self.startpoint,self.endpoint]:
calcpoints.append((self.curx,self.cury))
if len(self.oldpoints)!=0:
for o in self.oldpoints:
if o not in calcpoints:
calcpoints.append(o)
if self.startpoint not in calcpoints:
calcpoints.append(self.startpoint)
if self.endpoint not in calcpoints:
calcpoints.append(self.endpoint)
calcpoints.sort()
length=len(calcpoints)
for l in range(length):
if l+1<=length-1:
mypoints=[calcpoints[l],calcpoints[l+1]]
if calcpoints[l] not in mynewpoints:
mynewpoints.append( calcpoints[l])
(x1,y1)=calcpoints[l]
(x2,y2)=calcpoints[l+1]
if x1>x2:
dcx=x1-x2
px=x1-1
else:
dcx=x2-x1
px=x1+1
if y1>y2:
dcy=y1-y2
if dcx>=1:
py=y1-float(dcy)/float(dcx)
else:
py=y1
else:
dcy=y2-y1
if dcx>=1:
py=y1+float(dcy)/float(dcx)
else:
py=y2
mynewpoints.append( (px,int(round(py))))
for dc in range(dcx-1):
if x1>x2:
px=px-1
else:
px=px+1
if y1>y2:
if dcx>=1:
py=py-float(dcy)/float(dcx)
else:
py=y1
else:
if dcx>=1:
py=py+float(dcy)/float(dcx)
else:
py=y2
mynewpoints.append( (px,int(round(py))))
ramp=[]
for r in mynewpoints:
#scale
ra=float(275-r[1])
if ra>=256:
ra=255.0
ramp.append(ra)
dramp=Numeric.array(ramp,'f')
if len(dramp)!=0:
return dramp
else:
dramp=Numeric.arange(0,256,1,'f')
return dramp
def get(self):
if hasattr(self,"newd1ramp"):
return self.newd1ramp
else:
return self.caluculate_ramp()
def configure(self, **kw):
if 'type' in kw.keys(): # make sure type is set first
self.setType(kw['type'])
del kw['type']
for key,value in kw.items():
if key=='callback':
self.setCallbacks(value)
def setCallbacks(self, cb):
"""Set widget callback. Must be callable function. Callback is called
every time the widget value is set/modified"""
assert cb is None or callable(cb) or type(cb) is types.ListType,\
"Illegal callback: must be either None or callable. Got %s"%cb
if cb is None: return
elif type(cb) is types.ListType:
for func in cb:
assert callable(func), "Illegal callback must be callable. Got %s"%func
self.callbacks.AddCallback(func)
else:
self.callbacks.AddCallback(cb)
self.callback = cb
def invertGraph(self):
"""This function is for inverting graph by reverse computing controlpoints"""
if self.history!=[]:
if self.history[-1][1]!=self.d1scalewheel.get():
self.history[-1]=(self.history[-1][0],self.d1scalewheel.get())
invert_points=[]
#self.oldpoints=[]
points=self.getControlPoints()
if len(points)<2:
points=[self.startpoint,self.endpoint]
for p in points:
if p[1] in range(20,276):
y=275 -(p[1]-20)
invert_points.append((p[0],y))
self.reset()
###################################################
#Some times start and end points are not deleted
#So for deleting them canvas.find_enclosed points at
#startpoint and endpoint are caluculated(returns alist of
#canvas objects present there) and if the coords of
#any canvas objects matches with start or end point that gets deleted
#####################################################
x = 50
y = 275
st_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if st_oval_1:
for so in st_oval_1:
if so!=[]:
st_oval=so
st_oval_coords=self.canvas.coords(st_oval)
if (int(st_oval_coords[0]+2),int(st_oval_coords[1]+2))==self.startpoint:
self.canvas.delete(st_oval)
if st_oval in self.curovals:
self.curovals.remove(st_oval)
x = 305
y = 20
end_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if end_oval_1:
for eo in end_oval_1:
if eo!=[]:
end_oval=eo
end_oval_coords=self.canvas.coords(end_oval)
if (int(end_oval_coords[0]+2),int(end_oval_coords[1]+2))==self.endpoint:
self.canvas.delete(end_oval)
if end_oval in self.curovals:
self.curovals.remove(end_oval)
self.canvas.delete(self.curline)
if self.Smooth:
self.curline=self.canvas.create_line(invert_points,smooth=1)
else:
self.curline=self.canvas.create_line(invert_points)
self.oldpoints=invert_points
for p in invert_points:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
(self.curx,self.cury) =invert_points[-2]
if self.continuous or self.mousebuttonup:
self.newd1ramp=self.caluculate_ramp()
self.callbacks.CallCallbacks([self.newd1ramp])
self.history.append((deepCopySeq(self.oldpoints),self.d1scalewheel.get()))
def defaultcurve_cb(self):
"""draws curve with default points"""
if self.history!=[]:
if self.history[-1][1]!=self.d1scalewheel.get():
self.history[-1]=(self.history[-1][0],self.d1scalewheel.get())
points=[]
self.default_points=[]
self.oldpoints=[]
self.d1scalewheel.set(0.013)
self.default_points=[(50,275),(88, 238), (101, 150), (154, 78), (75, 271),(305,20)]
self.reset()
self.canvas.delete(self.curline)
self.default_points.sort()
if self.Smooth:
self.curline=self.canvas.create_line(self.default_points,smooth=1)
else:
self.curline=self.canvas.create_line(self.default_points)
self.oldpoints=self.default_points
for p in self.default_points:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
(self.curx,self.cury) =self.default_points[-2]
if self.continuous or self.mousebuttonup:
self.newd1ramp=self.caluculate_ramp()
self.callbacks.CallCallbacks(self.newd1ramp)
self.history.append((deepCopySeq(self.oldpoints),self.d1scalewheel.get()))
self.default_ramp= self.newd1ramp
def read_cb(self):
fileTypes = [("Graph",'*_Graph.py'), ("any file",'*.*')]
fileBrowserTitle = "Read Graph"
fileName = self.fileOpenAsk(types=fileTypes,
title=fileBrowserTitle)
if not fileName:
return
self.read(fileName)
def read( self,fileName):
if self.history!=[]:
if self.history[-1][1]!=self.d1scalewheel.get():
self.history[-1]=(self.history[-1][0],self.d1scalewheel.get())
fptr=open(fileName,"r")
data=fptr.readlines()
cpoints=data[0][:-1]
sensitivity=data[1]
self.d1scalewheel.set(eval(sensitivity))
if len(cpoints)==0:
return
else:
points=cpoints
self.oldpoints=[]
self.reset()
if hasattr(self,"curline"):
self.canvas.delete(self.curline)
for c in self.curovals:
self.canvas.delete(c)
self.curovals.remove(c)
if hasattr(self,"curoval"):
self.canvas.delete(self.curoval)
self.curovals=[]
if self.Smooth:
self.curline=self.canvas.create_line(eval(points),smooth=1)
else:
self.curline=self.canvas.create_line(eval(points))
self.readpoints=self.oldpoints=eval(points)[1:-1]
for p in eval(points)[1:-1]:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
(self.curx,self.cury) =eval(points)[-2]
self.history.append((deepCopySeq(self.oldpoints),self.d1scalewheel.get()))
def fileOpenAsk(self, idir=None, ifile=None, types=None,
title='Open'):
if types==None: types = [ ('All files', '*') ]
file = tkFileDialog.askopenfilename( filetypes=types,
initialdir=idir,
initialfile=ifile,
title=title)
if file=='': file = None
return file
def write_cb(self):
fileTypes = [("Graph",'*_Graph.py'), ("any file",'*.*')]
fileBrowserTitle = "Write Graph"
fileName = self.fileSaveAsk(types=fileTypes,
title=fileBrowserTitle)
if not fileName:
return
self.write(fileName)
def write(self,fileName):
fptr=open(fileName,"w")
points= self.getControlPoints()
points.sort()
fptr.write(str(points))
fptr.write("\n")
fptr.write(str(self.d1scalewheel.get()))
fptr.close()
def fileSaveAsk(self, idir=None, ifile=None, types = None,
title='Save'):
if types==None: types = [ ('All files', '*') ]
file = tkFileDialog.asksaveasfilename( filetypes=types,
initialdir=idir,
initialfile=ifile,
title=title)
if file=='': file = None
return file
def reset(self):
"""This function deletes current line removes current ovals"""
self.canvas.delete(self.curline)
self.oldpoints=[]
for c in self.curovals:
self.canvas.delete(c)
if hasattr(self,"curoval"):
self.canvas.delete(self.curoval)
self.curovals=[]
if hasattr(self,"curoval"):
delattr(self,"curoval")
if hasattr(self,"curx"):
delattr(self,"curx")
def resetAll_cb(self):
"""Resetting curve as slant line 0 to 255"""
self.reset()
self.curline=self.canvas.create_line([self.startpoint,self.endpoint],width=1,fill='black')
for p in [self.startpoint,self.endpoint]:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
self.oldpoints=[self.startpoint,self.endpoint]
(self.curx,self.cury)=self.endpoint
self.d1scalewheel.set(0.013)
if self.continuous or self.mousebuttonup:
self.newd1ramp=Numeric.arange(0,256,1,'f')
self.callbacks.CallCallbacks(self.newd1ramp)
#self.histvar.set(0)
self.history=[]
def stepBack_cb(self):
"""when stepBack button clicked previous step is displayed.History of
all the steps done is remembered and when stepback clicked from history
list previous step is shown and that step is removed from history list """
if self.history!=[]:
if len(self.history)==1:
self.resetAll_cb()
else:
del self.history[-1]
pns = self.history[-1][0]
#deleting
self.oldpoints=pns
self.canvas.delete(self.curline)
for c in self.curovals:
self.canvas.delete(c)
if hasattr(self,"curoval"):
self.canvas.delete(self.curoval)
self.curovals=[]
###################################################
#Some times start and end points are not deleted
#So for deleting them canvas.find_enclosed points at
#startpoint and endpoint are caluculated(returns alist of
#canvas objects present there) and if the coords of
#any canvas objects matches with start or end point that gets deleted
#####################################################
x = 50
y = 275
st_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if st_oval_1:
for so in st_oval_1:
if so!=[]:
st_oval=so
st_oval_coords=self.canvas.coords(st_oval)
if (int(st_oval_coords[0]+2),int(st_oval_coords[1]+2))==self.startpoint:
self.canvas.delete(st_oval)
if st_oval in self.curovals:
self.curovals.remove(st_oval)
x = 305
y = 20
end_oval_1= self.canvas.find_enclosed(x-3,y-3,x+3,y+3)
if end_oval_1:
for eo in end_oval_1:
if eo!=[]:
end_oval=eo
end_oval_coords=self.canvas.coords(end_oval)
if (int(end_oval_coords[0]+2),int(end_oval_coords[1]+2))==self.endpoint:
self.canvas.delete(end_oval)
if end_oval in self.curovals:
self.curovals.remove(end_oval)
pns.sort()
#if no start or end points
if pns[0][0]>51 :
pns.insert(0,self.startpoint)
l=len(pns)
if pns[-1][0]<304:
pns.insert(l,self.endpoint)
#if start or endpoints and points with (50or 51) or (305or305)
if self.startpoint in pns:
for p in pns:
if p!=self.startpoint:
if p[0]== 50 or p[0]==51:
pns.remove(self.startpoint)
if self.endpoint in pns:
for p in pns:
if p!=self.endpoint:
if p[0]==305 or p[0]==304:
pns.remove(self.endpoint)
print pns
if self.Smooth:
self.curline=self.canvas.create_line(pns,width=1,fill='black',smooth=1)
else:
self.curline=self.canvas.create_line(pns,width=1,fill='black')
for p in pns:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
self.d1scalewheel.set(self.history[-1][1])
if self.continuous or self.mousebuttonup:
self.newd1ramp=Numeric.arange(0,256,1,'f')
self.callbacks.CallCallbacks(self.newd1ramp)
(self.curx,self.cury)=self.endpoint
def getControlPoints(self):
"""fuction to get current control points of the curve"""
if not self.oldpoints==[self.startpoint,self.endpoint]:
for i in range(len(self.oldpoints)):
if self.startpoint in self.oldpoints:
self.oldpoints.remove(self.startpoint)
if self.endpoint in self.oldpoints:
self.oldpoints.remove(self.endpoint)
self.controlpoints=[]
if hasattr(self,"curoval"):
c=self.canvas.coords(self.curoval)
if len(c)!=0:
if (int(c[0]+2),int(c[1]+2)) not in self.oldpoints and (int(c[0]+2),int(c[1]+2)) not in [self.startpoint,self.endpoint]:
self.controlpoints.append((int(c[0]+2),int(c[1]+2)))
for op in self.oldpoints:
self.controlpoints.append(op)
self.controlpoints.sort()
if len(self.controlpoints)>0:
if self.controlpoints[0][0]==50 or self.controlpoints[0][0]==51 :
pass
else:
self.controlpoints.append(self.startpoint)
self.controlpoints.sort()
if self.controlpoints[-1][0]==305 or self.controlpoints[-1][0]==304:
pass
else:
self.controlpoints.append(self.endpoint)
self.controlpoints.sort()
return self.controlpoints
def setControlPoints(self,points):
"""function to set curve control points"""
assert isinstance(points, types.ListType),"Illegal type for points"
for (x,y) in points:
assert x in range(50,306),"coordinates are out of range,x should be in [50,305]"
assert y in range(20,276),"coordinates are out of range,y should be in [20,275]"
self.oldpoints=[]
self.controlpoints=[]
self.reset()
self.oldpoints=self.controlpoints=points
self.controlpoints.sort()
if self.controlpoints[0]!=self.startpoint:
self.controlpoints.append(self.startpoint)
if self.controlpoints[-1]!=self.endpoint:
self.controlpoints.append(self.endpoint)
self.canvas.delete(self.curline)
self.controlpoints.sort()
if self.Smooth:
self.curline=self.canvas.create_line( self.controlpoints,smooth=1)
else:
self.curline=self.canvas.create_line( self.controlpoints)
for p in self.controlpoints[1:-1]:
self.curoval=self.canvas.create_oval(p[0]-2,p[1]-2,p[0]+2,p[1]+2,width=1,outline='black',fill='black')
self.curovals.append(self.curoval)
(self.curx,self.cury)= self.controlpoints[-2]
self.history.append((deepCopySeq(self.oldpoints),self.d1scalewheel.get()))
if self.continuous or self.mousebuttonup:
self.newd1ramp=self.caluculate_ramp()
self.callbacks.CallCallbacks(self.newd1ramp)
def setSensitivity(self,val):
self.d1scalewheel.set(val)
def Update(self):
if self.update==1:
dramp=self.caluculate_ramp()
self.newd1ramp=dramp
self.callbacks.CallCallbacks(dramp)
def dismiss_cb(self):
try:
if self.master.winfo_ismapped():
self.master.withdraw()
except:
if self.master.master.winfo_ismapped():
self.master.master.withdraw()
#draw Histogram
def removeHistogram(self):
"""removes Histograms"""
for b in self.bars:
self.canvas.delete(b)
self.bars=[]
def drawHistogram(self):
"""This function draws histogram from list of pixel counts ,one for
each value in the source image"""
self.removeHistogram()
if self.histvar.get():
h=self.histvalues
if h==[]:
return
list_pixels_count=h
c=[]
maxc=max(list_pixels_count)
if maxc==0:
return
if list_pixels_count.index(maxc):
list_pixels_count.remove(maxc)
list_pixels_count.insert(255,0)
for i in list_pixels_count[:256]:
max_list=max(list_pixels_count)
if max_list==0:
return
val=i*200/max_list
c.append(val)
for i in range(0,len(c)):
x1=50+i
x2=50+i
y1=275-c[i]
y2=275
r=self.canvas.create_line([(x1,y1),(x2,y2)],fill="gray70",width=1)
self.bars.append(r)
#displaying line and ovals ontop
self.canvas.tkraise(self.curline)
for i in self.curovals:
self.canvas.tkraise(i)
if hasattr(self,"curoval"):
self.canvas.tkraise(self.curoval)
self.canvas.update()
##Update Histograms on Graphtool
#if self.update!=1:
# prev_option=self.optionType.get()
# self.optionType.set(2)
# self.update=1
# self.Update()
# self.optionType.set(prev_option)
# self.update=0
# return
################SMOOTHING CODE############################
def addcurve(self,out, xy, steps):
add = out.append
for i in range(1, steps+1):
t = float(i) / steps; t2 = t*t; t3 = t2*t
u = 1.0 - t; u2 = u*u; u3 = u2*u
add(xy[0]*u3 + 3*(xy[2]*t*u2 + xy[4]*t2*u) + xy[6]*t3)
add(xy[1]*u3 + 3*(xy[3]*t*u2 + xy[5]*t2*u) + xy[7]*t3)
def smooth(self,xy, steps=12):
if not xy:
return xy
closed = xy[0] == xy[-2] and xy[1] == xy[-1]
out = []
if closed:
# connect end segment to first segment
control = (
0.500*xy[-4] + 0.500*xy[0],
0.500*xy[-3] + 0.500*xy[1],
0.167*xy[-4] + 0.833*xy[0],
0.167*xy[-3] + 0.833*xy[1],
0.833*xy[0] + 0.167*xy[2],
0.833*xy[1] + 0.167*xy[3],
0.500*xy[0] + 0.500*xy[2],
0.500*xy[1] + 0.500*xy[3],
)
out = [control[0], control[1]]
self.addcurve(out, control, steps)
else:
out = [xy[0], xy[1]]
for i in range(0, len(xy)-4, 2):
if i == 0 and not closed:
control = (xy[i],xy[i+1],0.333*xy[i] + 0.667*xy[i+2],0.333*xy[i+1] + 0.667*xy[i+3],)
else:
control = (
0.500*xy[i] + 0.500*xy[i+2],
0.500*xy[i+1] + 0.500*xy[i+3],
0.167*xy[i] + 0.833*xy[i+2],
0.167*xy[i+1] + 0.833*xy[i+3],
)
if i == len(xy)-6 and not closed:
control = control + (
0.667*xy[i+2] + 0.333*xy[i+4],
0.667*xy[i+3] + 0.333*xy[i+5],
xy[i+4],
xy[i+5],
)
else:
control = control + (
0.833*xy[i+2] + 0.167*xy[i+4],
0.833*xy[i+3] + 0.167*xy[i+5],
0.500*xy[i+2] + 0.500*xy[i+4],
0.500*xy[i+3] + 0.500*xy[i+5],
)
if ((xy[i] == xy[i+2] and xy[i+1] == xy[i+3]) or
(xy[i+2] == xy[i+4] and xy[i+3] == xy[i+5])):
out.append(control[6])
out.append(control[7])
else:
self.addcurve(out, control, steps)
return out
```
#### File: BasicWidgets/Tk/KeyboardEntry.py
```python
import sys
from Tkinter import Toplevel, Label
from mglutil.gui import widgetsOnBackWindowsCanGrabFocus
class KeyboardEntry:
"""Mixin class that can be used to add the ability to type values for
widget. When the cursor enters the widget the focus is set to the widget
and the widget that had the focus previousy is saved in .lastFocus.
When the cursor leaves the widget focus is restored to self.lastFocus.
key_cb(event) is called upon KeyRelease events. If this is the first keytroke
an undecorated window is created next to the cursor and handleKeyStroke(event)
is called. This method should be subclassed to modify the way the string is
typed in (see thumbwheel.py for an example of handling numbers only).
When the Return key is pressed, the entry window is destroyed and if the
typed striong is not empty self.callSet(self.typedValue) is called.
If the cursor moves out of the widget before Rrturn is pressed the value
in the entry window is discarded and the entry window is destroyed.
"""
def __init__(self, widgets, callSet):
# callSet is a function taking one argument (string) which will be
# when the Returnm key is hit (if the typed string is not empty)
# widgets is a list of Tkinter wigets for which <Enter>, <Leave>
# <Return> and <KeyRelease> are handled. These widgets has to exist
# before thsi constructor can be called
assert callable(callSet)
self.callSet = callSet
for w in widgets:
w.bind("<Enter>", self.enter_cb)
w.bind("<Leave>", self.leave_cb)
w.bind("<Return>", self.return_cb)
w.bind("<KeyRelease>", self.key_cb)
self.typedValue = '' # string accumulating valuescharacters typed
self.lastFocus = None # widget to which the focus will be restored
# when the mouse leaves the widget
self.topEntry = None # top level for typing values
self.typedValueTK = None #Tk label used as entry for value
def key_cb(self, event=None):
# call back function for keyboard events (except for Return)
# handle numbers to set value
key = event.keysym
if key=='Return': return
#print 'Key:', key
if len(self.typedValue)==0 and self.topEntry is None:
# create Tk label showing typed value
x = event.x
y = event.y
#print 'create entry'
self.topEntry = Toplevel()
self.topEntry.overrideredirect(1)
w = event.widget
if event.x >= 0:
self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() + event.x+10,
w.winfo_rooty() + event.y))
else:
self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() +10,
w.winfo_rooty() ))
self.typedValueTK = Label(
master=self.topEntry, text='', relief='sunken', bg='yellow')
self.typedValueTK.pack()
self.handleKeyStroke(event)
def leave_cb(self, event=None):
# make sure widget gets keyboard events
# print 'leave', event.widget
if self.topEntry:
self.typedValueTK.destroy()
self.topEntry.destroy()
self.topEntry = None
self.typedValue = ''
if self.lastFocus:
#print 'restoring focus'
if widgetsOnBackWindowsCanGrabFocus is False:
lActiveWindow = self.lastFocus.focus_get()
if lActiveWindow is not None \
and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ):
return
self.lastFocus.focus_set()
self.lastFocus = None
event.widget.config(cursor='')
def enter_cb(self, event=None):
# make sure widget gets keyboard events
#print 'enter', event.widget
if widgetsOnBackWindowsCanGrabFocus is False:
lActiveWindow = event.widget.focus_get()
if lActiveWindow is not None \
and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ):
return
if self.lastFocus is None:
#print 'setting focus'
self.lastFocus = self.focus_lastfor()
event.widget.focus_set()
event.widget.config(cursor='xterm')
def return_cb(self, event):
# return should destroy the topEntry
#print "return_cb"
if self.typedValueTK is not None:
self.typedValueTK.destroy()
if self.topEntry is not None:
self.topEntry.destroy()
self.topEntry = None
if len(self.typedValue):
#print 'setting to', self.type(self.typedValue)
self.callSet(self.typedValue)
self.typedValue = ''
## TO BE SUBCLASSED
def handleKeyStroke(self, event):
# by default we handle delete character keys
key = event.keysym
if key=='BackSpace' or key=='Delete':
self.typedValue = self.typedValue[:-1]
self.typedValueTK.configure(text=self.typedValue)
```
#### File: gui/Spline/splineGUI.py
```python
import Tkinter
from math import sqrt
from mglutil.util.callback import CallbackFunction
from mglutil.util.misc import deepCopySeq
from spline import Spline
import copy
class splineGUI:
"""Draw a spline that can be edited
the self.canvas on which to draw is provided as an argument
the viewport provides the coordinates on the self.canvas of the lower left corner
and the width and height of the drawing area.
uniqueID is a string that is used as a tag for self.canvas items for this GUI. It
should not be used by items on the self.canvas not created by this object.
doubleClick on control points to add or delete a point.
rightClick to tie or untie normals.
"""
def __init__(self, spline, canvas, viewport, uniqueId, scale = None):
assert isinstance(spline, Spline)
self.spline = spline
self.uniqueId = uniqueId
assert isinstance(canvas, Tkinter.Canvas)
self.canvas = canvas
self.autoScale = False
assert len(viewport) == 4
self.setViewport(viewport)
self.setScale(scale)
self.pointRadius = 2 # radius of a control point
self.drawControlPoints()
self._slopes_0n = 0
self.history_cpts = []
self.history_spline_points = []
self.history_spline_slopes = []
self.history_spline_slopes_lengths =[]
self.slopes_lengths=[]
self._var_ = 1
self.right_dic={}
self.left_dic={}
self.canvas.configure(cursor="cross")
self.drawSlopes()
self.drawFunctionLine()
def setScale(self, scale):
# scale can be an (sx,sy) tuple or None in which case the scale
# is computed automatically to contain the function
if scale is None:
self.doAutoScale()
else:
assert len(scale) == 2
assert isinstance(scale[0], float)
assert isinstance(scale[1], float)
self.scale = scale
def doAutoScale(self):
# compute scaling factors to fit function in viewport
self.autoScale = True
ptx = []
pty = []
pts = self.spline.getControlPoints()
for p in pts:
ptx.append(p[0])
pty.append(p[1])
if pty[-1]<=1.5:
dx=1.0
dy =1.1
else:
minx = min(ptx)
maxx = max(ptx)
dx = maxx-minx
miny = min(pty)*1.1 # FIXME we should really evaluate the fucntion
maxy = max(pty)*1.1 # to find real min and max for y
dy = maxy-miny
self.scale = (self.width/float(dx), self.height/float(dy))
def setViewport(self, viewport):
# portion of the self.canvas on which the function will be drawn
x,y,w,h = viewport
self.originX = x
self.originY = y
self.width = w
self.height = h
self.viewport = viewport
if self.autoScale:
self.doAutoScale()
def drawControlPoints(self):
self.right_dic={}
self.left_dic={}
canvas = self.canvas
pts = self.getControlPoints()
ptRad = self.pointRadius
sx, sy = self.scale
ox = self.originX
oy = self.originY
uid = self.uniqueId
tag = 'ctrlPoints_'+uid
index = 0
for (x, y) in pts:
rx = x
ry = y
id = self.canvas.create_oval(rx-ptRad, ry-ptRad, rx+ptRad, ry+ptRad,
fill = 'black', tags = (tag, uid,
'cp'+str(index)+uid))
cb = CallbackFunction(self.startMoveControlPoint, id, index)
self.canvas.tag_bind(id, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endModeControlPoint, id)
self.canvas.tag_bind(id, '<ButtonRelease-1>', cb)
cb = CallbackFunction(self.deletePoint, id)
self.canvas.tag_bind(id, '<Double-Button-1>', cb)
cb = CallbackFunction(self.tieNormals, id)
self.canvas.tag_bind(id, '<ButtonPress-3>', cb)
index += 1
def removeControlPoints(self):
c = self.canvas
c.delete('ctrlPoints_'+self.uniqueId)
def startEditingCurve(self):
c = self.canvas
c.itemconfigure('ctrlPoints_'+self.uniqueId, fill = 'red')
self.drawSlopes()
def drawSlopes(self):
self._slopes_0n = 1
canvas = self.canvas
pts = self.getControlPoints()
slopes = self.getSlopesVectors()
ptRad = self.pointRadius
sx, sy = self.scale
ox = self.originX
oy = self.originY
uid = self.uniqueId
tag = 'slopes_'+uid
self._points=[]
#index = 0
for p, slope in zip(pts, slopes):
left_slope = None
right_slope = None
ind = slopes.index(slope)
rx = p[0]
ry = p[1]
sll, slr = slope # unpack left and right slope
if sll: # draw vector on left side of the point
vx, vy = sll
if len(self.slopes_lengths)<ind+1:
n = 30/sqrt(vx*vx+vy*vy)
else:
n = 30/sqrt(vx*vx+vy*vy)
if round(n)!=round(self.slopes_lengths[ind][0]):
n= self.slopes_lengths[ind][0]/sqrt(vx*vx+vy*vy)
vx *= n
vy *= n
Ry = ry-vy
Rx = rx-vx
if Rx>rx:
Rx = rx+vx
if Rx<self.originX:
Rx = self.originX
elif Rx>self.originY:
Rx = self.originY
if Ry<self.originX:
Ry = self.originX
elif Ry>self.originY:
Ry=self.originY
lid = self.canvas.create_line(Rx, Ry, rx, ry,
fill = 'black', tags = (tag,
uid,"left","ln"))
tid = self.canvas.create_text((Rx+10, Ry+10),text = round(vy/vx,1), tags = (tag, uid,"left","tx"))
sid = self.canvas.create_oval(Rx-ptRad, Ry-ptRad,
Rx+ptRad, Ry+ptRad,
fill = 'green', tags = (tag,
uid,"left","pt"))
cb = CallbackFunction(self.startMoveSlopePoint, sid, lid,tid)
self.canvas.tag_bind(sid, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endMoveSlopePoint, sid,lid,tid)
self.canvas.tag_bind(sid, '<ButtonRelease-1>', cb)
left_slope = n
self._points.append((Rx,Ry))
self._points.append((rx,ry))
if slr:
vx, vy = slr
if len(self.slopes_lengths)<ind+1:
n = 30/sqrt(vx*vx+vy*vy)
else:
n = 30/sqrt(vx*vx+vy*vy)
if round(n)!=round(self.slopes_lengths[ind][1]):
n= self.slopes_lengths[ind][1]/sqrt(vx*vx+vy*vy)
vx *= n
vy *= n
Ry = ry+vy
Rx = rx+vx
if Rx<rx:
Rx = rx-vx
if Rx>rx:
Rx = rx+vx
if Rx<self.originX:
Rx =self.originX
elif Rx>self.originY:
Rx = self.originY
if Ry<self.originX:
Ry =self.originX
elif Ry>self.originY:
Ry=self.originY
lid = self.canvas.create_line(rx, ry, Rx, Ry,
fill = 'black', tags = (tag,
uid,"right","ln"))
tid = self.canvas.create_text((Rx+10, Ry+10),text = round(vy/vx,1), tags = (tag, uid,"right","tx"))
sid = self.canvas.create_oval(Rx-ptRad, Ry-ptRad,
Rx+ptRad, Ry+ptRad,
fill = 'green', tags = (tag,
uid,"right","pt"))
cb = CallbackFunction(self.startMoveSlopePoint, sid, lid,tid)
self.canvas.tag_bind(sid, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endMoveSlopePoint, sid,lid,tid)
right_slope = n
self._points.append((rx,ry))
self._points.append((Rx,Ry))
if len(self.slopes_lengths)!=len(slopes):
self.slopes_lengths.append((left_slope,right_slope))
self.canvas.tag_raise("pt")
self.canvas.tag_raise('ctrlPoints_'+self.uniqueId)
def stopEditingCurve(self):
self._slopes_0n = 0
c = self.canvas
c.itemconfigure('ctrlPoints_'+self.uniqueId, fill = 'black')
c.delete('slopes_'+self.uniqueId)
def endModeControlPoint(self, cid, index):
c = self.canvas
c.tag_unbind(cid, '<B1-Motion>')
self.appendToHistory()
def findSplinePoints(self):
c=self.canvas
spline_points=[]
self.spline_points=[]
self.n_points=[]
time_steps=[]
for i in range(len(self._points)):
if i%4==0:
if i+3 <=len(self._points)-1 :
p0 = self._points[i]
p1 = self._points[i+1]
p2 = self._points[i+2]
p3 = self._points[i+3]
self.n_points.append([p0,p1,p2,p3])
for j in range(10):
time_steps.append(float(j)/10)
for p in self.n_points:
p0,p1,p2,p3=p
ind_p=self.n_points.index(p)
curve_points=[]
result_points=[]
for t in time_steps:
ind_t = time_steps.index(t)
res = self.spline.beizer_calc(t,p)
result_points.append(res)
curve_points.append(res)
if p0 not in curve_points:
curve_points.append(p0)
if hasattr(self,"id"):
#right
if self.id == "right":
#for i in range(0,len(result_points)):
# if i+1 <= len(result_points)-1:
if result_points[4][0]<result_points[5][0] :
f = ind_p*11#(len(time_steps))
l = (ind_p+1)*11#(len(time_steps))
required_points = self.history_spline_points[-1][f:l]
required_points.reverse()
curve_points=[]
for q in required_points:
curve_points.append(q)
ind = self._points.index(p1)
self._points.remove(self._points[ind])
self._points.insert(ind,p1)
self.point_p1 = self._points[ind]
if hasattr(self,"sid"):
sid = self.sid
if len(c.coords(sid))>0:
[x1,y1,x2,y2] = c.coords(sid)
if self.point_p1[0]>x1 and self.point_p1[0]<x2:
n_x = self.point_p1[0]
if self.point_p1[1]>y1 and self.point_p1[1]<y2:
n_y = self.point_p1[1]
self.right_dic[sid]=(n_x,n_y)
#break
#result_points.reverse()
if self.id == "left":
# for i in range(0,len(result_points)):
# if i+1 <= len(result_points)-1:
if result_points[7][0]>result_points[6][0]:
f = ind_p*11#(len(time_steps))
l = (ind_p+1)*11#(len(time_steps))
required_points = self.history_spline_points[-1][f:l]
required_points.reverse()
curve_points=[]
for q in required_points:
curve_points.append(q)
ind = self._points.index(p2)
point_p2 = self._points[ind]
if hasattr(self,"sid"):
sid = self.sid
if len(c.coords(sid))>0:
[x1,y1,x2,y2] = c.coords(sid)
if point_p2[0]>x1 and point_p2[0]<x2:
n_x = point_p2[0]
if point_p2[1]>y1 and point_p2[1]<y2:
n_y = point_p2[1]
self.left_dic[sid]=(n_x,n_y)
#break
#result_points.reverse()
spline_points.append(curve_points)
for r in spline_points:
r.reverse()
for i in r:
self.spline_points.append(i)
self.history_spline_points.append(deepCopySeq(self.spline_points))
return self.spline_points
def drawFunctionLine(self):
self._line_On = 1
c = self.canvas
uid = self.uniqueId
tag = 'ctrlPoints_'+uid
tag1 = 'line_'+uid
spline_points = self.findSplinePoints()
self.line = id = c.create_line(spline_points,tags = (tag1, uid))
cb = CallbackFunction(self.createPoint, id)
self.canvas.tag_bind(id, '<Double-Button-1>', cb)
self.canvas.tag_raise('ctrlPoints_'+self.uniqueId)
if self.history_cpts==[]:
self.appendToHistory()
#if self.history_cpts==[]:
# self.history_cpts.append(deepCopySeq(self.getControlPoints()))
# self.history_spline_slopes.append((deepCopySeq(self.getSlopesVectors()),deepCopySeq(self.slopes_lengths)))
def removeFunctionLine(self):
self._line_On = 0
c = self.canvas
c.delete('line_'+self.uniqueId)
##
## callbacks
##
def startMoveControlPoint(self, cid, index, event):
# cid of control point and control point index
c = self.canvas
cb = CallbackFunction(self.moveControlPoint, cid, index)
c.tag_bind(cid, '<B1-Motion>', cb)
self.origx = event.x
self.origy = event.y
cpts=self.getControlPoints()
rounded_cpts = []
ind_cpt=None
for p in cpts:
rounded_cpts.append((round(p[0]),round(p[1])))
if (round(c.coords(cid)[0]+2),round(c.coords(cid)[1]+2)) in rounded_cpts:
ind_cpt = rounded_cpts.index((round(c.coords(cid)[0]+2),round(c.coords(cid)[1]+2)))
if (round(c.coords(cid)[2]),round(c.coords(cid)[3])) in rounded_cpts:
ind_cpt = rounded_cpts.index((round(c.coords(cid)[2]),round(c.coords(cid)[3])))
if ind_cpt:
if ind_cpt-1 in range(len(cpts)):
self.p_cpt = rounded_cpts[ind_cpt -1]
if ind_cpt+1 in range(len(cpts)):
self.n_cpt = rounded_cpts[ind_cpt +1]
def moveControlPoint(self, cid, index, event):
c = self.canvas
uid = self.uniqueId
tag = 'ctrlPoints_'+uid
items = c.find_withtag(tag)
x = c.canvasx(event.x)
y = c.canvasy(event.y)
coords = c.coords(cid)
cx1,cy1=(coords[0],coords[1])
#fixing to limit cpts to move with in Viewport
if y>self.originY:
y=self.originY
if y<self.originX:
y=self.originX
#making start ,end points to move along y-axis
if index == 0 or index == len(items)-1:
dx = 0
if index == 0:
x = self.originX
else:
x = self.originY
else:
dx = x-self.origx
if hasattr(self,"p_cpt"):
if x<self.p_cpt[0]:
if cx1>self.p_cpt[0]:
x= self.p_cpt[0]+3
dx = x-cx1+2
else:
dx = 0
if hasattr(self,"n_cpt"):
if x>self.n_cpt[0]:
if cx1<self.n_cpt[0]:
x=self.n_cpt[0]-3
dx = x-cx1-2
else:
dx = 0
if y == self.originY or y == self.originX:
dy = 0
else:
dy = y - self.origy
c.move(cid,dx,dy)
self.origx = event.x
self.origy = event.y
#setting splines Controlpoints with new points.Such that
#spline.getControlPoints returns new control points
cpts = []
sx, sy = self.scale
ox = self.originX
oy = self.originY
for i in items:
cx = c.coords(i)[0]
cy = c.coords(i)[1]
cpts.append((cx+2,cy+2))
self.spline.setControlPoints(cpts,self.getSlopesVectors())
self.id=None
self._drawSpline()
cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
for cid in cids:
if "tied" in c.gettags(cid):
lsid,rsid = self.find_sids(cid)
if lsid!=None and rsid!=None:
c.itemconfigure(lsid, fill = 'blue')
c.itemconfigure(rsid, fill = 'blue')
def startMoveSlopePoint(self, sid, lid,tid, event):
c = self.canvas
self.origx = event.x
self.origy = event.y
self.line_coords = c.coords(lid)
cb = CallbackFunction(self.moveSlopePoint, sid,lid, tid)
c.tag_bind(sid, '<B1-Motion>', cb)
self._var_=1
def moveSlopePoint(self ,sid, lid,tid, event):
c = self.canvas
x = c.canvasx(event.x)
y = c.canvasy(event.y)
other_sid,cid = self.find_othersid(sid)
#when tied ,controlling other_side slope point not to cross viewport limits
if "left" in c.gettags(sid):
c_rid, c_cid= self.find_othersid(sid)
cid = c_cid
self.line_coords = (c.coords(sid)[0]+2,c.coords(sid)[1]+2,c.coords(c_cid)[0]+2,c.coords(c_cid)[1]+2)
if c_cid:
if "tied" in c.gettags(c_cid):
if c_rid:
if c.coords(c_rid)[0]>=self.originY-2:
if x<=c.coords(sid)[0]:
x = c.coords(sid)[0]+2
if c.coords(c_rid)[1]<=self.originX+2:
if y>=c.coords(sid)[1]:
y = c.coords(sid)[1]+2
if c.coords(c_rid)[1]>=self.originY-2:
if y<=c.coords(sid)[1]+2:
y = c.coords(sid)[1]+2
if "right" in c.gettags(sid):
c_lid , c_cid= self.find_othersid(sid)
cid = c_cid
self.line_coords = (c.coords(c_cid)[0]+2,c.coords(c_cid)[1]+2,c.coords(sid)[0]+2,c.coords(sid)[1]+2)
if c_cid:
if "tied" in c.gettags(c_cid):
if c_lid:
if c.coords(c_lid)[0]<=self.originX+2:
if x>=c.coords(sid)[0]:
x = c.coords(sid)[0]+2
if c.coords(c_lid)[1]<=self.originX+2:
if y>=c.coords(sid)[1]:
y = c.coords(sid)[1]+2
if c.coords(c_lid)[1]>=self.originY-2:
if y<=c.coords(sid)[1]+2:
y = c.coords(sid)[1]+2
c.delete(lid)
c.delete(tid)
if hasattr(self,"sid"):
self.old_sid = self.sid
if hasattr(self,"lid"):
self.old_lid=self.lid
self.old_tid =self.tid
if self._var_ == 0:
c.delete(self.lid)
c.delete(self.tid)
uid = self.uniqueId
tag = 'slopes_'+uid
tag1 = 'ctrlPoints_'+uid
current_points = self.getControlPoints()
cpts = []
for i in current_points:
cx = i[0]
cy = i[1]
cpts.append((round(cx),round(cy)))
slope_vectors = self.getSlopesVectors()
cid_coords = []
for i in c.find_withtag("ctrlPoints_"+self.uniqueId):
cid_coords.append(c.coords(i))
if "left" in c.gettags(sid):
self.id = "left"
if self.left_dic!={}:
if sid in self.left_dic.keys():
(px,py) = self.left_dic[sid]
self.left_dic.pop(sid)
if (round(px),round(py))==(round(self.line_coords[0]),round(self.line_coords[1])):
if (x,y)<(px,py):
(x,y)=(px,py)
#limiting left slope in one direction
if x>self.line_coords[2]:
x = self.line_coords[2]
#when slope is infinity
if self.line_coords[2] - x == 0:
x = self.line_coords[2]-2
dx = x-self.line_coords[0]
dy = y-self.line_coords[1]
#moving point
#limiting slope points with in view port
cx,cy = (c.coords(sid)[0]+2,c.coords(sid)[1]+2)
if x<=self.originX:
if cx>=self.originX :
x = self.originX+2
dx = x - cx
else:
dx = 0
x = self.originX+2
if y>=self.originY:
if cy<=self.originY:
y = self.originY-2
dy = y-cy
else:
dy =0
y = self.originY-2
if y<=self.originX:
if cy>=self.originX:
y = self.originX+2
dy = y - cy
else:
dy =0
y = self.originX+2
#if sid coords == cid coords
for i in cid_coords:
if (round(x),round(y)) == (round(i[0]+2),round(i[1]+2)):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx=4
dy =4
if (round(x),round(y)) == (round(i[0]),round(i[1])):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx = 4
dy = 4
if (round(x),round(y)) == (round(i[0]+4),round(i[1]+4)):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx = 4
dy = 4
#checking if tied other sid coords crosses viewport limits before
#moving slope point
if cid:
if "tied" in c.gettags(cid):
coords_other_sid = c.coords(other_sid)
if (coords_other_sid[0]+2)-dx>=self.originY:
dx = -1*(self.originY - (coords_other_sid[0]+2))
x = c.coords(sid)[0]+dx+2
if (coords_other_sid[1]+2)-dy<=self.originX:
dy = ((coords_other_sid[1]+2)-self.originX)
y = c.coords(sid)[1]+dy+2
if (coords_other_sid[1]+2)-dy>=self.originY:
dy = -1*(self.originY - (coords_other_sid[1]+2))
y = c.coords(sid)[1]+dy+2
if x>self.line_coords[2]-6 :
if y in range(int(round(self.line_coords[3]-6)) ,int(round(self.line_coords[3]+6))):
x=self.line_coords[2]-6
dx = (self.line_coords[2]-6) - (c.coords(sid)[0]+2)
if dx%2!=0:
x =x+1
dx = dx+1
#d = x - (self.line_coords[2]-6 )
#d = 6-diff
#if d!=0:
# if d%2!=0:
# x=c.coords(sid)[0]+2-(d+1)
# dx = -(d+1)
#
# else:
# x = c.coords(sid)[0]+2-d
# dx=-d
c.move(sid,dx,dy)
#x,y = (c.coords(sid)[0]+2,c.coords(sid)[1]+2)
#drawing line and text
self.lid = c.create_line((x,y),(self.line_coords[2],self.line_coords[3]),tags = (tag,uid,"left","ln"))
_current_slope_length = sqrt((self.line_coords[2]-x)*(self.line_coords[2]-x)+(self.line_coords[3]-y)*(self.line_coords[3]-y))
_current_slope = (self.line_coords[3] - y)/(self.line_coords[2] - x)
self.tid = self.canvas.create_text((x+10,y+10),text = round(_current_slope,1), tags = (tag, uid,"left","tx"))
#considering radius of point
if (round(self.line_coords[2]),round(self.line_coords[3])) in cpts :
_point_index = cpts.index((round(self.line_coords[2]),round(self.line_coords[3])))
else:
_point_index = cpts.index((round(self.line_coords[2]-2),round(self.line_coords[3]-2)))
right_slope = slope_vectors[_point_index][1]
slope_vectors.remove(slope_vectors[_point_index])
cpt=(round(self.line_coords[2]),round(self.line_coords[3]))
#updating self._points
rx,ry = (round(self.line_coords[0]),round(self.line_coords[1]))
new_p=[]
for i in self._points:
new_p.append((round(i[0]),round(i[1])))
if (rx,ry) in new_p :
ind = new_p.index((rx,ry))
if (rx-2,ry-2) in new_p :
ind = new_p.index((rx-2,ry-2))
if (rx+2,ry+2) in new_p :
ind = new_p.index((rx+2,ry+2))
Ry =y
Rx = x
self._points.remove(self._points[ind])
self._points.insert(ind,(Rx,Ry))
#finding current cid
cids=c.find_withtag(tag1)
coords_cids_rounded = []
for i in cids:
coords_cids = c.coords(i)
coords_cids_rounded.append((round(coords_cids[0]+2),round(coords_cids[1]+2),round(coords_cids[2]),round(coords_cids[3])))
current_id = None
#finding cid
for j in coords_cids_rounded:
if (j[0],j[1])==cpt:
cpt = (j[0]+2,j[1]+2)
ind = coords_cids_rounded.index(j)
current_id= cids[ind]
elif (j[2],j[3])==cpt:
cpt =(j[2],j[3])
ind = coords_cids_rounded.index(j)
if ind >0 and ind <len(coords_cids_rounded)-1:
current_id= cids[ind]
##finding lid,sid,tid with same cpt
for i in c.find_withtag("pt"):
if i>sid:
right_sid = i
break
if current_id:
if "tied" in c.gettags(current_id):
#finding and deleting if right lid and right tid exists
if sid+1 in c.find_all():
r_lid = sid+1
r_tid = sid+2
c.delete(r_lid)
c.delete(r_tid)
right_sl = c.find_withtag("right")
for l,t in zip(c.find_withtag("ln"),c.find_withtag("tx")):
if "right" in c.gettags(l) and "right" in c.gettags(t):
if (round(c.coords(l)[0]),round(c.coords(l)[1]))==(round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(l)
c.delete(t)
if hasattr(self,"old_lid"):
coords_l = c.coords(self.old_lid)
if coords_l!=[]:
if (round(coords_l[0]),round(coords_l[1])) == (round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(self.old_lid)
c.delete(self.old_tid)
if hasattr(self,"right_lid"):
coords_l = c.coords(self.right_lid)
if coords_l!=[]:
if (round(coords_l[0]),round(coords_l[1])) == (round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(self.right_lid)
c.delete(self.right_tid)
right_sid_coords=c.coords(right_sid)
#moving point
#limiting slope point to move with in viewport
c.move(right_sid,-dx,-dy)
new_coords = c.coords(right_sid)
self.right_lid = c.create_line((self.line_coords[2],self.line_coords[3]),(new_coords[2]-2,new_coords[3]-2),tags = (tag,uid,"right","ln"))
self.right_tid = self.canvas.create_text((new_coords[2]-2+10,new_coords[3]-2+10),text = round(_current_slope,1), tags = (tag, uid,"right","tx"))
slope_vectors.insert(_point_index,((1,_current_slope),(1,_current_slope)))
#r_slope = self.slopes_lengths[_point_index][1]
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(_current_slope_length,_current_slope_length))
cb = CallbackFunction(self.startMoveSlopePoint, right_sid, self.right_lid,self.right_tid)
self.canvas.tag_bind(right_sid, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endMoveSlopePoint, right_sid,self.right_lid,self.right_tid)
self.canvas.tag_bind(right_sid, '<ButtonRelease-1>', cb)
#updating self._points
if right_sid_coords:
rx,ry = (round(right_sid_coords[2]),round(right_sid_coords[3]))
new_p=[]
for i in self._points:
new_p.append((round(i[0]),round(i[1])))
if (rx,ry) in new_p :
ind1 = new_p.index((rx,ry))
if (rx-2,ry-2) in new_p :
ind1 = new_p.index((rx-2,ry-2))
if (rx-4,ry-4) in new_p :
ind1 = new_p.index((rx-4,ry-4))
if (rx-4,ry-2) in new_p :
ind1 = new_p.index((rx-4,ry-2))
if (rx-2,ry-4) in new_p :
ind1 = new_p.index((rx-2,ry-4))
Ry =new_coords[3]
Rx = new_coords[2]
self._points.remove(self._points[ind1])
self._points.insert(ind1,(Rx,Ry))
else:
slope_vectors.insert(_point_index,((1,_current_slope),right_slope))
r_slope = self.slopes_lengths[_point_index][1]
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(_current_slope_length,r_slope))
#c.itemconfigure(sid, fill = 'green')
else:
r_slope = self.slopes_lengths[_point_index][1]
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(_current_slope_length,r_slope))
slope_vectors.insert(_point_index,((1,_current_slope),right_slope))
if "right" in c.gettags(sid):
self.id = "right"
if self.right_dic!={}:
if sid in self.right_dic.keys():
(px,py) = self.right_dic[sid]
self.right_dic.pop(sid)
if (round(px),round(py))==(round(self.line_coords[2]),round(self.line_coords[3])):
#if x>px:
if (x,y)>(px,py):
(x,y)=(px,py)
#limiting right slope in one direction
if x<self.line_coords[0]:
x = self.line_coords[0]
#when slope is infinity
if x-self.line_coords[0] == 0:
x = self.line_coords[0]+2
dx = x-self.line_coords[2]
dy = y-self.line_coords[3]
#moving point
#limiting slope point to move with in viewport
cx,cy = (c.coords(sid)[0]+2,c.coords(sid)[1]+2)
if x>=self.originY:
if cx<=self.originY :
x = self.originY-2
dx = x-cx
else:
dx = 0
x = self.originY-2
if y>=self.originY:
if cy<=self.originY:
y = self.originY-2
dy = y-cy
else:
dy =0
y = self.originY-2
if y<=self.originX:
if cy>=self.originX:
y = self.originX+2
dy = y - cy
else:
dy =0
y = self.originX+2
#if sid coords == cid coords
for i in cid_coords:
if (round(x),round(y)) == (round(i[0]+2),round(i[1]+2)):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx=4
dy =4
if (round(x),round(y)) == (round(i[0]),round(i[1])):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx = 4
dy = 4
if (round(x),round(y)) == (round(i[0]+4),round(i[1]+4)):
x =c.coords(sid)[0]+2+4
y = c.coords(sid)[1]+2+4
dx = 4
dy = 4
#checking if tied other sid coords crosses viewport limits
if cid:
if "tied" in c.gettags(cid):
coords_other_sid = c.coords(other_sid)
if (coords_other_sid[0]+2)-dx<=self.originX:
dx = ((coords_other_sid[0]+2)-self.originX)
x = c.coords(sid)[0]+dx+2
if (coords_other_sid[1]+2)-dy<=self.originX:
dy = ((coords_other_sid[1]+2)-self.originX)
y = c.coords(sid)[1]+dy+2
if (coords_other_sid[1]+2)-dy>=self.originY:
dy = -1*(self.originY - (coords_other_sid[1]+2))
y = c.coords(sid)[1]+dy+2
#if x<self.line_coords[0]+6 :
# if y in range(int(round(self.line_coords[1]-6)) ,int(round(self.line_coords[1]+6))):
# x=self.line_coords[0]+6
# dx = (c.coords(sid)[0]+2) - (self.line_coords[0]+6)
# if dx%2!=0:
# x=x+1
# dx = dx+1
c.move(sid,dx,dy)
#drawing line and text
self.lid = c.create_line((self.line_coords[0],self.line_coords[1]),(x,y),tags = (tag,uid,"right","ln"))
_current_slope_length = sqrt((x-self.line_coords[0])*(x-self.line_coords[0])+(y-self.line_coords[1])*(y-self.line_coords[1]))
_current_slope = (y-self.line_coords[1])/(x-self.line_coords[0])
self.tid = c.create_text((x+10,y+10),text = round(_current_slope,1), tags = (tag, uid,"right","tx"))
#considering radius of point
if (round(self.line_coords[0]),round(self.line_coords[1])) in cpts:
_point_index = cpts.index((round(self.line_coords[0]),round(self.line_coords[1])))
else:
_point_index = cpts.index((round(self.line_coords[0]-2),round(self.line_coords[1]-2)))
left_slope = slope_vectors[_point_index][0]
slope_vectors.remove(slope_vectors[_point_index])
cpt=(round(self.line_coords[0]),round(self.line_coords[1]))
#updating self._points which is used to compute beizercurve
rx,ry = (round(self.line_coords[2]),round(self.line_coords[3]))
new_p=[]
for i in self._points:
new_p.append((round(i[0]),round(i[1])))
if (rx,ry) in new_p :
ind = new_p.index((rx,ry))
if (rx-2,ry-2) in new_p:
ind = new_p.index((rx-2,ry-2))
if (rx+2,ry+2) in new_p:
ind = new_p.index((rx+2,ry+2))
Ry =y
Rx = x
self._points.remove(self._points[ind])
self._points.insert(ind,(Rx,Ry))
#finding current cid
cids=c.find_withtag(tag1)
coords_cids_rounded = []
for i in cids:
coords_cids = c.coords(i)
coords_cids_rounded.append((round(coords_cids[0]+2),round(coords_cids[1]+2),round(coords_cids[2]),round(coords_cids[3])))
current_id = None
#finding cid
for j in coords_cids_rounded:
if (j[0],j[1])==cpt:
cpt = (j[0]+2,j[1]+2)
ind = coords_cids_rounded.index(j)
current_id= cids[ind]
elif (j[2],j[3])==cpt:
cpt =(j[2],j[3])
ind = coords_cids_rounded.index(j)
if ind >0 and ind <len(coords_cids_rounded)-1:
current_id= cids[ind]
##finding lid,sid,tid with same cpt
for i in c.find_withtag("pt"):
if i == sid:
ind = list(c.find_withtag("pt")).index(sid)
left_sid=c.find_withtag("pt")[ind-1]
if current_id:
if "tied" in c.gettags(current_id):
#finding and deleting if left lid and left tid exists
if sid-4 in c.find_all():
l_lid = sid-4
l_tid = sid-5
c.delete(l_lid)
c.delete(l_tid)
for l,t in zip(c.find_withtag("ln"),c.find_withtag("tx")):
if "left" in c.gettags(l) and "left" in c.gettags(t):
if (round(c.coords(l)[2]),round(c.coords(l)[3]))==(round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(l)
c.delete(t)
if hasattr(self,"left_lid"):
coords_l = c.coords(self.left_lid)
if coords_l!=[]:
if (round(coords_l[2]),round(coords_l[3])) == (round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(self.left_lid)
c.delete(self.left_tid)
if hasattr(self,"old_lid"):
coords_l = c.coords(self.old_lid)
if coords_l!=[]:
if (round(coords_l[2]),round(coords_l[3])) == (round(c.coords(current_id)[0]+2),round(c.coords(current_id )[1]+2)):
c.delete(self.old_lid)
c.delete(self.old_tid)
#moving point
#limiting slope points with in view port
left_sid_coords = c.coords(left_sid)
c.move(left_sid,-dx,-dy)
new_coords = c.coords(left_sid)
self.left_lid = c.create_line((new_coords[2]-2,new_coords[3]-2),(self.line_coords[0],self.line_coords[1]),tags = (tag,uid,"left","ln"))
self.left_tid = self.canvas.create_text((new_coords[2]-2+10,new_coords[3]-2+10),text = round(_current_slope,1), tags = (tag, uid,"left","tx"))
slope_vectors.insert(_point_index,((1,_current_slope),(1,_current_slope)))
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(_current_slope_length,_current_slope_length))
cb = CallbackFunction(self.startMoveSlopePoint, left_sid, self.left_lid,self.left_tid)
self.canvas.tag_bind(left_sid, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endMoveSlopePoint, left_sid,self.left_lid,self.left_tid)
self.canvas.tag_bind(left_sid, '<ButtonRelease-1>', cb)
#updating self._points
if left_sid_coords:
rx,ry = (round(left_sid_coords[2]),round(left_sid_coords[3]))
new_p=[]
for i in self._points:
new_p.append((round(i[0]),round(i[1])))
if (rx,ry) in new_p :
ind1 = new_p.index((rx,ry))
if (rx-2,ry-2) in new_p :
ind1 = new_p.index((rx-2,ry-2))
if (rx-4,ry-4) in new_p :
ind1 = new_p.index((rx-4,ry-4))
if (rx-4,ry-2) in new_p :
ind1 = new_p.index((rx-4,ry-2))
if (rx-2,ry-4) in new_p :
ind1 = new_p.index((rx-2,ry-4))
Ry =new_coords[3]
Rx = new_coords[2]
self._points.remove(self._points[ind1])
self._points.insert(ind1,(Rx,Ry))
else:
l_slope = self.slopes_lengths[_point_index][0]
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(l_slope,_current_slope_length))
slope_vectors.insert(_point_index,(left_slope,(1,_current_slope)))
else:
l_slope = self.slopes_lengths[_point_index][0]
self.slopes_lengths.remove(self.slopes_lengths[_point_index])
self.slopes_lengths.insert(_point_index,(l_slope,_current_slope_length))
slope_vectors.insert(_point_index,(left_slope,(1,_current_slope)))
cb = CallbackFunction(self.startMoveSlopePoint, sid, self.lid,self.tid)
self.canvas.tag_bind(sid, '<ButtonPress-1>', cb)
cb = CallbackFunction( self.endMoveSlopePoint, sid,self.lid,self.tid)
self.canvas.tag_bind(sid, '<ButtonRelease-1>', cb)
#finding slope and calling spline with new slope
self.spline.setControlPoints(cpts,slope_vectors)
if self._line_On == 1:
self.removeFunctionLine()
self.drawFunctionLine()
#self.line_coords = c.coords(self.lid)
self._var_ = 0
self.canvas.tag_raise('pt')
self.sid = sid
def endMoveSlopePoint(self, sid,lid, tid,index):
c = self.canvas
c.tag_unbind(sid, '<Any-Motion>')
self.appendToHistory()
def createPoint(self,id,event = None):
"""function to insert point on spline"""
c = self.canvas
old_cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
coords = []
for cid in old_cids:
if "tied" in c.gettags(cid):
coords.append([round(c.coords(cid)[0]),round(c.coords(cid)[1]),round(c.coords(cid)[2]),round(c.coords(cid)[3])])
x = event.x
y = event.y
slope = ((1,0),(1,0))
vx1,vy1 = slope[0]
slope_length=(30,30)
pts = self.getControlPoints()
pts.append((x,y))
pts.sort()
ind = pts.index((x,y))
pos = ind
self.slopes_lengths.insert(pos,slope_length)
s_vectors = copy.deepcopy(self.getSlopesVectors())
s_vectors.insert(pos,slope)
self.spline.setControlPoints(pts,s_vectors)
self.drawSpline()
self.appendToHistory()
cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
for cid in cids:
if [round(c.coords(cid)[0]),round(c.coords(cid)[1]),round(c.coords(cid)[2]),round(c.coords(cid)[3])] in coords:
tags = c.gettags(cid)
tags += ("tied",)
if "tied" not in c.gettags(cid):
c.itemconfig(cid,tags = tags)
lsid,rsid = self.find_sids(cid)
if lsid!=None and rsid!=None:
c.itemconfigure(lsid, fill = 'blue')
c.itemconfigure(rsid, fill = 'blue')
def deletePoint(self,id,event = None):
"""function to delete point on spline"""
c = self.canvas
old_cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
coords = []
for cid in old_cids:
if "tied" in c.gettags(cid):
coords.append([round(c.coords(cid)[0]),round(c.coords(cid)[1]),round(c.coords(cid)[2]),round(c.coords(cid)[3])])
p=None
pts = self.getControlPoints()
slopes=copy.deepcopy(self.getSlopesVectors())
cur_point = c.coords(id)
pts = map(lambda p: ((int(round(p[0])),int(round(p[1])))) ,pts)
pn = (round(cur_point[0]+2),round(cur_point[1]+2))
if pn in pts:
p = pn
if p:
ind = pts.index(p)
pts.remove(p)
slope=slopes[ind]
slopes.remove(slope)
self.spline.setControlPoints(pts,slopes)
self.slopes_lengths.remove(self.slopes_lengths[ind])
self.drawSpline()
self.appendToHistory()
cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
for cid in cids:
if [round(c.coords(cid)[0]),round(c.coords(cid)[1]),round(c.coords(cid)[2]),round(c.coords(cid)[3])] in coords:
tags = c.gettags(cid)
tags += ("tied",)
if "tied" not in c.gettags(cid):
c.itemconfig(cid,tags = tags)
lsid,rsid = self.find_sids(cid)
if lsid!=None and rsid!=None:
c.itemconfigure(lsid, fill = 'blue')
c.itemconfigure(rsid, fill = 'blue')
else:
return
def untieNormals(self,cid,event=None):
c=self.canvas
if "tied" in c.gettags(cid):
c.dtag(cid,"tied")
ls,rs = self.find_sids(cid)
if ls!=None and rs!=None:
c.itemconfigure(ls, fill = 'green')
c.itemconfigure(rs, fill = 'green')
cb= CallbackFunction(self.tieNormals, cid)
c.tag_bind(cid, '<ButtonPress-3>', cb)
def tieNormals(self,cid,event=None):
c = self.canvas
cid_coords = c.coords(cid)
cpts= self.getControlPoints()
rounded_cpts=[]
uid = self.uniqueId
tag1 = 'ctrlPoints_'+uid
#if cid is first or last cpts cannot be tied
cs = c.find_withtag(tag1)
if cid ==cs[0] or cid==cs[-1]:
print "cannot tie first and last coords of spline"
return
for p in cpts:
rounded_cpts.append((round(p[0]),round(p[1])))
if (round(cid_coords[0]+2),round(cid_coords[1]+2)) in rounded_cpts :
ind = rounded_cpts.index((round(cid_coords[0]+2),round(cid_coords[1]+2)))
slopes_vectors=self.getSlopesVectors()
slopes_vectors.remove(slopes_vectors[ind])
slopes_vectors.insert(ind,((1,0),(1,0)))
cur_len = 21.6
#if self.slopes_lengths[ind][0]>self.slopes_lengths[ind][1]:
# cur_len = self.slopes_lengths[ind][0]
#else:
# cur_len = self.slopes_lengths[ind][1]
self.slopes_lengths.remove(self.slopes_lengths[ind])
self.slopes_lengths.insert(ind,(cur_len,cur_len))
self.spline.setControlPoints(cpts,slopes_vectors)
if self._slopes_0n == 1:
self.stopEditingCurve()
self.startEditingCurve()
cids = c.find_withtag(tag1)
for ci in cids:
if "tied" in c.gettags(ci):
ls,rs = self.find_sids(ci)
if ls!=None and rs!=None:
c.itemconfigure(ls, fill = 'blue')
c.itemconfigure(rs, fill = 'blue')
if self._line_On == 1:
self.removeFunctionLine()
self.drawFunctionLine()
ls,rs = self.find_sids(cid)
if ls!=None and rs!=None:
c.itemconfigure(ls, fill = 'blue')
c.itemconfigure(rs, fill = 'blue')
tags = c.gettags(cid)
tags += ("tied",)
if "tied" not in c.gettags(cid):
c.itemconfig(cid,tags = tags)
cb= CallbackFunction(self.untieNormals, cid)
c.tag_bind(cid, '<ButtonPress-3>', cb)
def getControlPoints(self):
sx, sy = self.scale
ox = self.originX
oy = self.originY
pts =self.spline.getControlPoints()
cpts = []
for (x, y) in pts:
rx = x
ry = y
if y <= 1.5:
rx = ox + sx*x
ry = oy - sy*y
cpts.append((rx,ry))
self.controlpoints = cpts
return cpts
def find_sids(self,cid):
#finding sids at cid
c=self.canvas
lids = c.find_withtag("ln")
pids = c.find_withtag("pt")
rsids = c.find_withtag("right")
lsids = c.find_withtag("left")
r_lids = []
l_lids = []
r_sids = []
l_sids = []
cid_coords = c.coords(cid)
current_rsid =None
current_lsid = None
for s in pids:
if s in rsids:
r_sids.append(s)
if s in lsids:
l_sids.append(s)
for s in lids:
if s in rsids:
r_lids.append(s)
if s in lsids:
l_lids.append(s)
for r in r_lids:
if (round(c.coords(r)[0]),round(c.coords(r)[1]))==(round(cid_coords[0]+2),round(cid_coords[1]+2)):
current_rlid = r
for i in r_sids:
if (round(c.coords(r)[2]),round(c.coords(r)[3]))==(round(c.coords(i)[0]+2),round(c.coords(i)[1]+2)):
current_rsid = i
for l in l_lids:
if (round(c.coords(l)[2]),round(c.coords(l)[3]))==(round(cid_coords[0]+2),round(cid_coords[1]+2)):
current_llid = l
for i in l_sids:
if (round(c.coords(l)[0]),round(c.coords(l)[1]))==(round(c.coords(i)[0]+2),round(c.coords(i)[1]+2)):
current_lsid = i
return current_lsid,current_rsid
def find_othersid(self,sid):
c=self.canvas
lsids = c.find_withtag("left")
rsids = c.find_withtag("right")
lids = c.find_withtag("ln")
pids = c.find_withtag("pt")
cids = c.find_withtag("ctrlPoints_"+self.uniqueId)
cids_coords = []
for cid in cids:
cids_coords.append(c.coords(cid))
r_lids = []
l_lids = []
r_sids = []
l_sids = []
current_id = None
current_cid = None
for s in pids:
if s in rsids:
r_sids.append(s)
if s in lsids:
l_sids.append(s)
for s in lids:
if s in rsids:
r_lids.append(s)
if s in lsids:
l_lids.append(s)
if "left" in c.gettags(sid):
for l in l_lids:
#llid=sid
if (round(c.coords(l)[0])-2,round(c.coords(l)[1]-2)) == (round(c.coords(sid)[0]),round(c.coords(sid)[1])) or (round(c.coords(l)[0]),round(c.coords(l)[1])) == (round(c.coords(sid)[0]),round(c.coords(sid)[1])) :
current_lid = l
for cid in cids_coords:
#llid=cid
if (round(c.coords(l)[2]),round(c.coords(l)[3])) == (round(cid[2]-2),round(cid[3]-2)):
ind = cids_coords.index(cid)
current_cid = cids[ind]
for r in r_lids:
#cid =rlid
if (round(cid[0]),round(cid[1]))==(round(c.coords(r)[0]-2),round(c.coords(r)[1]-2)):
for p in r_sids:
#rlid=rsid
if (round(c.coords(r)[2]+2),round(c.coords(r)[3]+2)) == (round(c.coords(p)[2]),round(c.coords(p)[3])):
current_id = p
if "right" in c.gettags(sid):
for r in r_lids:
#rlid=rsid
if (round(c.coords(r)[2]+2),round(c.coords(r)[3]+2)) == (round(c.coords(sid)[2]),round(c.coords(sid)[3])) or (round(c.coords(r)[2]),round(c.coords(r)[3])) == (round(c.coords(sid)[2]),round(c.coords(sid)[3])):
for cid in cids_coords:
#cid =rlid
if (round(cid[0]),round(cid[1]))==(round(c.coords(r)[0]-2),round(c.coords(r)[1]-2)):
ind = cids_coords.index(cid)
current_cid = cids[ind]
for l in l_lids:
#llid=cid
if (round(c.coords(l)[2]),round(c.coords(l)[3])) == (round(cid[2]-2),round(cid[3]-2)):
for p in l_sids:
#llid=sid
if (round(c.coords(l)[0])-2,round(c.coords(l)[1]-2)) == (round(c.coords(p)[0]),round(c.coords(p)[1])):
current_id = p
return current_id,current_cid
def drawSpline(self):
self.removeControlPoints()
self.drawControlPoints()
self._drawSpline()
def _drawSpline(self):
if self._slopes_0n == 1:
self.stopEditingCurve()
self.startEditingCurve()
if self._line_On == 1:
self.removeFunctionLine()
self.drawFunctionLine()
def invertSpline(self):
"""This function is for inverting graph by reverse computing controlpoints"""
invert_points = []
cpts = self.getControlPoints()
slopes = self.getSlopesVectors()
for p in cpts:
y=self.originY -(p[1]-50)
invert_points.append((p[0],y))
self.spline.setControlPoints(invert_points,slopes)
self.drawSpline()
self.appendToHistory()
def stepBack(self):
"""when stepBack button clicked previous step is displayed.History of
all the steps done is remembered and when stepback clicked from history
list previous step is shown and that step is removed from history list """
if len(self.history_cpts) == 1:
cpts = self.history_cpts[-1]
slopes = self.history_spline_slopes[-1]
slopes_lengths = self.history_spline_slopes_lengths[-1]
if len(self.history_cpts)>1:
self.history_cpts = self.history_cpts[:-1]
self.history_spline_slopes = self.history_spline_slopes[:-1]
self.history_spline_slopes_lengths = self.history_spline_slopes_lengths[:-1]
cpts = self.history_cpts[-1]
slopes = self.history_spline_slopes[-1]
slopes_lengths = self.history_spline_slopes_lengths[-1]
self.slopes_lengths = []
for j in slopes_lengths :
self.slopes_lengths.append(j)
self.spline.setControlPoints( cpts, slopes)
self.drawSpline()
def appendToHistory(self):
"""function to append to history"""
self.history_cpts.append(copy.deepcopy(self.controlpoints))
self.history_spline_slopes_lengths.append(copy.deepcopy(self.slopes_lengths))
self.history_spline_slopes.append(copy.deepcopy(self.slopesvectors))
def getSlopesVectors(self):
sls = self.spline.getSlopesVectors()
self.slopesvectors = sls
return sls
def setControlPoints(self,pn,sl):
self.spline.setControlPoints(pn,sl)
if __name__ == "__main__":
from spline import Spline
#sp = Spline( [0, .5, 1], [0, .7, 1], [ (None, (1,0)), ((1,1),(1,0)), ((1,0), None) ] )
#sp = Spline([(0,0),(0.3,0.5),(.5,.7),(1,1)],[ (None, (1,-1)), ((1,-3),(1,-4)),((1,-2),(1,-1)), ((1,-3), None) ] )
sp = Spline([(0.0,.5),(1.0,0.3)],[ (None, (1,-1)), ((1,-1), None) ] )
#sp = Spline([(100,600),(200,400),(400,200),(600,100)],[ (None, (1,-4)),((1,-3),(1,-4)),((1,-2),(1,-1)),((2,3), None) ])
canvas = Tkinter.Canvas(width = 700, height = 700)
canvas.pack()
#canvas.configure(cursor="cross")
spg = splineGUI(sp, canvas, (100, 600, 500, 500), 'abc')
#canvas.create_rectangle([100,600,600,100])
spg.drawSlopes()
spg.drawFunctionLine()
```
#### File: mglutil/math/gridDescriptor.py
```python
import string, types, Numeric
class ConstrainedParameterSet:
def __init__(self):
#conDict records constraints between parameters
#key is parm1Name, name of parameter1 ,
#value is list of triples: (parm2Name, func, args)
#changes in parm1 cause parm2 to be updated by func
#eg: to enforce
#self.center = 2*self.offset
#so that changes in self.offset force changes in self.center
#self.conDict['offset'] = [('center', Numeric.multiply, ('offset, 2.0'))]
#to enforce the reciprocal constraint
#so that changes in self.center force changes in self.offset
#self.conDict['center'] = [('offset', Numeric.multiply, ('center,0.5'))]
#suitable functions are Numeric.divide and Numeric.multiply
#DO SOMETHING SO THIS DOESN'T GET into an endless loop
#
self.conDict = {}
#rangeDict provides methods of checking validity
#of a given value for key
#possible types methods include:
#list of discrete values, tuple defining valid range, a type
#or a function which returns 1 if value is valid or 0 if not
self.rangeDict = {}
# values can be integers, floats, strings....???
self.typesList = [type(1), type(1.0), type('a')]
def tie(self, parm1Name, parm2Name, func, args):
#eg:
# changes in self.center force changes in self.offset
# self.tie('center','offset',Numeric.multiply,'center,2.0')
if not self.conDict.has_key(parm1Name):
self.conDict[parm1Name] = []
self.conDict[parm1Name].append((parm2Name, func, args))
#is this at all clear?
#cD = self.conDict
#cD[parm1Name] = cD.get(parm1Name, []).append((parm2Name, func, args))
def updateConstraints(self, parmName):
#called when parm changes to update other linked parms
conList = self.conDict.get(parmName, None)
if not conList:
# do nothing + return
print 'no constraints on ', parmName
return
#conList has tuples (func, args)
#eg: sample value in conList
# (parm2Name, Numeric.multiply, (parmName, 0.5))
for parm2Name, func, args in conList:
#FIX THIS:
#to update self.parm2Name:
# need to get (self.center, 0.5) from args='center, 0.5'
setattr(self,parm2Name, apply(func, eval('self.'+args)))
def untie(self, parm1Name, parm2Name, func, args):
#eg:
#g.untie('center','offset',Numeric.multiply,'center,2.0')
conList = self.conDict.get(parm1Name, None)
if not conList:
print 'no constraints on ', parm1Name
return "ERROR"
if (parm2Name, func, args) not in conList:
print '(%s,%s,%s) not in %s constraints'%(parm2Name, func, args, parm1Name)
return "ERROR"
self.conDict[parm1Name].remove((parm2Name, func, args))
def setRange(self, parm, range):
#range can be list, interval tuple, type or validation func
#FIX THIS: do some range validation
self.rangeDict[parm] = range
def validateValue(self, parm, value):
rangeD = self.rangeDict
if not rangeD.has_key(parm):
#nothing specified for this parm
return value
range = rangeD[parm]
if type(range)==types.ListType:
if value in range:
return value
else:
return "ERROR: value not in range list"
elif type(range)==types.TupleType:
if value>=range[0]and value<=range[1]:
return value
else:
return "ERROR: value not in range interval"
elif range in self.typesList:
if type(value)==range:
return value
else:
return "ERROR: value not specified type"
else:
#only thing left is validation function
ok = apply(range, value)
if ok:
return value
else:
return "ERROR: value failed validation func"
def update(self, parm, value):
check = self.validateValue(parm, value)
if check!=value:
print 'failed validation:\n', check
return "ERROR"
self.updateConstraints(parm)
def fix(self, parmName):
#????????????????????????????
#this method makes self.parmName constant
#by removing any constraints which force it to change
for k, v in self.conDict.items():
for triple in v:
if triple[0]==parmName:
self.conDict[k].remove(triple)
class GeneralRegularGridDescriptor(ConstrainedParameterSet):
keywords = ['center',
'offset',
'length',
'nbGridPoints',
'gridSpacing'
]
def __init__(self, **kw):
ConstrainedParameterSet.__init__(self)
for k in self.keywords:
setattr(self, k, kw.get(k, Numeric.array((0.,0.,0.))))
consDict = kw.get('consDict', None)
if consDict:
for k, v in consDict.items():
self.tie(k, v[0], v[1], v[2])
rangeDict = kw.get('rangeDict', None)
if rangeDict:
for k, v in rangeDict.items():
self.setRange(k, v)
fixed = kw.get('fixed', None)
if fixed:
#fixed should be a list of parameters to fix
#same problem of type(parm)...a string???
for p in fixed:
self.fix(p)
```
#### File: mglutil/math/statetocoordstest.py
```python
from mglutil.math.statetocoords import StateToCoords
import unittest, math
import numpy.oldnumeric as Numeric, numpy.oldnumeric.random_array as RandomArray
from UserList import UserList
class TestState:
def __init__(self, q, t, o, tList):
self.quaternion = q
self.translation = t
self.origin = o
self.torsions = tList
class TestTorTree(UserList):
def __init__(self, data=None):
UserList.__init__(self, data)
self.tList = self.data
class TestTorsion:
def __init__(self, pivot1, pivot2, points):
self.atm1_ix = pivot1
self.atm2_ix = pivot2
self.atms_to_move = points
class StateToCoordsTest(unittest.TestCase):
def setUp(self):
"""Called for every test."""
self.decimals = 2 # for rounding; 7 is SciPy default.
self.known_points = [ [1., 0., 2.],
[1., 0., 1.],
[1., 1., 1.],
[0., 0., 1.],
[0., 0., 0.],
[0., 1., 0.],
[0., 1., -1.],
[1., 1., -1.],
[1., 2., -1.],
[1., 1., -2.]]
# create a simple torsion system for known_points
torTree = TestTorTree()
torTree.append(TestTorsion(4, 3, [0,1,2]))
torTree.append(TestTorsion(3, 1, [0,2]))
torTree.append(TestTorsion(6, 7, [8,9]))
self.torTree = torTree
npts = 5
dim = 3
self.max = 9999.
self.min = -self.max
self.random_points = RandomArray.uniform(self.min,
self.max, (npts,dim)).tolist()
def assertArrayEqual(self, a1, a2, decimals=None):
"""Round the arrays according to decimals and compare
Use self.decimals if decimals is not supplied"""
if decimals:
d = decimals
else:
d = self.decimals
for point in xrange(len(a1)):
for axis in [0, 1, 2]:
self.assertEqual(round(a1[point][axis],d),
round(a2[point][axis],d))
def tearDown(self):
pass
class ComputedValues(StateToCoordsTest):
def test_applyState(self):
"""applyState -- computed values untested"""
value = TestState(q=(1.0, 0.0, 0.0, 90.0),
t=(10., 10., 10.),
o=(1., 0., 1.),
tList=[0., 0., 270.])
state = StateToCoords(self.known_points, self.torTree, tolist=1)
result = state.applyState(value)
expected = [[11., 9., 11.],
[11., 10., 11.],
[11., 10., 12.],
[10., 10., 11.],
[10., 11., 11.],
[10., 11., 12.],
[10., 12., 12.],
[11., 12., 12.],
[11., 13., 12.],
[11., 12., 11.]]
self.assertArrayEqual(expected, result)
def test_applyOrientation00(self):
"""applyOrientation00 -- random pts with defaults"""
state = StateToCoords(self.random_points, tolist=1)
self.assertEqual(self.random_points, state.applyOrientation())
def test_applyOrientation01(self):
"""applyOrientation01 -- Q, T, O combined"""
state = StateToCoords(self.known_points, tolist=1)
result = state.applyOrientation( quat=(1.0, 0.0, 0.0, 90.0),
trans= (10., 10., 10.),
origin=(1., 0., 1.))
expected = [[11., 9., 11.],
[11., 10., 11.],
[11., 10., 12.],
[10., 10., 11.],
[10., 11., 11.],
[10., 11., 12.],
[10., 12., 12.],
[11., 12., 12.],
[11., 12., 13.],
[11., 13., 12.]]
self.assertArrayEqual(expected, result)
def test_applyQuaternion01(self):
"""applyQuaternion01 -- known pts 360 about x-axis"""
state = StateToCoords(self.known_points, tolist=1)
result = state.applyQuaternion((1.0, 0.0, 0.0, 360.0))
self.assertArrayEqual(self.known_points, result)
def test_applyQuaternion02(self):
"""applyQuaternion02 -- known pts 90 about x-axis"""
state = StateToCoords(self.known_points, tolist=1)
result = state.applyQuaternion((1.0, 0.0, 0.0, 90.0))
expected = [[1., -2., 0.],
[1., -1., 0.],
[1., -1., 1.],
[0., -1., 0.],
[0., 0., 0.],
[0., 0., 1.],
[0., 1., 1.],
[1., 1., 1.],
[1., 1., 2.],
[1., 2., 1.]]
self.assertArrayEqual(expected, result)
def test_applyQuaternion021(self):
"""applyQuaternion021 -- known pts 90 about x-axis; origin(1., 0., 1.)"""
state = StateToCoords(self.known_points, tolist=1)
result = state.applyQuaternion((1.0, 0.0, 0.0, 90.0), (1., 0., 1.))
expected = [[1., -1., 1.],
[1., 0., 1.],
[1., 0., 2.],
[0., 0., 1.],
[0., 1., 1.],
[0., 1., 2.],
[0., 2., 2.],
[1., 2., 2.],
[1., 2., 3.],
[1., 3., 2.]]
self.assertArrayEqual(expected, result)
def test_applyQuaternion03(self):
"""applyQuaternion02 -- known pts 90 about z-axis"""
state = StateToCoords(self.known_points, tolist=1)
result = state.applyQuaternion((0.0, 0.0, 1.0, 90.0))
expected = [[ 0., 1., 2.],
[ 0., 1., 1.],
[-1., 1., 1.],
[ 0., 0., 1.],
[ 0., 0., 0.],
[-1., 0., 0.],
[-1., 0., -1.],
[-1., 1., -1.],
[-2., 1., -1.],
[-1., 1., -2.]]
self.assertArrayEqual(expected, result)
def test_applyQuaternion04(self):
"""applyQuaternion04 -- random pts 360 about random-axis"""
state = StateToCoords(self.random_points, tolist=1)
q = RandomArray.uniform(self.min, self.max, (4,))
q[3] = 360.0
result = state.applyQuaternion(q)
self.assertArrayEqual(self.random_points, result)
def test_applyQuaternion05(self):
"""applyQuaternion05 -- random pts 3*120 about x-axis"""
state = StateToCoords(self.random_points, tolist=1)
q = (0.0, 0.0, 1.0, 120.0)
for n in xrange(3):
result = state.applyQuaternion(q)
self.assertArrayEqual(self.random_points, result,0)
def test_applyQuaternion06(self):
"""applyQuaternion06 -- random pts 2*180 about random-axis"""
state = StateToCoords(self.random_points, tolist=1)
q = RandomArray.uniform(self.min, self.max, (4,))
q[3] = 180.0
for n in xrange(2):
result = state.applyQuaternion(q)
self.assertArrayEqual(self.random_points, result)
def test_applyTranslation00(self):
"""applyTranslation00 -- random pts x (0., 0., 0.)"""
state = StateToCoords(self.random_points, tolist=1)
zzz = Numeric.zeros((3,), 'f')
self.assertEqual(self.random_points, state.applyTranslation(zzz))
def test_applyTranslation01(self):
"""applyTranslation01 -- random pts x (random translation)"""
state = StateToCoords(self.random_points, tolist=0)
trn = RandomArray.uniform(self.min, self.max, (3,))
expected = (Numeric.array(self.random_points) + trn)
self.assertArrayEqual(expected, state.applyTranslation(trn))
def test_applyTranslation02(self):
"""applyTranslation02 -- known pts x (1., 1., 1.)"""
state = StateToCoords(self.known_points, tolist=1)
ones = Numeric.ones((3,), 'f')
expected = (Numeric.array(self.known_points) + ones).tolist()
self.assertEqual(expected, state.applyTranslation(ones))
def test_applyTranslation03(self):
"""applyTranslation03 -- random pts x (random there and back)"""
state = StateToCoords(self.random_points, tolist=1)
trn = RandomArray.uniform(self.min, self.max, (3,))
state.applyTranslation(trn)
trn = -1*trn
self.assertArrayEqual(self.random_points, state.applyTranslation(trn))
if __name__ == '__main__':
unittest.main()
# for example:
# py mglutil/math/statetest.py -v
# or, to redirect output to a file:
# py statetest.py -v > & ! /tmp/st.out
```
#### File: MGLToolsPckgs/mglutil/preferences.py
```python
import os
import pickle
import types
from UserDict import UserDict
from mglutil.util.packageFilePath import getResourceFolderWithVersion
class UserPreference(UserDict):
"""
Class to let the user define Preferences.
a preference is made of a name, a current value, a possibly empty list
of valid values.
preferences can be added using the add method
and set using the set method
"""
def __init__(self, ):
UserDict.__init__(self)
self.dirty = 0 # used to remember that something changed
self.resourceFile = None
resourceFolder = getResourceFolderWithVersion()
if resourceFolder is None:
return
self.resourceFile = os.path.join(resourceFolder, '.settings')
self.defaults = {}
self.settings = {}
if os.path.exists(self.resourceFile):
try:
pkl_file = open(self.resourceFile)
self.settings = pickle.load(pkl_file)
pkl_file.close()
except Exception, inst:
print inst, "Error in ", __file__
def add(self, name, value, validValues = [], validateFunc=None,
callbackFunc=[], doc='', category="General"):
"""add a userpreference. A name and a value are required,
a list of valide values can be provoded as well as a function that
can be called to validate the value. A callback function can be
specified, it will be called when the value is set with the old value
and the new value passed as an argument"""
# if name in self.data.keys():
# # doesn't create the userpreference if the name already exists:
# return
if len(validValues):
assert value in validValues
if validateFunc:
assert callable(validateFunc)
if callbackFunc != []:
assert type(callbackFunc) is types.ListType and \
len(filter(lambda x: not callable(x), callbackFunc))==0
self[name] = { 'value':value, 'validValues':validValues,
'validateFunc': validateFunc,
'callbackFunc': callbackFunc,
'doc':doc ,
'category':category}
self.set(name, value)
self.dirty = 1
def set(self, name, value):
if not self.data.has_key(name):
self.settings[name] = value
return
if self.resourceFile is None:
return
self.settings[name] = value
entry = self.data[name]
try:
if entry.has_key('validValues') and len(entry['validValues']):
if not value in entry['validValues']:
#msg = " is not a valid value, value has to be in %s" % str(entry['validValues'])
#print value, msg
return
if entry.has_key('validateFunc') and entry['validateFunc']:
if not entry['validateFunc'](value):
msg = " is not a valid value, try the Info button"
#print value, msg
return
except Exception, inst:
print __file__, inst
oldValue = entry['value']
entry['value'] = value
if entry['callbackFunc']!=[]:
for cb in entry['callbackFunc']:
cb(name,oldValue, value)
self.dirty = 1
def addCallback(self, name, func):
assert callable(func)
assert self.data.has_key(name)
entry = self.data[name]
entry['callbackFunc'].append(func)
def removeCallback(self, name, func):
assert self.data.has_key(name) and \
func in self.data[name]['callbackFunc']
entry = self.data[name]
entry['callbackFunc'].remove(func)
def save(self, filename):
"""save the preferences to a file"""
pass
self.dirty = 0 # clean now !
def loadSettings(self):
if self.resourceFile is None:
return
settings = {}
if os.path.exists(self.resourceFile):
pkl_file = open(self.resourceFile)
settings = pickle.load(pkl_file)
pkl_file.close()
for key, value in settings.items():
self.set(key, value)
def saveAllSettings(self):
output = open(self.resourceFile, 'w')
pickle.dump(self.settings, output)
output.close()
def saveSingleSetting(self, name, value):
if os.path.exists(self.resourceFile):
pkl_file = open(self.resourceFile)
settings = pickle.load(pkl_file)
pkl_file.close()
else:
settings = {}
settings[name] = value
output = open(self.resourceFile, 'w')
pickle.dump(settings, output)
output.close()
def saveDefaults(self):
if self.resourceFile is None:
return
for key, value in self.data.items():
self.defaults[key] = value
def restoreDefaults(self):
for key, value in self.defaults.items():
self.set(key, value)
```
#### File: mglutil/TestUtil/Dependencytester.py
```python
import os, sys, re,string
from os.path import walk
import getopt,warnings
os.system('rm -rf depresult')
vinfo = sys.version_info
pythonv = "python%d.%d"%(vinfo[0], vinfo[1])
######################################################################
# COMMAND LINE OPTIONS
######################################################################
class DEPENDENCYCHECKER:
########################################################################
# Findind packages
########################################################################
def rundependencychecker(self,pack,v=True,V=False,loc=None):
cwd = os.getcwd()
import string
packages = {}
pn =[]
for i in sys.path:
s =i.split('/')
if s[-1]=="MGLToolsPckgs" or s[-1]== 'site-packages':
#if s[-1]=='FDepPackages' or s[-1]=='RDepPackages' or s[-1]=='FSharedPackages' or s[-1]=='RSharedPackages' or s[-1]== 'site-packages':
pn.append(i)
for p in pn:
os.chdir(p)
files = os.listdir(p)
for f in files:
if not os.path.isdir(f):
continue
pwdir = os.path.join(p, f)
if os.path.exists( os.path.join( pwdir, '__init__.py')):
if not packages.has_key(f):
packages[f] = pwdir
elif os.path.exists( os.path.join( p, '.pth') ):
if not packages.has_key(f):
packages[f] = pwdir
os.chdir(cwd)
################################################################
# packages in site-packages
###################################################################
pack_site=packages.keys()
##########################################################################
# Finding list of import statements used in all packages
###########################################################################
Total_packs = []
if V == True:
if pack!=None:
packn = string.split(pack,'.')
pack =packn[0]
exec('packages={"%s":"%s"}'%(pack,packages[pack]))
if packn[-1]!='py':
pack_file =packn[-1]
if packn[-1]=='py':
pack_file =packn[-2]
else:
pack_file=None
for pack in packages:
files = []
pat = re.compile('import')
print "please wait ...."
for root, dirs, files in os.walk(packages[pack]):
# remove directories not to visit
for rem in ['CVS', 'regression', 'Tutorial', 'test','Doc','doc']:
if rem in dirs:
dirs.remove(rem)
# look for files that contain the string 'import'
for fi in files:
if fi[-3:]!='.py':
continue
if fi[-3:]=='.py':
#finds pattern "import" match in that particular file
if pack_file!=pack:
if pack_file!=None:
if fi !=pack_file+'.py':
continue
else:
candidates = []
f = open( os.path.join(root, fi) )
data = f.readlines()
f.close()
found = 0
for line in data:
match = pat.search(line)
if match:
candidates.append( (root, fi, line) )
#finds pattern "import" for packages given with option p at file level
if pack_file==pack:
candidates = []
f = open( os.path.join(root, fi) )
data = f.readlines()
f.close()
found = 0
for line in data:
match = pat.search(line)
if match:
candidates.append( (root, fi, line) )
#finds pattern "import" match for all packages at file level
else:
candidates = []
f = open( os.path.join(root, fi) )
data = f.readlines()
f.close()
found = 0
for line in data:
match = pat.search(line)
if match:
candidates.append( (root, fi, line) )
#######################################
#finding dependencies
#######################################
result= []
import string
if len(candidates)>0:
for candidate_num in candidates:
p, f, imp = candidate_num
path =string.split(p,'site-packages')[-1]
implist =[]
fromlist=[]
y =string.split(imp)
#omitting commemted imports
if '.' not in imp and y[0]=="import":
len_space = len(imp.split(' '))
len_comma=len(imp.split(','))
if (len_space -1) > len_comma:
continue
# as im import statement
if "as" in y:
for a in y:
if a=='as':
aind = y.index(a)
if '.' not in y[aind-1] :
implist.append(y[aind-1])
continue
else:
newa = y[aind-1].split('.')
implist.append(newa[0])
continue
if '#' in y:
continue
#if first word is import in the list
if y[0]=='import':
for i in range(1,len(y)):
if y[i][-1]==";":
y[i]=y[i][:-1]
if y[i] not in implist:
implist.append(y[i])
break
if 'as' in y:
break
if y[i][-1]==',':
y[i]=y[i][:-1]
if ',' in y[i]:
srg = string.split(y[i],',')
for j in srg:
if j not in implist:
implist.append(j)
continue
elif len(y[i])<=2:
continue
#if import statement is like a.q
elif len(string.split(y[i],'.'))!=1:
sr = string.split(y[i],'.')
if sr[0] not in implist:
#if module doesn't starts with __
#append to list
if sr[0][0]!='__':
implist.append(sr[0])
#if import statement with out '.'
else:
if y[i] not in implist:
#print y[i]
if y[i][0]!='__':
implist.append(y[i])
#import statement with out ',' in the end
else:
if len(y[i])==1:
continue
elif ',' in y[i]:
srg = string.split(y[i],',')
for j in srg:
if j not in implist:
implist.append(j)
continue
#import statement as a.b.c.d
elif len(string.split(y[i],'.'))>1:
sr = string.split(y[i],'.')
if sr[0] not in implist:
if sr[0][0]!='__':
implist.append(sr[0])
continue
#import statement without '.'
elif y[i] not in implist:
if y[i][0]!='__':
implist.append(y[i])
continue
for im in implist:
#try importing module in implist
try:
exec('import %s'%im)
if im == 'Pmw':
if im not in result:
if im!=pack:
result.append(im)
continue
else:
continue
#if module.__file__ exists check in
#site-packages and append to result
exec('fi = %s.__file__'%im)
fil = os.path.abspath('%s'%fi)
if os.path.exists(fil):
file = string.split(str(fil),'/')
if file[-2] in pack_site:
if file[-2] not in result:
if file[-2] !=pack:
result.append(file[-2])
elif file[-2]=='Numeric':
if 'Numeric' not in result:
if 'Numeric'!=pack:
result.append('Numeric')
elif file[-2] not in ['lib-dynload', pythonv,'lib-tk']:
if im not in result:
if im!=pack:
result.append(im)
except:
if im in ['sys','gc','thread','exceptions']:
continue
else:
if im not in result:
result.append(im)
#if first word is from in list
if y[0]=='from':
#if from statement is like a.b.c
if len(string.split(y[1],'.'))!=1:
sr = string.split(y[1],'.')
if sr[0] not in fromlist:
fromlist.append(sr[0])
else:
if y[1]!=pack:
if y[1] not in fromlist:
if y[1][0]!='__':
fromlist.append(y[1])
for i in fromlist:
#checks importing module
try:
exec('import %s'%i)
if i == 'Pmw':
if i not in result:
if i !=pack:
result.append(i)
continue
else:
continue
#if __file exixts check in site-pacakges
#and append to result
exec('fi = %s.__file__'%i)
fil = os.path.abspath('%s'%fi)
if os.path.exists(fil):
file = string.split(str(fil),'/')
if file[-2] in pack_site:
if file[-2] not in result:
if file[-2] !=pack:
result.append(file[-2])
elif file[-2]=='Numeric':
if 'Numeric' not in result:
if 'Numeric'!=pack:
result.append('Numeric')
elif file[-2] not in ['lib-dynload', pythonv,'lib-tk']:
if i not in result:
if i!=pack :
result.append(i)
except:
if i in ['sys','gc','thread','exceptions']:
continue
else:
if i not in result:
result.append(i)
listdf=[]
for r,d,lf in os.walk(packages[pack]):
for rem in ['CVS', 'regression', 'Tutorial', 'test','Doc','doc']:
if rem in d:
d.remove(rem)
#when files in pack are imported
listd = os.listdir(r)
for ld in listd:
if ld.endswith('.py')==True or ld.endswith('.so')==True:
for res in result:
if res == ld[:-3]:
if res in result:
result.remove(res)
for files in lf:
for res in result:
pat1 = re.compile('"%s"' %res)
pat2 = re.compile("%s.py" %res)
fptr=open("%s/%s" %(r,files))
lines = fptr.readlines()
for line in lines:
match1 = pat1.search(line)
match2 = pat2.search(line)
if match1 or match2:
if res in result:
ind = result.index(res)
if result[ind] not in pack_site:
del result[ind]
continue
#In case of Pmv multires,pdb2qr etc
if res in files:
if res in result:
ind = result.index(res)
if result[ind] not in pack_site:
del result[ind]
for res in result:
if res[:3] in ['tmp','TMP','win']:
result.remove(res)
continue
exec('l = len("%s")'%f)
if l>60:
exec('md = string.split("%s",",")[0]'%f)
exec('f = string.split("%s","/")[-1][:-1]'%md)
Total_packs.append('result_%s %s %s %s' %(pack,path,f,result))
#return Total_packs
else:
Total_packs.append('result_%s %s %s %s' %(pack,path,f,result))
print "result_%s %s %s %s" %(pack,path,f,result)
if Total_packs:
return Total_packs
else:
if pack != None:
#print pack
pack_list = pack.split(',')
if len(pack_list)>=1:
packs = {}
for p in pack_list:
packs[p]=packages[p]
packages = packs
print "please wait ......."
for pack in packages:
files = []
pat = re.compile('import')
candidates = []
for root, dirs, files in os.walk(packages[pack]):
# remove directories not to visit
for rem in ['CVS', 'regression', 'Tutorial', 'test','Doc','doc']:
if rem in dirs:
dirs.remove(rem)
# look for files that contain the string 'import'
for fi in files:
if fi[-3:]!='.py':
continue
#finding pattern "import" match
if fi[-3:]=='.py':
f = open( os.path.join(root, fi) )
data = f.readlines()
f.close()
found = 0
for line in data:
match = pat.search(line)
if match:
candidates.append( (root, fi, line) )
##############################
#finding dependencies
##############################
result= []
import string
for candidate_num in candidates:
#print candidate_num
p, f, imp = candidate_num
implist =[]
fromlist=[]
y =string.split(imp)
#omitting commemted imports
if '.' not in imp and y[0]=="import":
len_space = len(imp.split(' '))
len_comma=len(imp.split(','))
if (len_space -1) > len_comma:
continue
if "as" in y:
for a in y:
if a=='as':
aind = y.index(a)
if '.' not in y[aind-1] :
if y[aind-1] not in implist:
implist.append(y[aind-1])
continue
else:
newa = y[aind-1].split('.')
if newa[0] not in implist:
implist.append(newa[0])
continue
if '#' in y:
continue
#if first word is import in the list
if y[0]=='import':
for i in range(1,len(y)):
if y[i][-1]==";":
y[i]=y[i][:-1]
if y[i] not in implist:
implist.append(y[i])
break
if "as" in y:
break
if y[i][-1]==',':
y[i]=y[i][:-1]
if ',' in y[i]:
srg = string.split(y[i],',')
for j in srg:
if j not in implist:
implist.append(j)
continue
elif len(y[i])<=2:
continue
elif len(string.split(y[i],'.'))!=1:
sr = string.split(y[i],'.')
if sr[0]!=pack:
if sr[0] not in implist:
if sr[0][0]!='__':
implist.append(sr[0])
else:
if y[i]!=pack:
if y[i] not in implist:
if y[i][0]!='__':
implist.append(y[i])
else:
if len(y[i])==1:
continue
if len(string.split(y[i],','))!=1:
srg = string.split(y[i],',')
for j in range(0,len(srg)):
if srg[j] not in implist:
implist.append(srg[j])
else:
continue
elif len(string.split(y[i],'.'))!=1:
sr = string.split(y[i],'.')
if sr[0] not in implist:
if sr[0][0]!='__':
implist.append(sr[0])
elif y[i] not in implist:
if y[i][0]!='__':
implist.append(y[i])
for im in implist:
try:
exec('import %s'%im)
if im == 'Pmw':
if im not in result:
if im!=pack:
result.append(im)
continue
else:
continue
exec('fi = %s.__file__'%im)
fil = os.path.abspath('%s'%fi)
if os.path.exists(fil):
file = string.split(str(fil),'/')
if file[-2] in pack_site:
if file[-2] not in result:
if file[-2] !=pack:
result.append(file[-2])
elif file[-2]=='Numeric':
if 'Numeric' not in result:
if 'Numeric'!=pack:
result.append('Numeric')
elif file[-2] not in ['lib-dynload', pythonv,'lib-tk']:
if im not in result:
if im!=pack:
result.append(im)
except:
if im in ['sys','gc','thread','exceptions']:
continue
if im not in result:
if im!=pack:
result.append(im)
#if first word is from in list
if y[0]=='from':
if len(string.split(y[1],'.'))!=1:
sr = string.split(y[1],'.')
if sr[0] != pack:
if sr[0] not in fromlist:
fromlist.append(sr[0])
else:
if y[1]!=pack:
if y[1] not in fromlist:
fromlist.append(y[1])
for i in fromlist:
try:
exec('import %s'%i)
if i == 'Pmw':
if i not in result:
if i !=pack:
result.append(i)
continue
else:
continue
exec('fi = %s.__file__'%i)
fil = os.path.abspath('%s'%fi)
if os.path.exists(fil):
file = string.split(str(fil),'/')
if file[-2] in pack_site:
if file[-2] not in result:
if file[-2] !=pack:
result.append(file[-2])
elif file[-2]=='Numeric':
if 'Numeric' not in result:
if 'Numeric'!=pack:
result.append('Numeric')
elif file[-2] not in ['lib-dynload', pythonv,'lib-tk']:
if i not in result:
if i!=pack :
result.append(i)
except:
if i in ['sys','gc','thread','exceptions']:
continue
if i not in result:
if i!=pack:
result.append(i)
listdf =[]
for r,d,lf in os.walk(packages[pack]):
for rem in ['CVS', 'regression', 'Tutorial', 'test','Doc','doc']:
if rem in d:
d.remove(rem)
#when directory is imported eg: import extent(opengltk/extent)
for res in result:
if res in d:
if res in result:
result.remove(res)
continue
#when files in pack are imported
listd = os.listdir(r)
for ld in listd:
if ld.endswith('.py')==True or ld.endswith('.so')==True:
for res in result:
if res == ld[:-3]:
if res in result:
result.remove(res)
#This is for cases in which (mainly tests) some file is created and
#for tests purpose and removed .but imported in testfile
#like tmpSourceDial.py in mglutil
for files in lf:
if files[-3:]!=".py":
lf.remove(files)
continue
for res in result:
pat1 = re.compile('%s' %res)
pat2 = re.compile('%s.py' %res)
fptr=open("%s/%s" %(r,files))
lines = fptr.readlines()
for line in lines:
match1 = pat1.search(line)
match2 = pat2.search(line)
if match1 or match2:
if res in result:
ind = result.index(res)
if result[ind] not in pack_site:
del result[ind]
continue
#In case of Pmv multires,pdb2qr etc
if res in files:
if res in result:
ind = result.index(res)
if result[ind] not in pack_site:
del result[ind]
continue
for res in result:
if res[:3] in ['tmp','TMP','win']:
result.remove(res)
continue
print "result_%s %s" %(pack,result)
Total_packs.append('result_%s %s' %(pack,result))
return Total_packs
############################################################
# PRINTING DEPENDENCIES AND COPYING THEM TO FILE
############################################################
```
#### File: web/services/AppService_services_types.py
```python
import ZSI
from ZSI.TCcompound import Struct
##############################
# targetNamespace
#
# http://nbcr.sdsc.edu/opal/types
##############################
# imported as: ns1
class nbcr_sdsc_edu_opal_types:
targetNamespace = 'http://nbcr.sdsc.edu/opal/types'
class OutputsByNameInputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'OutputsByNameInputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._jobID = None
self._fileName = None
TClist = [ZSI.TC.String(pname="jobID",aname="_jobID"), ZSI.TC.String(pname="fileName",aname="_fileName"), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_jobID(self):
return self._jobID
def Set_jobID(self,_jobID):
self._jobID = _jobID
def Get_fileName(self):
return self._fileName
def Set_fileName(self,_fileName):
self._fileName = _fileName
class ParamsType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'ParamsType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._id = None
self._tag = None
self._paramType = None
self._ioType = None
self._required = None
self._value = None
self._semanticType = None
self._textDesc = None
TClist = [ZSI.TC.String(pname="id",aname="_id"), ZSI.TC.String(pname="tag",aname="_tag", optional=1), ns1.ParamType_Def(name="paramType",ns=ns), ns1.IOType_Def(name="ioType",ns=ns, optional=1), ZSI.TC.Boolean(pname="required",aname="_required", optional=1), ZSI.TC.String(pname="value",aname="_value", repeatable=1, optional=1), ZSI.TC.String(pname="semanticType",aname="_semanticType", optional=1), ZSI.TC.String(pname="textDesc",aname="_textDesc", optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_id(self):
return self._id
def Set_id(self,_id):
self._id = _id
def Get_tag(self):
return self._tag
def Set_tag(self,_tag):
self._tag = _tag
def Get_paramType(self):
return self._paramType
def Set_paramType(self,_paramType):
self._paramType = _paramType
def Get_ioType(self):
return self._ioType
def Set_ioType(self,_ioType):
self._ioType = _ioType
def Get_required(self):
return self._required
def Set_required(self,_required):
self._required = _required
def Get_value(self):
return self._value
def Set_value(self,_value):
self._value = _value
def Get_semanticType(self):
return self._semanticType
def Set_semanticType(self,_semanticType):
self._semanticType = _semanticType
def Get_textDesc(self):
return self._textDesc
def Set_textDesc(self,_textDesc):
self._textDesc = _textDesc
class InputFileType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'InputFileType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._name = None
self._contents = None
TClist = [ZSI.TC.String(pname="name",aname="_name"), ZSI.TC.Base64String(pname="contents",aname="_contents"), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_name(self):
return self._name
def Set_name(self,_name):
self._name = _name
def Get_contents(self):
return self._contents
def Set_contents(self,_contents):
self._contents = _contents
class FaultType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'FaultType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._message = None
TClist = [ZSI.TC.String(pname="message",aname="_message", optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_message(self):
return self._message
def Set_message(self,_message):
self._message = _message
class FlagsType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'FlagsType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._id = None
self._tag = None
self._textDesc = None
TClist = [ZSI.TC.String(pname="id",aname="_id"), ZSI.TC.String(pname="tag",aname="_tag"), ZSI.TC.String(pname="textDesc",aname="_textDesc", optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_id(self):
return self._id
def Set_id(self,_id):
self._id = _id
def Get_tag(self):
return self._tag
def Set_tag(self,_tag):
self._tag = _tag
def Get_textDesc(self):
return self._textDesc
def Set_textDesc(self,_textDesc):
self._textDesc = _textDesc
class ImplicitParamsType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'ImplicitParamsType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._id = None
self._name = None
self._extension = None
self._ioType = None
self._required = None
self._semanticType = None
self._textDesc = None
self._min = None
self._max = None
TClist = [ZSI.TC.String(pname="id",aname="_id"), ZSI.TC.String(pname="name",aname="_name", optional=1), ZSI.TC.String(pname="extension",aname="_extension", optional=1), ns1.IOType_Def(name="ioType",ns=ns), ZSI.TC.Boolean(pname="required",aname="_required", optional=1), ZSI.TC.String(pname="semanticType",aname="_semanticType", optional=1), ZSI.TC.String(pname="textDesc",aname="_textDesc", optional=1), ZSI.TCnumbers.Iint(pname="min",aname="_min", optional=1), ZSI.TCnumbers.Iint(pname="max",aname="_max", optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_id(self):
return self._id
def Set_id(self,_id):
self._id = _id
def Get_name(self):
return self._name
def Set_name(self,_name):
self._name = _name
def Get_extension(self):
return self._extension
def Set_extension(self,_extension):
self._extension = _extension
def Get_ioType(self):
return self._ioType
def Set_ioType(self,_ioType):
self._ioType = _ioType
def Get_required(self):
return self._required
def Set_required(self,_required):
self._required = _required
def Get_semanticType(self):
return self._semanticType
def Set_semanticType(self,_semanticType):
self._semanticType = _semanticType
def Get_textDesc(self):
return self._textDesc
def Set_textDesc(self,_textDesc):
self._textDesc = _textDesc
def Get_min(self):
return self._min
def Set_min(self,_min):
self._min = _min
def Get_max(self):
return self._max
def Set_max(self,_max):
self._max = _max
class StatusOutputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'StatusOutputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._code = None
self._message = None
self._baseURL = None
TClist = [ZSI.TCnumbers.Iint(pname="code",aname="_code"), ZSI.TC.String(pname="message",aname="_message"), ZSI.TC.URI(pname="baseURL",aname="_baseURL"), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_code(self):
return self._code
def Set_code(self,_code):
self._code = _code
def Get_message(self):
return self._message
def Set_message(self,_message):
self._message = _message
def Get_baseURL(self):
return self._baseURL
def Set_baseURL(self,_baseURL):
self._baseURL = _baseURL
class OutputFileType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'OutputFileType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._name = None
self._url = None
TClist = [ZSI.TC.String(pname="name",aname="_name"), ZSI.TC.URI(pname="url",aname="_url"), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_name(self):
return self._name
def Set_name(self,_name):
self._name = _name
def Get_url(self):
return self._url
def Set_url(self,_url):
self._url = _url
class getOutputAsBase64ByNameOutput_Dec(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/literals'
literal = 'getOutputAsBase64ByNameOutput'
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
# internal vars
self._item = None
TClist = [ZSI.TCnumbers.Ibyte(pname="item",aname="_item", repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_item(self):
return self._item
def Set_item(self,_item):
self._item = _item
class getOutputAsBase64ByNameInput_Dec(OutputsByNameInputType_Def):
literal = "getOutputAsBase64ByNameInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.OutputsByNameInputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.OutputsByNameInputType_Def(name=name, ns=ns, **kw)
class ParamsArrayType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'ParamsArrayType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._separator = None
self._param = None
TClist = [ZSI.TC.String(pname="separator",aname="_separator", optional=1), ns1.ParamsType_Def(name="param", ns=ns, repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_separator(self):
return self._separator
def Set_separator(self,_separator):
self._separator = _separator
def Get_param(self):
return self._param
def Set_param(self,_param):
self._param = _param
class JobInputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'JobInputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._argList = None
self._numProcs = None
self._inputFile = None
TClist = [ZSI.TC.String(pname="argList",aname="_argList", optional=1), ZSI.TCnumbers.Iint(pname="numProcs",aname="_numProcs", optional=1), ns1.InputFileType_Def(name="inputFile", ns=ns, repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_argList(self):
return self._argList
def Set_argList(self,_argList):
self._argList = _argList
def Get_numProcs(self):
return self._numProcs
def Set_numProcs(self,_numProcs):
self._numProcs = _numProcs
def Get_inputFile(self):
return self._inputFile
def Set_inputFile(self,_inputFile):
self._inputFile = _inputFile
class opalFaultOutput_Dec(FaultType_Def):
literal = "opalFaultOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.FaultType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.FaultType_Def(name=name, ns=ns, **kw)
class FlagsArrayType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'FlagsArrayType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._flag = None
TClist = [ns1.FlagsType_Def(name="flag", ns=ns, repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_flag(self):
return self._flag
def Set_flag(self,_flag):
self._flag = _flag
class ImplicitParamsArrayType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'ImplicitParamsArrayType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._param = None
TClist = [ns1.ImplicitParamsType_Def(name="param", ns=ns, repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_param(self):
return self._param
def Set_param(self,_param):
self._param = _param
class JobSubOutputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'JobSubOutputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._jobID = None
self._status = None
TClist = [ZSI.TC.String(pname="jobID",aname="_jobID"), ns1.StatusOutputType_Def(name="status", ns=ns), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_jobID(self):
return self._jobID
def Set_jobID(self,_jobID):
self._jobID = _jobID
def Get_status(self):
return self._status
def Set_status(self,_status):
self._status = _status
class queryStatusOutput_Dec(StatusOutputType_Def):
literal = "queryStatusOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.StatusOutputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.StatusOutputType_Def(name=name, ns=ns, **kw)
class destroyOutput_Dec(StatusOutputType_Def):
literal = "destroyOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.StatusOutputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.StatusOutputType_Def(name=name, ns=ns, **kw)
class JobOutputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'JobOutputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._stdOut = None
self._stdErr = None
self._outputFile = None
TClist = [ZSI.TC.URI(pname="stdOut",aname="_stdOut", optional=1), ZSI.TC.URI(pname="stdErr",aname="_stdErr", optional=1), ns1.OutputFileType_Def(name="outputFile", ns=ns, repeatable=1, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_stdOut(self):
return self._stdOut
def Set_stdOut(self,_stdOut):
self._stdOut = _stdOut
def Get_stdErr(self):
return self._stdErr
def Set_stdErr(self,_stdErr):
self._stdErr = _stdErr
def Get_outputFile(self):
return self._outputFile
def Set_outputFile(self,_outputFile):
self._outputFile = _outputFile
class launchJobInput_Dec(JobInputType_Def):
literal = "launchJobInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.JobInputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.JobInputType_Def(name=name, ns=ns, **kw)
class launchJobBlockingInput_Dec(JobInputType_Def):
literal = "launchJobBlockingInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.JobInputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.JobInputType_Def(name=name, ns=ns, **kw)
class ArgumentsType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'ArgumentsType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._flags = None
self._taggedParams = None
self._untaggedParams = None
self._implicitParams = None
TClist = [ns1.FlagsArrayType_Def(name="flags", ns=ns, optional=1), ns1.ParamsArrayType_Def(name="taggedParams", ns=ns, optional=1), ns1.ParamsArrayType_Def(name="untaggedParams", ns=ns, optional=1), ns1.ImplicitParamsArrayType_Def(name="implicitParams", ns=ns, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_flags(self):
return self._flags
def Set_flags(self,_flags):
self._flags = _flags
def Get_taggedParams(self):
return self._taggedParams
def Set_taggedParams(self,_taggedParams):
self._taggedParams = _taggedParams
def Get_untaggedParams(self):
return self._untaggedParams
def Set_untaggedParams(self,_untaggedParams):
self._untaggedParams = _untaggedParams
def Get_implicitParams(self):
return self._implicitParams
def Set_implicitParams(self,_implicitParams):
self._implicitParams = _implicitParams
class launchJobOutput_Dec(JobSubOutputType_Def):
literal = "launchJobOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.JobSubOutputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.JobSubOutputType_Def(name=name, ns=ns, **kw)
class BlockingOutputType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'BlockingOutputType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._status = None
self._jobOut = None
TClist = [ns1.StatusOutputType_Def(name="status", ns=ns), ns1.JobOutputType_Def(name="jobOut", ns=ns), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_status(self):
return self._status
def Set_status(self,_status):
self._status = _status
def Get_jobOut(self):
return self._jobOut
def Set_jobOut(self,_jobOut):
self._jobOut = _jobOut
class getOutputsOutput_Dec(JobOutputType_Def):
literal = "getOutputsOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.JobOutputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.JobOutputType_Def(name=name, ns=ns, **kw)
class AppMetadataType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'AppMetadataType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._usage = None
self._info = None
self._types = None
TClist = [ZSI.TC.String(pname="usage",aname="_usage"), ZSI.TC.String(pname="info",aname="_info", repeatable=1, optional=1), ns1.ArgumentsType_Def(name="types", ns=ns, optional=1), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
hasextras=1, **kw)
def Get_usage(self):
return self._usage
def Set_usage(self,_usage):
self._usage = _usage
def Get_info(self):
return self._info
def Set_info(self,_info):
self._info = _info
def Get_types(self):
return self._types
def Set_types(self,_types):
self._types = _types
class launchJobBlockingOutput_Dec(BlockingOutputType_Def):
literal = "launchJobBlockingOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.BlockingOutputType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.BlockingOutputType_Def(name=name, ns=ns, **kw)
class AppConfigType_Def(ZSI.TCcompound.Struct):
schema = 'http://nbcr.sdsc.edu/opal/types'
type = 'AppConfigType'
def __init__(self, name=None, ns=None, **kw):
# internal vars
self._metadata = None
self._binaryLocation = None
self._defaultArgs = None
self._parallel = None
TClist = [ns1.AppMetadataType_Def(name="metadata", ns=ns), ZSI.TC.String(pname="binaryLocation",aname="_binaryLocation"), ZSI.TC.String(pname="defaultArgs",aname="_defaultArgs", optional=1), ZSI.TC.Boolean(pname="parallel",aname="_parallel"), ]
oname = name
if name:
aname = '_%s' % name
if ns:
oname += ' xmlns="%s"' % ns
else:
oname += ' xmlns="%s"' % self.__class__.schema
else:
aname = None
ZSI.TCcompound.Struct.__init__(self, self.__class__, TClist,
pname=name, inorder=0,
aname=aname, oname=oname,
**kw)
def Get_metadata(self):
return self._metadata
def Set_metadata(self,_metadata):
self._metadata = _metadata
def Get_binaryLocation(self):
return self._binaryLocation
def Set_binaryLocation(self,_binaryLocation):
self._binaryLocation = _binaryLocation
def Get_defaultArgs(self):
return self._defaultArgs
def Set_defaultArgs(self,_defaultArgs):
self._defaultArgs = _defaultArgs
def Get_parallel(self):
return self._parallel
def Set_parallel(self,_parallel):
self._parallel = _parallel
class getAppMetadataOutput_Dec(AppMetadataType_Def):
literal = "getAppMetadataOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.AppMetadataType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.AppMetadataType_Def(name=name, ns=ns, **kw)
class getAppConfigOutput_Dec(AppConfigType_Def):
literal = "getAppConfigOutput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
ns1.AppConfigType_Def.__init__(self, name=name, ns=ns, **kw)
self.typecode = ns1.AppConfigType_Def(name=name, ns=ns, **kw)
class ParamType_Def(ZSI.TC.String):
tag = "tns:ParamType"
def __init__(self, name=None, ns=None, **kw):
aname = None
if name:
kw["pname"] = name
kw["aname"] = "_%s" % name
kw["oname"] = '%s xmlns:tns="%s"' %(name,ns1.targetNamespace)
ZSI.TC.String.__init__(self, **kw)
class IOType_Def(ZSI.TC.String):
tag = "tns:IOType"
def __init__(self, name=None, ns=None, **kw):
aname = None
if name:
kw["pname"] = name
kw["aname"] = "_%s" % name
kw["oname"] = '%s xmlns:tns="%s"' %(name,ns1.targetNamespace)
ZSI.TC.String.__init__(self, **kw)
class queryStatusInput_Dec(ZSI.TC.String):
literal = "queryStatusInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
kw["oname"] = '%s xmlns="%s"' %(name, ns)
ZSI.TC.String.__init__(self,pname=name, aname="%s" % name, **kw)
class getOutputsInput_Dec(ZSI.TC.String):
literal = "getOutputsInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
kw["oname"] = '%s xmlns="%s"' %(name, ns)
ZSI.TC.String.__init__(self,pname=name, aname="%s" % name, **kw)
class destroyInput_Dec(ZSI.TC.String):
literal = "destroyInput"
schema = "http://nbcr.sdsc.edu/opal/types"
def __init__(self, name=None, ns=None, **kw):
name = name or self.__class__.literal
ns = ns or self.__class__.schema
kw["oname"] = '%s xmlns="%s"' %(name, ns)
ZSI.TC.String.__init__(self,pname=name, aname="%s" % name, **kw)
# define class alias for subsequent ns classes
ns1 = nbcr_sdsc_edu_opal_types
```
#### File: MGLToolsPckgs/MolKit/amberPrmTop.py
```python
from sff.amber import AmberParm
import numpy.oldnumeric as Numeric, types
from math import pi, sqrt, ceil, fabs
from string import split, strip, join
from os.path import basename
from MolKit.data.all_amino94_dat import all_amino94_dat
from MolKit.data.all_aminont94_dat import all_aminont94_dat
from MolKit.data.all_aminoct94_dat import all_aminoct94_dat
class Parm:
"""class to hold parameters for Amber Force Field calcuations
"""
def __init__(self, allDictList = [all_amino94_dat], ntDictList = [all_aminont94_dat],
ctDictList = [all_aminoct94_dat]):
#amber parameter reference dictionaries:
if len(allDictList)==0:
allDict = all_amino94_dat
else:
allDict = allDictList[0]
if type(allDict)==types.StringType:
allDict = self.getDictObj(allDict)
if len(allDictList)>1:
for d in allDictList:
if type(d)== types.StringType:
d = self.getDictObj(d)
allDict.update(d)
#allDict.extend(d)
self.allDict = allDict
if len(ntDictList)==0:
ntDict = all_aminont94_dat
else:
ntDict = ntDictList[0]
if type(ntDict)==types.StringType:
ntDict = self.getDictObj(ntDict)
if len(ntDictList)>1:
for d in ntDictList:
if type(d)== types.StringType:
d = self.getDictObj(d)
ntDict.update(d)
#ntDict.extend(d)
self.ntDict = ntDict
if len(ctDictList)==0:
ctDict = all_aminoct94_dat
else:
ctDict = ctDictList[0]
if type(ctDict)==types.StringType:
ctDict = self.getDictObj(ctDict)
if len(ctDictList)>1:
for d in ctDictList:
if type(d)== types.StringType:
d = self.getDictObj(d)
ctDict.update(d)
#ctDict.extend(d)
self.ctDict = ctDict
#formatD is used for write method
formatD = {}
for k in ['Iac', 'Iblo', 'Cno', 'Ipres', 'ExclAt']:
formatD[k] = ('%6d', 12, 0)
for k in ['Charges', 'Masses', 'Rk', 'Req', 'Tk', 'Teq',\
'Pk', 'Pn', 'Phase', 'Solty', 'Cn1', 'Cn2']:
formatD[k] = ('%16.8E', 5, 0)
for k in ['AtomNames', 'ResNames', 'AtomSym', 'AtomTree']:
formatD[k] = ('%-4.4s', 20, 0)
for k in ['allHBnds', 'allBnds']:
formatD[k] = ('%6d', 12, 3)
for k in ['allHAngs', 'allAngs']:
formatD[k] = ('%6d', 12, 4)
for k in ['allHDihe', 'allDihe']:
formatD[k] = ('%6d', 12, 5)
self.formatD = formatD
#processAtoms results are built in this dictionary
self.prmDict = {}
def getDictObj(self, nmstr):
#mod = __import__('MolKit/data/' + nmstr)
#dict = eval('mod.'+ nmstr)
mod = __import__('MolKit')
b = getattr(mod.data, nmstr)
dict = getattr(b, nmstr)
return dict
def loadFromFile(self, filename):
"""reads a parmtop file"""
self.prmDict = self.py_read(filename)
self.createSffCdataStruct(self.prmDict)
def processAtoms(self, atoms, parmDict=None, reorder=1):
"""finds all Amber parameters for the given set of atoms
parmDict is parm94_dat """
if atoms:
self.build(atoms, parmDict, reorder)
self.createSffCdataStruct(self.prmDict)
print 'after call to createSffCdataStruct'
def checkSanity(self):
d = self.prmDict
#length checks:
Natom = d['Natom']
assert len(d['Charges']) == Natom
assert len(d['Masses']) == Natom
assert len(d['Iac']) == Natom
assert len(d['Iblo']) == Natom
assert len(d['AtomRes']) == Natom
assert len(d['N14pairs']) == Natom
assert len(d['TreeJoin']) == Natom
Nres = d['Nres']
assert len(d['Ipres']) == Nres + 1
assert len(d['AtomNames']) == Natom * 4 + 81
assert len(d['AtomSym']) == Natom * 4 + 81
assert len(d['AtomTree']) == Natom * 4 + 81
assert len(d['ResNames']) == Nres * 4 + 81
#Ntypes is number of unique amber_types w/equiv replacement
Ntypes = d['Ntypes']
assert len(d['Cno']) == Ntypes**2
assert len(d['ExclAt']) == d['Nnb']
assert len(d['Cn1']) == Ntypes*(Ntypes+1)/2.
assert len(d['Cn2']) == Ntypes*(Ntypes+1)/2.
#Numbnd is number of bnd types
Numbnd = d['Numbnd']
assert len(d['Rk']) == Numbnd
assert len(d['Req']) == Numbnd
#Numang is number of angle types
Numang = d['Numang']
assert len(d['Tk']) == Numang
assert len(d['Teq']) == Numang
#Numptra is number of dihe types
Nptra = d['Nptra']
assert len(d['Pk']) == Nptra
assert len(d['Pn']) == Nptra
assert len(d['Phase']) == Nptra
assert len(d['Solty']) == d['Natyp']
#Nbona is number of bonds w/out H
Nbona = d['Nbona']
assert len(d['BondAt1']) == Nbona
assert len(d['BondAt2']) == Nbona
assert len(d['BondNum']) == Nbona
#Nbonh is number of bonds w/ H
Nbonh = d['Nbonh']
assert len(d['BondHAt1']) == Nbonh
assert len(d['BondHAt2']) == Nbonh
assert len(d['BondHNum']) == Nbonh
#Ntheta is number of angles w/out H
Ntheta = d['Ntheta']
assert len(d['AngleAt1']) == Ntheta
assert len(d['AngleAt2']) == Ntheta
assert len(d['AngleAt3']) == Ntheta
assert len(d['AngleNum']) == Ntheta
#Ntheth is number of angles w/ H
Ntheth = d['Ntheth']
assert len(d['AngleHAt1']) == Ntheth
assert len(d['AngleHAt2']) == Ntheth
assert len(d['AngleHAt3']) == Ntheth
assert len(d['AngleHNum']) == Ntheth
#Nphia is number of dihedrals w/out H
Nphia = d['Nphia']
assert len(d['DihAt1']) == Nphia
assert len(d['DihAt2']) == Nphia
assert len(d['DihAt3']) == Nphia
assert len(d['DihAt4']) == Nphia
assert len(d['DihNum']) == Nphia
#Nphih is number of dihedrals w/ H
Nphih = d['Nphih']
assert len(d['DihHAt1']) == Nphih
assert len(d['DihHAt2']) == Nphih
assert len(d['DihHAt3']) == Nphih
assert len(d['DihHAt4']) == Nphih
assert len(d['DihHNum']) == Nphih
##WHAT ABOUT HB10, HB12, N14pairs, N14pairlist
#value based on length checks:
#all values of BondNum and BondHNum in range (1, Numbnd)
for v in d['BondNum']:
assert v >0 and v < Numbnd + 1
for v in d['BondHNum']:
assert v >0 and v < Numbnd + 1
#all values of AngleNum and AngleHNum in range (1, Numang)
for v in d['AngleNum']:
assert v >0 and v < Numang + 1
for v in d['AngleHNum']:
assert v >0 and v < Numang + 1
#all values of DihNum and DihHNum in range (1, Nptra)
for v in d['DihNum']:
assert v >0 and v < Nptra + 1
for v in d['DihHNum']:
assert v >0 and v < Nptra + 1
def createSffCdataStruct(self, dict):
"""Create a C prm data structure"""
print 'in createSffCdataStruct'
self.ambPrm = AmberParm('test1', parmdict=dict)
print 'after call to init'
def build(self, allAtoms, parmDict, reorder):
# find out amber special residue name and
# order the atoms inside a residue to follow the Amber convention
self.residues = allAtoms.parent.uniq()
self.residues.sort()
self.fixResNamesAndOrderAtoms(reorder)
# save ordered chains
self.chains = self.residues.parent.uniq()
self.chains.sort()
# save ordered atoms
self.atoms = self.residues.atoms
# renumber them
self.atoms.number = range(1, len(allAtoms)+1)
print 'after call to checkRes'
self.getTopology(self.atoms, parmDict)
print 'after call to getTopology'
if reorder:
self.checkSanity()
print 'passed sanity check'
else:
print 'skipping sanity check'
return
def reorderAtoms(self, res, atList):
ats = []
rlen = len(res.atoms)
if rlen!=len(atList):
print "atoms missing in residue", res
print "expected:", atList
print "found :", res.atoms.name
for i in range(rlen):
a = atList[i]
for j in range(rlen):
b = res.atoms[j]
# DON'T rename HN atom H, HN1->H1, etc...
# use editCommands instead
#if b.name=='HN': b.name='H'
#elif len(b.name)==3 and b.name[:2]=='HN':
#b.name ='H'+b.name[2]
if b.name==a:
ats.append(b)
break
if len(ats)==len(res.atoms):
res.children.data = ats
res.atoms.data = ats
def fixResNamesAndOrderAtoms(self, reorder):
# level list of atom names used to rename residues
# check is HIS is HIS, HID, HIP, HIE, etc...
residues = self.residues
last = len(residues)-1
for i in range(len(residues)):
residue = residues[i]
chNames = residue.atoms.name
amberResType = residue.type
if amberResType=='CYS':
returnVal = 'CYS'
#3/21:
if 'HSG' in chNames or 'HG' in chNames:
amberResType ='CYS'
elif 'HN' in chNames:
amberResType = 'CYM'
else:
amberResType = 'CYX'
elif amberResType=='LYS':
# THIS DOESN'T SUPPORT LYH assigned in all.in
returnVal = 'LYS'
if 'HZ1' in chNames or 'HZN1' in chNames:
amberResType ='LYS'
else:
amberResType ='LYN'
elif amberResType=='ASP':
returnVal = 'ASP'
#3/21
if 'HD' in chNames or 'HD2' in chNames:
amberResType ='ASH'
else:
amberResType ='ASP'
elif amberResType=='GLU':
returnVal = 'GLU'
#3/21
if 'HE' in chNames or 'HE2' in chNames:
amberResType ='GLH'
else:
amberResType ='GLU'
elif amberResType=='HIS':
returnVal = 'HIS'
hasHD1 = 'HD1' in chNames
hasHD2 = 'HD2' in chNames
hasHE1 = 'HE1' in chNames
hasHE2 = 'HE2' in chNames
if hasHD1 and hasHE1:
if hasHD2 and not hasHE2:
amberResType = 'HID'
elif hasHD2 and hasHE2:
amberResType = 'HIP'
elif (not hasHD1) and (hasHE1 and hasHD2 and hasHE2):
amberResType = 'HIE'
else:
print 'unknown HISTIDINE config'
raise ValueError
residue.amber_type = amberResType
if residue == residue.parent.residues[0]:
residue.amber_dict = self.ntDict[amberResType]
elif residue == residue.parent.residues[-1]:
residue.amber_dict = self.ctDict[amberResType]
else:
residue.amber_dict = self.allDict[amberResType]
if reorder:
self.reorderAtoms(residue, residue.amber_dict['atNameList'])
def processChain(self, residues, parmDict):
#this should be called with a list of residues representing a chain
# NOTE: self.parmDict is parm94 which was parsed by Ruth while parmDict is
# MolKit.parm94_dat.py
dict = self.prmDict
#residues = self.residues
# initialize
atNames = ''
atSym = ''
atTree = ''
resname = ''
masses = dict['Masses']
charges = dict['Charges']
uniqList = []
uniqTypes = {} # used to build list with equivalent names removed
atypTypes = {} # used to build list without equivalent names removed
allTypeList = [] # list of all types
last = len(residues)-1
dict['Nres'] = dict['Nres'] + last + 1
atres = dict['AtomRes']
ipres = dict['Ipres']
maxResLen = 0
for i in range(last+1):
res = residues[i]
atoms = res.atoms
nbat = len(atoms)
if nbat > maxResLen: maxResLen = nbat
ipres.append(ipres[-1]+nbat)
resname = resname + res.amber_type + ' '
ad = res.amber_dict
pdm = parmDict.atomTypes
for a in atoms:
# get the amber atom type
name = a.name
atres.append(i+1)
atNames = atNames+'%-4s'%name
atD = ad[name]
a.amber_type = newtype = '%-2s'%atD['type']
chg = a._charges['amber'] = atD['charge']*18.2223
charges.append(chg)
mas = a.mass = pdm[newtype][0]
masses.append(mas)
atTree = atTree+'%-4.4s'%atD['tree']
allTypeList.append(newtype)
atSym = atSym+'%-4s'%newtype
symb = newtype[0]
if symb in parmDict.AtomEquiv.keys():
if newtype in parmDict.AtomEquiv[symb]:
newsym = symb + ' '
uniqTypes[symb+' '] = 0
a.amber_symbol = symb+' '
if newsym not in uniqList:
uniqList.append(newsym)
else:
uniqTypes[newtype] = 0
a.amber_symbol = newtype
if newtype not in uniqList:
uniqList.append(newtype)
else:
uniqTypes[newtype] = 0
a.amber_symbol = newtype
if newtype not in uniqList: uniqList.append(newtype)
# to get uniq list of all types w/out equiv replacement
atypTypes[newtype] = 0
# post processing of some variable
dict['AtomNames'] = dict['AtomNames'] + atNames
dict['AtomSym'] = dict['AtomSym'] + atSym
dict['AtomTree'] = dict['AtomTree'] + atTree
dict['ResNames'] = dict['ResNames'] + resname
# save list of unique types for later use
###1/10:
#self.uniqTypeList = uniqList
uL = self.uniqTypeList
for t in uniqList:
if t not in uL:
uL.append(t)
#self.uniqTypeList = uniqTypes.keys()
self.uniqTypeList = uL
ntypes = len(uL)
dict['Ntypes'] = ntypes
aL = self.atypList
for t in atypTypes.keys():
if t not in aL:
aL.append(t)
self.atypList = aL
dict['Natyp'] = len(aL)
dict['Ntype2d'] = ntypes*ntypes
dict['Nttyp'] = ntypes * (ntypes+1)/2
if maxResLen > dict['Nmxrs']:
dict['Nmxrs'] = maxResLen
newtypelist = []
for t in residues.atoms.amber_symbol:
# Iac is 1-based
newtypelist.append( self.uniqTypeList.index(t) + 1 )
###1/10:
#dict['Iac'] = newtypelist
dict['Iac'].extend( newtypelist)
def processBonds(self, bonds, parmDict):
# NOTE: self,parmDict is parm94 parsed by Ruth while parmDict is
# MolKit.parm94_dat.py):
dict = self.prmDict
bat1 = dict['BondAt1']
bat2 = dict['BondAt2']
bnum = dict['BondNum']
batH1 = dict['BondHAt1']
batH2 = dict['BondHAt2']
bHnum = dict['BondHNum']
rk = dict['Rk']
req = dict['Req']
bndTypes = {} # used to build a unique list of bond types
btDict = parmDict.bondTypes #needed to check for wildcard * in type
for b in bonds:
a1 = b.atom1
#t1 = a1.amber_symbol
t1 = a1.amber_type
a2 = b.atom2
#t2 = a2.amber_symbol
t2 = a2.amber_type
if t1<t2:
newtype = '%-2.2s-%-2.2s'%(t1,t2)
else:
newtype = '%-2.2s-%-2.2s'%(t2,t1)
bndTypes[newtype] = 0
n1 = (a1.number-1)*3
n2 = (a2.number-1)*3
if n2<n1: tmp=n1; n1=n2; n2=tmp
if a1.element=='H' or a2.element=='H':
bHnum.append(newtype)
batH1.append(n1)
batH2.append(n2)
else:
bnum.append(newtype)
bat1.append(n1)
bat2.append(n2)
dict['Numbnd'] = len(bndTypes)
btlist = bndTypes.keys()
for bt in btlist:
rk.append( btDict[bt][0] )
req.append( btDict[bt][1] )
newbnum = []
for b in bnum:
newbnum.append( btlist.index(b) + 1 )
dict['BondNum'] = newbnum
newbnum = []
for b in bHnum:
newbnum.append( btlist.index(b) + 1 )
dict['BondHNum'] = newbnum
return
def processAngles(self, allAtoms, parmDict):
dict = self.prmDict
aa1 = dict['AngleAt1']
aa2 = dict['AngleAt2']
aa3 = dict['AngleAt3']
anum = dict['AngleNum']
aHa1 = dict['AngleHAt1']
aHa2 = dict['AngleHAt2']
aHa3 = dict['AngleHAt3']
aHnum = dict['AngleHNum']
tk = dict['Tk']
teq = dict['Teq']
angTypes = {}
atdict = parmDict.bondAngles
for a1 in allAtoms:
t1 = a1.amber_type
for b in a1.bonds:
a2 = b.atom1
if id(a2)==id(a1): a2=b.atom2
t2 = a2.amber_type
for b2 in a2.bonds:
a3 = b2.atom1
if id(a3)==id(a2): a3=b2.atom2
if id(a3)==id(a1): continue
if a1.number > a3.number: continue
t3 = a3.amber_type
nn1 = n1 = (a1.number-1)*3
nn2 = n2 = (a2.number-1)*3
nn3 = n3 = (a3.number-1)*3
if n3<n1:
nn3 = n1
nn1 = n3
rev = 0
if (t1==t3 and a1.name > a3.name) or t3 < t1:
rev = 1
if rev:
newtype = '%-2.2s-%-2.2s-%-2.2s'%(t3,t2,t1)
else:
newtype = '%-2.2s-%-2.2s-%-2.2s'%(t1, t2, t3)
#have to check for wildcard *
angTypes[newtype] = 0
if a1.element=='H' or a2.element=='H' or a3.element=='H':
aHa1.append( nn1 )
aHa2.append( nn2 )
aHa3.append( nn3 )
aHnum.append(newtype)
else:
aa1.append( nn1 )
aa2.append( nn2 )
aa3.append( nn3 )
anum.append(newtype)
atlist = angTypes.keys()
torad = pi / 180.0
atKeys = atdict.keys()
for t in atlist:
tk.append( atdict[t][0] )
teq.append( atdict[t][1]*torad )
anewlist = []
for a in anum:
anewlist.append( atlist.index( a ) + 1 )
dict['AngleNum'] = anewlist
anewlist = []
for a in aHnum:
anewlist.append( atlist.index( a ) + 1 )
dict['AngleHNum'] = anewlist
dict['Numang'] = len(atlist)
dict['Ntheth'] = len(aHa1)
dict['Mtheta'] = len(aa1)
dict['Ntheta'] = len(aa1)
return
def checkDiheType(self, t, t2, t3, t4, dict):
#zero X
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%(t,t2,t3,t4)
if dict.has_key(newtype): return newtype
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%(t4,t3,t2,t)
if dict.has_key(newtype): return newtype
#X
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t2,t3,t4)
if dict.has_key(newtype): return newtype
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t3,t2,t)
if dict.has_key(newtype): return newtype
#2X
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t2,t3,'X')
if dict.has_key(newtype): return newtype
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t3,t2,'X')
if dict.has_key(newtype): return newtype
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X','X',t3,t4)
if dict.has_key(newtype): return newtype
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X','X',t2,t)
if dict.has_key(newtype): return newtype
raise RuntimeError('dihedral type not in dictionary')
## it is slower to check a list if the key is in there than to ask a
## dictionanry if it has this key
##
## keys = dict.keys()
## #zero X
## newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%(t,t2,t3,t4)
## if newtype in keys:
## return newtype
## newtype2 = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%(t4,t3,t2,t)
## if newtype2 in keys:
## return newtype2
## #X
## newtypeX = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t2,t3,t4)
## if newtypeX in keys:
## return newtypeX
## newtype2X = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t3,t2,t)
## if newtype2X in keys:
## return newtype2X
## #2X
## newtypeX_X = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t2,t3,'X')
## if newtypeX_X in keys:
## return newtypeX_X
## newtype2X_X = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X',t3,t2,'X')
## if newtype2X_X in keys:
## return newtype2X_X
## newtypeXX = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X','X',t3,t4)
## if newtypeXX in keys:
## return newtypeXX
## newtype2XX = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%('X','X',t2,t)
## if newtype2XX in keys:
## return newtype2XX
## raise RuntimError('dihedral type not in dictionary')
def processTorsions(self, allAtoms, parmDict):
# find torsions and also excuded atoms
dict = self.prmDict
foundDihedTypes = {}
ta1 = dict['DihAt1']
ta2 = dict['DihAt2']
ta3 = dict['DihAt3']
ta4 = dict['DihAt4']
tnum = dict['DihNum']
taH1 = dict['DihHAt1']
taH2 = dict['DihHAt2']
taH3 = dict['DihHAt3']
taH4 = dict['DihHAt4']
tHnum = dict['DihHNum']
nb14 = dict['N14pairs']
n14list = dict['N14pairlist']
iblo = dict['Iblo']
exclAt = dict['ExclAt']
dihedTypes = parmDict.dihedTypes
for a1 in allAtoms:
n14 = []
excl = []
t1 = a1.amber_type
restyp = a1.parent.type
if restyp in ['PRO', 'TRP', 'HID', 'HIE', 'HIP']:
ringlist = self.AA5rings[restyp]
else:
ringlist = None
for b in a1.bonds:
a2 = b.atom1
if id(a2)==id(a1): a2=b.atom2
t2 = a2.amber_type
if a2.number > a1.number: excl.append(a2.number)
for b2 in a2.bonds:
a3 = b2.atom1
if id(a3)==id(a2): a3=b2.atom2
if id(a3)==id(a1): continue
if a3.number > a1.number: excl.append(a3.number)
t3 = a3.amber_type
for b3 in a3.bonds:
a4 = b3.atom1
if id(a4)==id(a3): a4=b3.atom2
if id(a4)==id(a2): continue
if id(a4)==id(a1): continue
if a1.number > a4.number: continue
excl.append(a4.number)
t4 = a4.amber_type
newtype = '%-2.2s-%-2.2s-%-2.2s-%-2.2s'%(t1,t2,t3,t4)
dtype = self.checkDiheType(t1,t2,t3,t4,dihedTypes)
for i in range(len(dihedTypes[dtype])):
tname = dtype+'_'+str(i)
foundDihedTypes[tname] = 0
sign3 = 1
period = dihedTypes[dtype][i][3]
if period < 0.0: sign3= -1
if a4.parent==a1.parent:
if ringlist and a4.name in ringlist \
and a1.name in ringlist:
sign3= -1
if a1.element=='H' or a2.element=='H' or \
a3.element=='H' or a4.element=='H':
taH1.append( (a1.number-1)*3 )
taH2.append( (a2.number-1)*3 )
taH3.append( sign3*(a3.number-1)*3 )
taH4.append( (a4.number-1)*3 )
tHnum.append( tname )
else:
ta1.append( (a1.number-1)*3 )
ta2.append( (a2.number-1)*3 )
ta3.append( sign3*(a3.number-1)*3 )
ta4.append( (a4.number-1)*3 )
tnum.append( tname )
if sign3>0.0:
# this trick work only for 6 rings and
# prevents from adding 14 interactions
# twice between atoms in the ring
# PRO, TRP and HIS and cp. have to be handle
# separately
num = a4.number-1
if num not in n14:
n14.append( num )
else: # make 3rd atom in torsion negative
ta3[-1] = -ta3[-1]
if len(excl):
# excl can contain duplicated values (pro tyr phe cycles)
# we also sort the values (probably only comsetics)
excl.sort()
last = excl[0]
uexcl = [last]
for i in range(1,len(excl)):
if excl[i]!=last:
last = excl[i]
uexcl.append(last)
iblo.append(len(uexcl))
exclAt.extend(uexcl)
else:
iblo.append( 1 )
exclAt.append( 0 )
nb14.append(len(n14))
##!##1/28: n14.sort()
n14list.extend(n14)
# remember how many proper diehedrals
lastProper = len(tnum)
lastHProper = len(tHnum)
# loop over residues to add improper torsions
sumAts = 0
foundImproperDihedTypes = {}
for res in self.residues:
foundImproperDihedTypes = self.getImpropTors(
res, sumAts, foundImproperDihedTypes, parmDict)
sumAts = sumAts + len(res.atoms)
#typeDict = foundDihedTypes.copy()
#typeDict.update(foundImproperDihedTypes)
#print typeDict.keys()
dict['Nptra'] = len(foundDihedTypes) + len(foundImproperDihedTypes)
dict['Mphia'] = dict['Nphia'] = len(ta1)
dict['Nphih'] = len(taH1)
pn = dict['Pn']
pk = dict['Pk']
phase = dict['Phase']
dtlist = foundDihedTypes.keys()
torad = pi/180.
for t in dtlist:
index = int(t[-1])
val = dihedTypes[t[:-2]][index] # remove the '_x'
pk.append(val[1]/val[0])
phase.append(val[2]*torad)
pn.append(fabs(val[3]))
dihedTypes = parmDict.improperDihed
dtlist1 = foundImproperDihedTypes.keys()
for t in dtlist1:
val = dihedTypes[t]
pk.append(val[0])
phase.append(val[1]*torad)
pn.append(val[2])
typenum = []
dtlist = dtlist + dtlist1
for t in tnum:
typenum.append( dtlist.index(t) + 1 ) # types are 1-based
dict['DihNum'] = typenum
typenum = []
for t in tHnum:
typenum.append( dtlist.index(t) + 1 ) # types are 1-based
dict['DihHNum'] = typenum
dict['Nnb'] = len(dict['ExclAt'])
#print len(tnum), len(dict['DihNum'])
return
def getImpropTors(self, res, sumAts, foundDihedTypes, parmDict):
#eg tList:[['CA','+M','C','0'],['-M','CA','N','H']]
dict = self.prmDict
offset = sumAts * 3
nameList = res.atoms.name
typeList = res.atoms.amber_type
ta1 = dict['DihAt1']
ta2 = dict['DihAt2']
ta3 = dict['DihAt3']
ta4 = dict['DihAt4']
tnum = dict['DihNum']
taH1 = dict['DihHAt1']
taH2 = dict['DihHAt2']
taH3 = dict['DihHAt3']
taH4 = dict['DihHAt4']
tHnum = dict['DihHNum']
dihedTypes = parmDict.improperDihed
atNameList = res.amber_dict['atNameList']
resat = res.atoms
for item in res.amber_dict['impropTors']:
atomNum = []
atomType = []
newTors = []
offset = res.atoms[0].number
#use hasH to detect 'HZ2' etc
hasH = 0
for t in item:
if t[0]=='H': hasH = 1
if len(t)==2 and t[1]=='M':
if t[0]=='-':
atomType.append('C ')
atomNum.append(offset - 2)
else:
atomType.append('N ')
atomNum.append(offset + len(res.atoms) )
else:
atIndex = atNameList.index(t)
atom = resat[atIndex]
atomType.append(atom.amber_type)
atomNum.append( atom.number )
newType = self.checkDiheType(atomType[0], atomType[1],
atomType[2], atomType[3],
dihedTypes)
foundDihedTypes[newType] = 0
if hasH:
taH1.append( (atomNum[0]-1)*3 )
taH2.append( (atomNum[1]-1)*3 )
taH3.append(-(atomNum[2]-1)*3 )
taH4.append(-(atomNum[3]-1)*3 )
tHnum.append(newType)
else:
ta1.append( (atomNum[0]-1)*3 )
ta2.append( (atomNum[1]-1)*3 )
ta3.append(-(atomNum[2]-1)*3 )
ta4.append(-(atomNum[3]-1)*3 )
tnum.append(newType)
return foundDihedTypes
def getTopology(self, allAtoms, parmDict):
dict = self.prmDict
dict['ititl'] = allAtoms.top.uniq()[0].name + '.prmtop\n'
natom = dict['Natom'] = len(allAtoms)
dict['Nat3'] = natom * 3
dict['AtomNames'] = ''
dict['AtomSym'] = ''
dict['AtomTree'] = ''
dict['Ntypes'] = 0
dict['Natyp'] = 0
dict['Ntype2d'] = 0
dict['Nttyp'] = 0
dict['Masses'] = []
dict['Charges'] = []
dict['Nres'] = 0
dict['AtomRes'] = []
dict['ResNames'] = ''
dict['Ipres'] = [1]
dict['Nmxrs'] = 0
###1/10:
dict['Iac'] = []
self.uniqTypeList = []
#used for construction of Natyp
self.atypList = []
# fill get all arrays that are of len natom
# we have to call for each chain
for ch in self.chains:
self.processChain( ch.residues, parmDict)
#PAD AtomNames with 81 spaces
dict['AtomNames'] = dict['AtomNames'] + 81*' '
dict['AtomSym'] = dict['AtomSym'] + 81*' '
dict['AtomTree'] = dict['AtomTree'] + 81*' '
dict['ResNames'] = dict['ResNames'] + 81*' '
# create Iac list
#iac = []
#tl = self.uniqTypeList
#for a in allAtoms:
# iac.append( tl.index(a.amber_symbol) + 1 )
# delattr(a, 'amber_symbol')
#dict['Iac'] = iac
# to find out the number of bonds with hydrogen we simply count the
# number of hydrogen atoms
hlist = allAtoms.get(lambda x: x.element=='H')
if hlist is not None and len(hlist):
dict['Nbonh'] = numHs = len(hlist)
else:
numHs = 0
# number of bonds not involving an H atom
bonds = allAtoms.bonds[0]
dict['Mbona'] = len(bonds) - numHs
# since no bonds are constrined, Nbona==Mbona
dict['Nbona'] = dict['Mbona']
print 'after call to processChain'
# new process bond info
dict['BondAt1'] = []
dict['BondAt2'] = []
dict['BondNum'] = []
dict['BondHAt1'] = []
dict['BondHAt2'] = []
dict['BondHNum'] = []
dict['Rk'] = []
dict['Req'] = []
self.processBonds(bonds, parmDict)
print 'after call to processBonds'
# now process the angles
dict['AngleAt1'] = []
dict['AngleAt2'] = []
dict['AngleAt3'] = []
dict['AngleNum'] = []
dict['AngleHAt1'] = []
dict['AngleHAt2'] = []
dict['AngleHAt3'] = []
dict['AngleHNum'] = []
dict['Tk'] = []
dict['Teq'] = []
self.processAngles(allAtoms, parmDict)
print 'after call to processAngles'
# now handle the torsions
dict['Nhparm'] = 0
dict['Nparm'] = 0
dict['DihAt1'] = []
dict['DihAt2'] = []
dict['DihAt3'] = []
dict['DihAt4'] = []
dict['DihNum'] = []
dict['DihHAt1'] = []
dict['DihHAt2'] = []
dict['DihHAt3'] = []
dict['DihHAt4'] = []
dict['DihHNum'] = []
dict['Pn'] = []
dict['Pk'] = []
dict['Phase'] = []
dict['Nphih'] = dict['Mphia'] = dict['Nphia'] = dict['Nptra'] = 0
dict['N14pairs'] = []
dict['N14pairlist'] = []
dict['Nnb'] =0
dict['Iblo'] = []
dict['ExclAt'] = []
# FIXME
self.AA5rings ={
'PRO':['N', 'CA', 'CB', 'CG', 'CD'],
'TRP':['CG', 'CD1', 'CD2', 'NE1', 'CE2'],
'HID':['CG', 'ND1', 'CE1', 'NE2', 'CD2'],
'HIE':['CG', 'ND1', 'CE1', 'NE2', 'CD2'],
'HIP':['CG', 'ND1', 'CE1', 'NE2', 'CD2']
}
self.processTorsions(allAtoms, parmDict)
print 'after call to processTorsions'
# some unused values
dict['Nspm'] = 1
dict['Box'] = [0., 0., 0.]
dict['Boundary'] = [natom]
dict['TreeJoin'] = range(natom)
dict['Nphb'] = 0
dict['HB12'] = []
dict['HB10'] = []
llist = ['Ifpert', 'Nbper','Ngper','Ndper','Mbper', 'Mgper',
'Mdper','IfBox', 'IfCap', 'Cutcap', 'Xcap', 'Ycap',
'Zcap', 'Natcap','Ipatm', 'Nspsol','Iptres']
for item in llist:
dict[item] = 0
dict['Cno'] = self.getICO( dict['Ntypes'] )
dict['Solty'] = self.getSOLTY( dict['Natyp'] )
dict['Cn1'], dict['Cn2'] = self.getCNList(parmDict)
return
def getICO(self, ntypes):
ct = 1
icoArray = Numeric.zeros((ntypes, ntypes), 'i')
for i in range(1, ntypes+1):
for j in range(1, i+1):
icoArray[i-1,j-1]=ct
icoArray[j-1,i-1]=ct
ct = ct+1
return icoArray.ravel().tolist()
def getSOLTY(self, ntypes):
soltyList = []
for i in range(ntypes):
soltyList.append(0.)
return soltyList
def getCN(self, type1, type2, pow, parmDict, factor=1):
#pow is 12 or 6
#factor is 1 except when pow is 6
d = parmDict.potParam
if type1=='N3': type1='N '
if type2=='N3': type2='N '
r1, eps1 = d[type1][:2]
r2, eps2 = d[type2][:2]
eps = sqrt(eps1*eps2)
rij = r1 + r2
newval = factor*eps*rij**pow
return newval
def getCNList(self, parmDict):
ntypes = len(self.uniqTypeList)
ct = 1
## size = self.prmDict['Nttyp']
## cn1List = [0]*size
## cn2List = [0]*size
## iac = self.prmDict['Iac']
## cno = self.prmDict['Cno']
## for i in range(ntypes):
## indi = i*ntypes
## ival = self.uniqTypeList[i]
## for j in range(i, ntypes):
## jval = self.uniqTypeList[j]
## ind = cno[indi+j]-1
## cn1List[ind] = self.getCN(jval, ival, 12, parmDict)
## cn2List[ind] = self.getCN(jval, ival, 6, parmDict, 2)
nttyp = self.prmDict['Nttyp']
cn1List = []
cn2List = []
for j in range(ntypes):
jval = self.uniqTypeList[j]
for i in range(j+1):
ival = self.uniqTypeList[i]
cn1List.append(self.getCN(ival, jval, 12, parmDict))
cn2List.append(self.getCN(ival, jval, 6, parmDict, 2))
return cn1List, cn2List
def readSummary(self, allLines, dict):
#set summary numbers
ll = split(allLines[1])
assert len(ll)==12
#FIX THESE NAMES!
natom = dict['Natom'] = int(ll[0])
ntypes = dict['Ntypes'] = int(ll[1])
nbonh = dict['Nbonh'] = int(ll[2])
dict['Mbona'] = int(ll[3])
ntheth = dict['Ntheth'] = int(ll[4])
dict['Mtheta'] = int(ll[5])
nphih = dict['Nphih'] = int(ll[6])
dict['Mphia'] = int(ll[7])
dict['Nhparm'] = int(ll[8])
dict['Nparm'] = int(ll[9])
#called 'next' in some documentation
#NEXT-> Nnb
next = dict['Nnb'] = int(ll[10])
dict['Nres'] = int(ll[11])
ll = split(allLines[2])
assert len(ll)==12
nbona = dict['Nbona'] = int(ll[0])
ntheta = dict['Ntheta'] = int(ll[1])
nphia = dict['Nphia'] = int(ll[2])
numbnd = dict['Numbnd'] = int(ll[3])
numang = dict['Numang'] = int(ll[4])
numptra = dict['Nptra'] = int(ll[5])
natyp = dict['Natyp'] = int(ll[6])
dict['Nphb'] = int(ll[7])
dict['Ifpert'] = int(ll[8])
dict['Nbper'] = int(ll[9])
dict['Ngper'] = int(ll[10])
dict['Ndper'] = int(ll[11])
ll = split(allLines[3])
assert len(ll)==6
dict['Mbper'] = int(ll[0])
dict['Mgper'] = int(ll[1])
dict['Mdper'] = int(ll[2])
dict['IfBox'] = int(ll[3])
dict['Nmxrs'] = int(ll[4])
dict['IfCap'] = int(ll[5])
return dict
def readIGRAPH(self, allLines, numIGRAPH, ind=3):
#the names are not necessarily whitespace delimited
igraph = []
for i in range(numIGRAPH):
ind = ind + 1
l = allLines[ind]
for k in range(20):
it = l[k*4:k*4+4]
igraph.append(strip(it))
#igraph.extend(split(l))
return igraph, ind
def readCHRG(self, allLines, ind, numCHRG, natom):
chrg = []
ct = 0
for i in range(numCHRG):
ind = ind + 1
l = allLines[ind]
newl = []
# build 5 charges per line if enough are left
#otherwise, build the last line's worth
if natom - ct >=5:
rct = 5
else:
rct = natom - ct
for q in range(rct):
lindex = q*16
item = l[lindex:lindex+16]
newl.append(float(item))
ct = ct + 1
chrg.extend(newl)
return chrg, ind
def readNUMEX(self, allLines, ind, numIAC):
numex = []
NumexSUM = 0
for i in range(numIAC):
ind = ind + 1
ll = split(allLines[ind])
newl = []
for item in ll:
newent = int(item)
newl.append(newent)
NumexSUM = NumexSUM + newent
numex.extend(newl)
return numex, ind, NumexSUM
def readLABRES(self, allLines, ind):
done = 0
labres = []
while not done:
ind = ind + 1
ll = split(allLines[ind])
try:
int(ll[0])
done = 1
break
except ValueError:
labres.extend(ll)
#correct for 1 extra line read here
ind = ind - 1
return labres, ind
def readFList(self, allLines, ind, numITEMS):
v = []
for i in range(numITEMS):
ind = ind + 1
ll = split(allLines[ind])
newl = []
for item in ll:
newl.append(float(item))
v.extend(newl)
return v, ind
def readIList(self, allLines, ind, numITEMS):
v = []
for i in range(numITEMS):
ind = ind + 1
ll = split(allLines[ind])
newl = []
for item in ll:
newl.append(int(item))
v.extend(newl)
return v, ind
def readILList(self, allLines, ind, numITEMS, n):
bhlist = []
for i in range(n):
bhlist.append([])
ct = 0
for i in range(numITEMS):
ind = ind + 1
ll = split(allLines[ind])
for j in range(len(ll)):
item = ll[j]
newl = bhlist[ct%n]
newl.append(int(item))
ct = ct + 1
return bhlist, ind
def py_read(self, filename, **kw):
#??dict['Iptres'] #dict['Nspsol'] #dict['Ipatm'] #dict['Natcap']
f = open(filename, 'r')
allLines = f.readlines()
f.close()
dict = {}
#set title
dict['ititl'] = allLines[0]
#get summary numbers
dict = self.readSummary(allLines, dict)
#set up convenience fields:
natom = dict['Natom']
ntypes = dict['Ntypes']
dict['Nat3'] = natom * 3
dict['Ntype2d'] = ntypes ** 2
nttyp = dict['Nttyp'] = ntypes * (ntypes+1)/2
# read IGRAPH->AtomNames
numIGRAPH = int(ceil((natom*1.)/20.))
anames, ind = self.readIGRAPH(allLines, numIGRAPH)
dict['AtomNames'] = join(anames)
# read CHRG->Charges
numCHRG = int(ceil((natom*1.)/5.))
dict['Charges'], ind = self.readCHRG(allLines, ind, numCHRG, natom)
# read AMASS **same number of lines as charges->Masses
dict['Masses'], ind = self.readFList(allLines, ind, numCHRG)
# read IAC **NOT same number of lines as IGRAPH 12!!
numIAC = int(ceil((natom*1.)/12.))
dict['Iac'], ind = self.readIList(allLines, ind, numIAC)
# read NUMEX **same number of lines as IAC
dict['Iblo'], ind, NumexSUM = self.readNUMEX(allLines, ind, numIAC)
# read ICO *Ntype2d/12
numICO = int(ceil((ntypes**2*1.0)/12.))
dict['Cno'], ind = self.readIList(allLines, ind, numICO)
##NB this should be half of a matrix
# read LABRES....no way to know how many
dict['ResNames'], ind = self.readLABRES(allLines, ind)
labres = dict['ResNames']
# read IPRES....depends on len of LABRES
numIPRES = int(ceil((len(labres)*1.)/20.))
dict['Ipres'], ind = self.readIList(allLines, ind, numIPRES)
# read RK + REQ-> depend on numbnd
numbnd = dict['Numbnd']
numRK = int(ceil((numbnd*1.)/5.))
dict['Rk'], ind = self.readFList(allLines, ind, numRK)
dict['Req'], ind = self.readFList(allLines, ind, numRK)
# read TK + TEQ-> depend on numang
numang = dict['Numang']
numTK = int(ceil((numang*1.)/5.))
dict['Tk'], ind = self.readFList(allLines, ind, numTK)
dict['Teq'], ind = self.readFList(allLines, ind, numTK)
# read PK, PN + PHASE-> depend on numptra
nptra = dict['Nptra']
numPK = int(ceil((nptra*1.)/5.))
dict['Pk'], ind = self.readFList(allLines, ind, numPK)
dict['Pn'], ind = self.readFList(allLines, ind, numPK)
dict['Phase'], ind = self.readFList(allLines, ind, numPK)
# read SOLTY
natyp = dict['Natyp']
numSOLTY = int(ceil((natyp*1.)/5.))
dict['Solty'], ind = self.readFList(allLines, ind, numSOLTY)
# read CN1 and CN2
numCN = int(ceil((nttyp*1.)/5.))
dict['Cn1'], ind = self.readFList(allLines, ind, numCN)
dict['Cn2'], ind = self.readFList(allLines, ind, numCN)
# read IBH, JBH, ICBH 12
nbonh = dict['Nbonh']
numIBH = int(ceil((nbonh*3.0)/12.))
[dict['BondHAt1'], dict['BondHAt2'], dict['BondHNum']], ind = \
self.readILList(allLines, ind, numIBH, 3)
# read IB, JB, ICB 12
nbona = dict['Nbona']
numIB = int(ceil((nbona*3.0)/12.))
[dict['BondAt1'], dict['BondAt2'], dict['BondNum']], ind = \
self.readILList(allLines, ind, numIB, 3)
# read ITH, JTH, KTH, ICTH 12
ntheth = dict['Ntheth']
numITH = int(ceil((ntheth*4.0)/12.))
[dict['AngleHAt1'], dict['AngleHAt2'], dict['AngleHAt3'],\
dict['AngleHNum']], ind = self.readILList(allLines, ind, numITH, 4)
# read IT, JT, KT, ICT 12
ntheta = dict['Ntheta']
numIT = int(ceil((ntheta*4.0)/12.))
[dict['AngleAt1'], dict['AngleAt2'], dict['AngleAt3'],\
dict['AngleNum']], ind = self.readILList(allLines, ind, numIT, 4)
# read IPH, JPH, KPH, LPH, ICPH 12
nphih = dict['Nphih']
numIPH = int(ceil((nphih*5.0)/12.))
[dict['DihHAt1'], dict['DihHAt2'], dict['DihHAt3'], dict['DihHAt4'],\
dict['DihHNum']], ind = self.readILList(allLines, ind, numIPH, 5)
# read IP, JP, KP, LP, ICP 12
nphia = dict['Nphia']
numIP = int(ceil((nphia*5.0)/12.))
[dict['DihAt1'], dict['DihAt2'], dict['DihAt3'], dict['DihAt4'],\
dict['DihNum']], ind = self.readILList(allLines, ind, numIP, 5)
# read NATEX 12
#FIX THIS: has to be the sum of previous entries
numATEX = int(ceil((NumexSUM*1.0)/12.))
dict['ExclAt'], ind = self.readIList(allLines, ind, numATEX)
# read CN1 and CN2
# skip ASOL
# skip BSOL
# skip HBCUT
ind = ind + 3
# read ISYMBL 20
asym, ind = self.readIGRAPH(allLines, numIGRAPH, ind)
dict['AtomSym'] = join(asym)
# read ITREE 20
atree, ind = self.readIGRAPH(allLines, numIGRAPH, ind)
dict['AtomTree'] = join(atree)
return dict
def makeList(self, llist, num):
newL = []
for i in range(len(llist[0])):
ni = []
for j in range(num):
ni.append(llist[j][i])
newL.append(ni)
return newL
#functions to write self
def write(self, filename, **kw):
fptr = open(filename, 'w')
dict = self.prmDict
self.writeItitl(fptr, dict['ititl'])
self.writeSummary(fptr)
#WHAT ABOUT SOLTY???
self.writeString(fptr,dict['AtomNames'][:-81])
for k in ['Charges', 'Masses', 'Iac','Iblo','Cno']:
item = dict[k]
f = self.formatD[k]
if f[2]:
self.writeTupleList(fptr, item, f[0], f[1], f[2])
else:
self.writeList(fptr, item, f[0], f[1])
self.writeString(fptr,dict['ResNames'][:-81])
self.writeList(fptr, dict['Ipres'][:-1], '%6d', 12 )
for k in ['Rk', 'Req', 'Tk', 'Teq',
'Pk', 'Pn', 'Phase', 'Solty', 'Cn1','Cn2']:
item = dict[k]
f = self.formatD[k]
if f[2]:
self.writeTupleList(fptr, item, f[0], f[1], f[2])
else:
self.writeList(fptr, item, f[0], f[1])
#next write bnds angs and dihe
allHBnds = zip(dict['BondHAt1'], dict['BondHAt2'],
dict['BondHNum'])
self.writeTupleList(fptr, allHBnds, "%6d", 12, 3)
allBnds = zip(dict['BondAt1'], dict['BondAt2'],
dict['BondNum'])
self.writeTupleList(fptr, allBnds, "%6d", 12, 3)
allHAngs = zip(dict['AngleHAt1'], dict['AngleHAt2'],
dict['AngleHAt3'], dict['AngleHNum'])
self.writeTupleList(fptr, allHAngs, "%6d", 12,4)
allAngs = zip(dict['AngleAt1'], dict['AngleAt2'],
dict['AngleAt3'], dict['AngleNum'])
self.writeTupleList(fptr, allAngs, "%6d", 12, 4)
allHDiHe = zip(dict['DihHAt1'], dict['DihHAt2'],
dict['DihHAt3'], dict['DihHAt4'], dict['DihHNum'])
self.writeTupleList(fptr, allHDiHe, "%6d", 12,5)
allDiHe = zip(dict['DihAt1'], dict['DihAt2'],
dict['DihAt3'], dict['DihAt4'], dict['DihNum'])
self.writeTupleList(fptr, allDiHe, "%6d", 12, 5)
self.writeList(fptr, dict['ExclAt'], '%6d', 12)
fptr.write('\n')
fptr.write('\n')
fptr.write('\n')
for k in ['AtomSym', 'AtomTree']:
item = dict[k][:-81]
self.writeString(fptr, item)
zList = []
for i in range(dict['Natom']):
zList.append(0)
self.writeList(fptr, zList, "%6d", 12)
self.writeList(fptr, zList, "%6d", 12)
fptr.close()
def writeString(self, fptr, item):
n = int(ceil(len(item)/80.))
for p in range(n):
if p!=n-1:
fptr.write(item[p*80:(p+1)*80]+'\n')
else:
#write to the end, whereever it is
fptr.write(item[p*80:]+'\n')
def writeList(self, fptr, outList, formatStr="%4.4s", lineCt=12):
ct = 0
s = ""
nlformatStr = formatStr+'\n'
lenList = len(outList)
for i in range(lenList):
#do something with outList[i]
s = s + formatStr%outList[i]
#ct is how many item are in s
ct = ct + 1
#if line is full, write it and reset s and ct
if ct%lineCt==0:
s = s + '\n'
fptr.write(s)
s = ""
ct = 0
#if last entry write it and exit
elif i == lenList-1:
s = s + '\n'
fptr.write(s)
break
def writeTupleList(self, fptr, outList, formatStr="%4.4s", lineCt=12, ll=2):
ct = 0
s = ""
nlformatStr = formatStr+'\n'
for i in range(len(outList)):
if i==len(outList)-1:
for k in range(ll):
s = s + formatStr%outList[i][k]
ct = ct + 1
if ct%lineCt==0:
s = s + '\n'
fptr.write(s)
s = ""
ct = 0
#after adding last entry, if anything left, print it
if ct!=0:
s = s + '\n'
fptr.write(s)
else:
for k in range(ll):
s = s + formatStr%outList[i][k]
ct = ct + 1
if ct%lineCt==0:
s = s + '\n'
fptr.write(s)
s = ""
ct = 0
def writeItitl(self, fptr, ititl):
fptr.write(ititl)
def writeSummary(self, fptr):
#SUMMARY
#fptr.write('SUMMARY\n')
##FIX THESE NAMES!!!
kL1 = ['Natom','Ntypes','Nbonh','Mbona',\
'Ntheth','Mtheta','Nphih','Mphia','Nhparm',\
'Nparm','Nnb','Nres']
kL2 = ['Nbona','Ntheta','Nphia','Numbnd',\
'Numang','Nptra','Natyp','Nphb','Ifpert',\
'Nbper','Ngper','Ndper']
kL3 = ['Mbper','Mgper','Mdper','IfBox','Nmxrs',\
'IfCap']
for l in [kL1, kL2, kL3]:
newL = []
for item in l:
newL.append(self.prmDict[item])
#print 'newL=', newL
self.writeList(fptr, newL, "%6d", 12)
if __name__ == '__main__':
# load a protein and build bonds
from MolKit import Read
p = Read('sff/testdir/p1H.pdb')
p[0].buildBondsByDistance()
# build an Amber parameter description objects
from MolKit.amberPrmTop import ParameterDict
pd = ParameterDict()
from MolKit.amberPrmTop import Parm
prm = Parm()
prm.processAtoms(p.chains.residues.atoms)
```
#### File: pdb2pqr/extensions/hbond.py
```python
__date__ = "17 February 2006"
__author__ = "<NAME>"
from src.utilities import *
from src.routines import *
ANGLE_CUTOFF = 20.0 # A - D - H(D) angle
DIST_CUTOFF = 3.3 # H(D) to A distance
def usage():
str = " --hbond : Print a list of hydrogen bonds to\n"
str += " {output-path}.hbond\n"
return str
def hbond(routines, outroot):
"""
Print a list of hydrogen bonds.
Parameters
routines: A link to the routines object
outroot: The root of the output name
"""
outname = outroot + ".hbond"
file = open(outname, "w")
routines.write("Printing hydrogen bond list...\n")
# Initialize - set nearby cells, donors/acceptors
# The cell size adds one for the D-H(D) bond, and rounds up
cellsize = int(DIST_CUTOFF + 1.0 + 1.0)
protein = routines.protein
routines.setDonorsAndAcceptors()
routines.cells = Cells(cellsize)
routines.cells.assignCells(protein)
for donor in protein.getAtoms():
# Grab the list of donors
if not donor.hdonor: continue
donorhs = []
for bond in donor.bonds:
if bond.isHydrogen(): donorhs.append(bond)
if donorhs == []: continue
# For each donor, grab all acceptors
closeatoms = routines.cells.getNearCells(donor)
for acc in closeatoms:
if not acc.hacceptor: continue
if donor.residue == acc.residue: continue
for donorh in donorhs:
# Do distance and angle checks
dist = distance(donorh.getCoords(), acc.getCoords())
if dist > DIST_CUTOFF: continue
angle = getAngle(acc.getCoords(), donor.getCoords(), donorh.getCoords())
if angle > ANGLE_CUTOFF: continue
routines.write("Donor: %s %s\tAcceptor: %s %s\tHdist: %.2f\tAngle: %.2f\n" % \
(donor.residue, donor.name, acc.residue, acc.name, dist, angle))
file.write("Donor: %s %s\tAcceptor: %s %s\tHdist: %.2f\tAngle: %.2f\n" % \
(donor.residue, donor.name, acc.residue, acc.name, dist, angle))
routines.write("\n")
file.close()
```
#### File: MolKit/pdb2pqr/hydrogens.py
```python
__date__ = "8 March 2004"
__author__ = "<NAME>, <NAME>"
HYDROGENFILE = "HYDROGENS.DAT"
HACCEPTOR=[0,1,1,0,1,1,0,1,0,1,0,0,1,0]
HDONOR =[0,0,1,1,1,0,1,0,1,0,0,0,1,1]
HYDROGEN_DIST = 6.0
WATER_DIST=4.0
import os
import string
from definitions import *
from utilities import *
from math import *
from quatfit import *
from random import *
from time import *
class hydrogenAmbiguity:
"""
A class containing information about the ambiguity
"""
def __init__(self, residue, hdef):
"""
Initialize the class
Parameters
residue: The residue in question (residue)
hdef: The hydrogen definition matching the residue
"""
self.residue = residue
self.hdef = hdef
self.nearatoms = []
def setNearatoms(self, allatoms):
"""
Set the nearby atoms to this residue. The only donors/acceptors
that will be changing positions are the flips, with maximum change
of 2.5 A.
Parameters
allatoms: A list of all donors/acceptors (list)
"""
nearatoms = []
resname = self.residue.get("name")
for atom in self.residue.get("atoms"):
if (atom.get("hacceptor") or atom.get("hdonor")):
for nearatom in allatoms:
if nearatom.get("residue") == self.residue: continue
nearres = atom.get("residue")
nearname = nearres.get("name")
dist = distance(atom.getCoords(), nearatom.getCoords())
compdist = HYDROGEN_DIST
if resname in ["HIS","ASN","GLN"]: compdist += 2.5
if nearname in ["HIS","ASN","GLN"]: compdist += 2.5
if dist < compdist and nearatom not in nearatoms:
nearatoms.append(nearatom)
self.nearatoms = nearatoms
class hydrogenRoutines:
"""
The main class of routines in the hydrogen optimization process.
"""
def __init__(self, routines):
"""
Initialize the routines and run the hydrogen optimization
Parameters
routines: The parent routines object (Routines)
"""
self.hdebug = 0
self.routines = routines
self.protein = routines.protein
self.hydrodefs = []
self.groups = []
self.watermap = {}
self.accmap = {}
def debug(self, text):
"""
Print text to stdout for debugging purposes.
Parameters
text: The text to output (string)
"""
if self.hdebug:
print text
def getstates(self, amb):
"""
Get all possible states for a conformation/protonation
ambiguity and store them in a list. Each.
hydrogen type must be explicitly defined.
Parameters
amb : The ambiguity to get the states of (tuple)
Returns
states: A list of states, where each state
is a list of conformations of the atom. (list)
"""
states = []
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
confs = hdef.conformations
# Now make the states
if type == 1: # CTR/ASP/GLU
states.append([()])
states.append([confs[0]]) # H on O1 cis
states.append([confs[1]]) # H on O1 trans
states.append([confs[2]]) # H on O2 cis
states.append([confs[3]]) # H on O2 trans
elif type == 3: # NTR
states.append([()]) # No Hs
states.append([confs[0]]) # H3 only
states.append([confs[1]]) # H2 only
states.append([confs[0], confs[1]]) # H3 and H2
elif type == 4: # HIS
states.append([confs[0]]) # HSD
states.append([confs[1]]) # HSE
states.append([()]) # Negative HIS
states.append([confs[0], confs[1]]) #HSP
elif type == 10: #PNTR
states.append([()])
states.append([confs[0]])
states.append([confs[1]])
states.append([confs[0], confs[1]])
elif type == 13: #GLH
states.append([confs[0]]) # H on O1 cis
states.append([confs[1]]) # H on O1 trans
states.append([confs[2]]) # H on O2 cis
states.append([confs[3]]) # H on O2 trans
return states
def switchstate(self, states, amb, id):
"""
Switch a residue to a new state by first removing all
hydrogens.
Parameters
states: The list of states (list)
amb : The amibiguity to switch (tuple)
id : The state id to switch to (int)
"""
if id > len(states):
raise ValueError, "Invalid State ID!"
# First Remove all Hs
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
for conf in hdef.conformations:
hname = conf.hname
boundname = conf.boundatom
if residue.getAtom(hname) != None:
residue.removeAtom(hname)
residue.getAtom(boundname).hacceptor = 1
residue.getAtom(boundname).hdonor = 0
# Update the IntraBonds
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
residue.updateIntraBonds(defresidue)
# Now build appropriate atoms
state = states[id]
for conf in state:
refcoords = []
defcoords = []
defatomcoords = []
if conf == (): continue # Nothing to add
hname = conf.hname
for atom in conf.atoms:
atomname = atom.get("name")
resatom = residue.getAtom(atomname)
if atomname == hname:
defatomcoords = atom.getCoords()
elif resatom != None:
refcoords.append(resatom.getCoords())
defcoords.append(atom.getCoords())
else:
raise ValueError, "Could not find necessary atom!"
newcoords = findCoordinates(3, refcoords, defcoords, defatomcoords)
boundname = conf.boundatom
residue.createAtom(hname, newcoords, "ATOM")
residue.addDebumpAtom(residue.getAtom(hname))
residue.getAtom(boundname).addIntraBond(hname)
residue.getAtom(boundname).hacceptor = 0
residue.getAtom(boundname).hdonor = 1
def optimizeSingle(self,amb):
"""
Use brute force optimization for a single ambiguity - try all
energy configurations and pick the best.
Parameters
amb: The ambiguity object (tuple)
"""
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
self.debug("Brute Force Optimization for residue %s %i - type %i" %\
(residue.get("name"), residue.get("resSeq"), type))
best = 0
energy = None
bestenergy = 1000.0
# Brute force for fixed states
if type in [1,4,3,10,13]:
if type == 4:
raise ValueError, "We shouldn't have a brute force HIS without the FLIP!"
states = self.getstates(amb)
for i in range(len(states)):
self.switchstate(states, amb, i)
energy = self.getHbondEnergy(amb)
if energy < bestenergy:
bestenergy = energy
best = i
self.switchstate(states, amb, best)
# Brute force for chi angle
elif type in [2]:
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
chinum = hdef.chiangle - 1
for angle in range(-180, 180, 5):
self.routines.setChiangle(residue, chinum, angle, defresidue)
energy = self.getHbondEnergy(amb)
if energy < bestenergy:
bestenergy = energy
best = angle
self.routines.setChiangle(residue, chinum, best, defresidue)
# Brute force for flips
elif type in [11]:
bestenergy = self.getHbondEnergy(amb)
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
chinum = hdef.chiangle - 1
oldangle = residue.get("chiangles")[chinum]
angle = 180.0 + oldangle
self.routines.setChiangle(residue, chinum, angle, defresidue)
energy = self.getHbondEnergy(amb)
if energy >= bestenergy: # switch back!
self.routines.setChiangle(residue, chinum, oldangle, defresidue)
else:
raise ValueError, "Invalid Hydrogen type %i in %s %i!" % \
(type, residue.get("name"), residue.get("resSeq"))
def optimizeHydrogens(self):
"""
Optimize hydrogens according to HYDROGENS.DAT. This
function serves as the main driver for the optimizing
script.
"""
starttime = time()
allatoms = self.findAmbiguities(0)
self.printAmbiguities()
networks = self.findNetworks(HYDROGEN_DIST)
for cluster in networks:
#clusteratoms, compatoms = self.initHbondEnergy(cluster, allatoms)
if len(cluster) == 1:
amb = self.groups[cluster[0]]
residue = getattr(amb, "residue")
amb.setNearatoms(allatoms)
self.optimizeSingle(amb)
else:
# Use Monte Carlo algorithm to optimize
steps = 0
if len(cluster) == 2: steps = 10
elif len(cluster) == 3: steps = 15
elif len(cluster) >= 4 and len(cluster) < 10: steps = pow(2,len(cluster))
if steps > 200 or len(cluster) >= 10: steps = 200
# Initialize
statemap = {}
curmap = {}
bestmap = {}
energy = 0.0
for id in range(len(cluster)):
amb = self.groups[cluster[id]]
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
if type in [1,4,3,10,13]:
states = self.getstates(amb)
statemap[id] = states
self.switchstate(states, amb, 0)
curmap[id] = 0
bestmap[id] = 0
elif type in [2,11]:
chinum = hdef.chiangle - 1
oldangle = residue.get("chiangles")[chinum]
curmap[id] = oldangle
bestmap[id] = oldangle
if getattr(amb,"nearatoms") == []:
amb.setNearatoms(allatoms)
energy += self.getHbondEnergy(amb)
maxenergy = energy + 1000
bestenergy = energy
newenergy = energy
self.debug("Initial Best energy: %.2f" % bestenergy)
self.debug("Initial Cur energy: %.2f" % energy)
self.debug("Initial Max energy: %.2f" % maxenergy)
self.debug("Initial Current map: %s" % curmap)
# Now go through the steps
for step in range(steps):
#self.debug("\n************************")
#self.debug("Current map: %s" % curmap)
#self.debug("Current energy: %.2f" % energy)
#self.debug("Maximum energy: %.2f" % maxenergy)
#self.debug("Trying step %i out of %i" % (step, steps))
id = randint(0, len(cluster) - 1)
amb = self.groups[cluster[id]]
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
states = []
#oldenergy = self.getHbondEnergy(clusteratoms, compatoms, residue)
oldenergy = self.getHbondEnergy(amb)
newstate = None
if type in [1,4,3,10,13]:
states = statemap[id]
newstate = randint(0, len(states) - 1)
while newstate == curmap[id] and type != 3: #Don't waste a step switching to same state
newstate = randint(0, len(states) - 1)
self.switchstate(states, amb, newstate)
elif type in [2]:
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
chinum = hdef.chiangle - 1
newstate = randint(0,71)*5.0 - 180
self.routines.setChiangle(residue, chinum, newstate, defresidue)
elif type in [11]:
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
chinum = hdef.chiangle - 1
oldangle = residue.get("chiangles")[chinum]
newstate = 180.0 + oldangle
self.routines.setChiangle(residue, chinum, newstate, defresidue)
#self.debug("Trying to change amb %i to new state %.2f" % (cluster[id], newstate))
# Evaluate the change
#newenergy = energy - oldenergy + self.getHbondEnergy(clusteratoms, compatoms, residue)
newenergy = energy - oldenergy + self.getHbondEnergy(amb)
ediff = newenergy - energy
rejected = 0
if ediff > 0.0 and ediff < 50.0:
exp = math.exp(-1 * ediff)
if random() >= exp or newenergy > maxenergy:
rejected = 1
elif ediff >= 50.0:
rejected = 1
if rejected == 1: # Switch Back
#self.debug("Rejected!")
if type in [1,4,3,10,13]:
self.switchstate(states, amb, curmap[id])
elif type in [2,11]:
self.routines.setChiangle(residue, chinum, curmap[id], defresidue)
else:
#self.debug("Accepted!")
energy = newenergy
curmap[id] = newstate
if energy < bestenergy:
bestenergy = energy
for cid in range(len(cluster)):
bestmap[cid] = curmap[cid]
# Cool the system
if step > steps/2 and energy < (bestenergy + 5.0):
maxenergy = bestenergy + 5
# Now switch to best energy
self.debug("Final state map: %s" % curmap)
for id in range(len(cluster)):
if bestmap[id] == curmap[id]: continue
amb = self.groups[cluster[id]]
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
type = hdef.type
if type in [1,4,3,10,13]:
newstate = bestmap[id]
states = statemap[id]
self.switchstate(states, amb, newstate)
elif type in [2,11]:
name = residue.get("name")
defresidue = self.routines.aadef.getResidue(name)
chinum = hdef.chiangle - 1
self.routines.setChiangle(residue, chinum, bestmap[id], defresidue)
#finalenergy = self.getHbondEnergy(clusteratoms, compatoms)
self.debug("Final Best energy: %.2f" % bestenergy)
#self.debug("Final Actual energy: %.2f" % finalenergy)
self.debug("Best state map: %s" % bestmap)
self.debug("*******************\n")
self.debug("Total time %.2f" % (time() - starttime))
self.liststates()
def liststates(self):
"""
List the final results of all conformation/protonation
ambiguities to stdout.
"""
for i in range(len(self.groups)):
state = ""
amb = self.groups[i]
residue = getattr(amb,"residue")
hdef = getattr(amb,"hdef")
resname = residue.get("name")
if residue.get("isNterm"):
H2 = residue.getAtom("H2")
H3 = residue.getAtom("H3")
if H2 != None and H3 != None:
state = "Positively charged N-terminus"
elif H2 != None or H3 != None:
state = "Neutral N-terminus"
else:
state = "N TERMINUS ERROR!"
elif residue.get("isCterm") and hdef.name == "CTR":
HO = residue.getAtom("HO")
if HO != None:
state = "Neutral C-Terminus"
else:
state = "Negative C-Terminus"
elif (resname == "HIS" and hdef.name != "HISFLIP") or \
resname in ["HSP","HSE","HSD","HID","HIE","HIP"]:
HD1 = residue.getAtom("HD1")
HE2 = residue.getAtom("HE2")
if HD1 != None and HE2 != None:
state = "Positive HIS"
elif HD1 != None:
state = "HIS HD1"
elif HE2 != None:
state = "HIS HE2"
else:
state = "Negative HIS"
elif resname == "ASP":
HD1 = residue.getAtom("HD1")
HD2 = residue.getAtom("HD2")
if HD1 != None or HD2 != None:
state = "Neutral ASP"
else:
state = "Negative ASP"
elif resname == "GLU":
HE1 = residue.getAtom("HE1")
HE2 = residue.getAtom("HE2")
if HE1 != None or HE2 != None:
state = "Neutral GLU"
else:
state = "Negative GLU"
elif resname == "GLH":
HE1 = residue.getAtom("HE1")
HE2 = residue.getAtom("HE2")
if HE1 != None: state = "Neutral GLU (HE1)"
elif HE2 != None: state = "Neutral GLU (HE2)"
else: raise ValueError, "GLH should always be neutral!"
if state != "":
self.routines.write("Ambiguity #: %i, chain: %s, residue: %i %s - %s\n" \
% (i, residue.chainID, residue.resSeq, residue.name, state),1)
def getHbondEnergy2(self,clusteratoms, compatoms, res=None):
"""
Get the hydrogen bond energy for a cluster of donors
and acceptors. If res is not present, compare each atom
in clusteratoms to all nearby atoms in compatoms. If res is
present, we are trying to find the new energy of the residue
res that has just switched states, and thus need to include
all comparisons where atoms within the residue is an
acceptor.
Parameters
clusteratoms: A list of hydrogen donor/acceptor atoms in
the cluster(list)
compatoms: A list of all hydrogen donor/acceptor
atoms within a given distance of the
cluster (list)
res: (Optional) Residue to get the energy of
(Residue)
Returns
energy: The energy of this hydrogen bond network
(float)
"""
energy = 0.0
if res != None:
for atom2 in compatoms:
res2 = atom2.get("residue")
if res2 != res: continue
elif not atom2.get("hacceptor"): continue
for atom1 in clusteratoms:
if atom1.get("residue") == res2: continue
elif not atom1.get("hdonor"): continue
elif distance(atom1.getCoords(), atom2.getCoords()) < HYDROGEN_DIST:
pair = self.getPairEnergy(atom1, atom2)
energy = energy + pair
#print "\tComparing %s %i to %s %i %.2f" % (atom1.name, atom1.residue.resSeq, atom2.name, atom2.residue.resSeq, pair)
for atom1 in clusteratoms:
energy = energy + self.getPenalty(atom1)
res1 = atom1.get("residue")
if res != None and res1 != res: continue
elif not res1.get("isNterm") and atom1.get("name") == "N": continue
elif not atom1.get("hdonor"): continue
for atom2 in compatoms:
if res1 == atom2.get("residue"): continue
elif not atom2.get("hacceptor"): continue
elif distance(atom1.getCoords(), atom2.getCoords()) < HYDROGEN_DIST:
pair = self.getPairEnergy(atom1, atom2)
energy = energy + pair
#print "\tComparing %s %i to %s %i %.2f" % (atom1.name, atom1.residue.resSeq, atom2.name, atom2.residue.resSeq, pair)
return energy
def getHbondEnergy(self, amb):
"""
"""
energy = 0.0
residue = getattr(amb,"residue")
nearatoms = getattr(amb,"nearatoms")
energy = energy + self.getPenalty(residue)
for nearatom in nearatoms:
for atom in residue.get("atoms"):
if atom.get("hdonor"):
if not nearatom.get("hacceptor"): continue
elif atom.get("name") == "N" and not residue.get("isNterm"): continue
elif nearatom.get("name") == "O" and not nearatom.residue.get("name") == "WAT": continue
if distance(atom.getCoords(), nearatom.getCoords()) < HYDROGEN_DIST:
pair = self.getPairEnergy(atom, nearatom)
energy = energy + pair
if atom.get("hacceptor"):
if not nearatom.get("hdonor"): continue
elif atom.get("name") == "O" and not residue.get("name") == "WAT": continue
elif nearatom.get("name") == "N" and not nearatom.residue.get("isNterm"): continue
if distance(atom.getCoords(), nearatom.getCoords()) < HYDROGEN_DIST:
pair = self.getPairEnergy(nearatom, atom)
energy = energy + pair
return energy
def getPairEnergy(self, donor, acceptor):
"""
Get the energy between two atoms
Parameters
donor: The first atom in the pair (Atom)
acceptor: The second atom in the pair (Atom)
Returns
energy: The energy of the pair (float)
"""
max_hbond_energy = -10.0
max_ele_energy = -1.0
maxangle = 20.0
max_dha_dist = 3.3
max_ele_dist = 5.0
energy = 0.0
donorh = None
acceptorh = None
donorhs = []
acceptorhs = []
if not (donor.get("hdonor") and acceptor.get("hacceptor")):
return energy
# See if hydrogens are presently bonded to the acceptor and donor
for bond in donor.get("intrabonds"):
if bond[0] == "H":
donorhs.append(bond)
for bond in acceptor.get("intrabonds"):
if bond[0] == "H":
acceptorhs.append(bond)
if donorhs == []: return energy
# Case 1: Both donor and acceptor hydrogens are present
if acceptorhs != []:
for donorh in donorhs:
for acceptorh in acceptorhs:
donorhatom = donor.get("residue").getAtom(donorh)
acceptorhatom = acceptor.get("residue").getAtom(acceptorh)
if donorhatom == None or acceptorhatom == None:
text = "Couldn't find bonded hydrogen even though "
text = text + "it is present in intrabonds!"
raise ValueError, text
dist = distance(donorhatom.getCoords(), acceptor.getCoords())
if dist > max_dha_dist and dist < max_ele_dist: # Are the Hs too far?
energy += max_ele_energy/(dist*dist)
continue
hdist = distance(donorhatom.getCoords(), acceptorhatom.getCoords())
if hdist < 1.5: # Are the Hs too close?
energy += -1 * max_hbond_energy
continue
angle1 = self.getHbondangle(acceptor, donor, donorhatom)
if angle1 <= maxangle:
angleterm = (maxangle - angle1)/maxangle
angle2 = self.getHbondangle(donorhatom, acceptorhatom, acceptor)
if angle2 < 110.0: angle2 = 1.0
else: angle2=-1.0/110.0*(angle2-110.0)
energy+=max_hbond_energy/pow(dist,3)*angleterm*angle2
return energy
# Case 2: Only the donor hydrogen is present
elif acceptorhs == []:
for donorh in donorhs:
donorhatom = donor.get("residue").getAtom(donorh)
if donorhatom == None:
text = "Couldn't find bonded hydrogen even though "
text = text + "it is present in intrabonds!"
raise ValueError, text
dist = distance(donorhatom.getCoords(), acceptor.getCoords())
if dist > max_dha_dist and dist < max_ele_dist: # Or too far?
energy += max_ele_energy/(dist*dist)
continue
angle1 = self.getHbondangle(acceptor, donor, donorhatom)
if angle1 <= maxangle:
angleterm = (maxangle - angle1)/maxangle
energy += max_hbond_energy/pow(dist,2)*angleterm
return energy
def getHbondangle(self, atom1, atom2, atom3):
"""
Get the angle between three atoms
Parameters
atom1: The first atom (atom)
atom2: The second (vertex) atom (atom)
atom3: The third atom (atom)
Returns
angle: The angle between the atoms (float)
"""
angle = 0.0
atom2Coords = atom2.getCoords()
coords1 = subtract(atom3.getCoords(), atom2Coords)
coords2 = subtract(atom1.getCoords(), atom2Coords)
norm1 = normalize(coords1)
norm2 = normalize(coords2)
dotted = dot(norm1, norm2)
if dotted > 1.0: # If normalized, this is due to rounding error
dotted = 1.0
rad = abs(acos(dotted))
angle = rad*180.0/pi
if angle > 180.0:
angle = 360.0 - angle
return angle
def getPenalty(self, residue):
"""
Add penalties for unusual protonation states.
Parameters
atom: The residue to examine (Atom)
Returns
penalty: The amount of the penalty (float)
"""
acidpenalty = 25.0
hispos = 0.1
hisminus = 10.0
nterm = 5.0
penalty = 0.0
resname = residue.get("name")
if residue.get("isNterm"):
charge = 1
if residue.getAtom("H2") == None: charge = charge - 1
if residue.getAtom("H3") == None: charge = charge - 1
penalty = penalty + (1- charge)*nterm
if resname == "HIS":
hd1 = residue.getAtom("HD1")
he2 = residue.getAtom("HE2")
if hd1 == None and he2 == None:
penalty = penalty + hisminus
elif hd1 != None and he2 != None:
penalty = penalty + hispos
if resname != "WAT":
for atom in residue.get("atoms"):
atomname = atom.get("name")
if atomname in ["OD1","OD2","OE1","OE2","O","OXT"] and atom.get("hdonor"):
penalty = penalty + acidpenalty
break
return penalty
def initHbondEnergy(self, cluster, allatoms):
"""
Create a list of hydrogen donors/acceptors within this cluster
and another list of donors/acceptors throughout the
entire protein.
Parameters
cluster: A list of group ids that are networked (list)
Returns
clusteratoms: A list of hydrogen donor/acceptor atoms in
the cluster (list)
"""
clusteratoms = []
compatoms = []
for id in cluster:
residue = self.groups[id][0]
for atom in residue.get("atoms"):
if (atom.get("hacceptor") or atom.get("hdonor")) \
and atom not in clusteratoms:
clusteratoms.append(atom)
for atom2 in allatoms:
dist = distance(atom.getCoords(), atom2.getCoords())
if dist < HYDROGEN_DIST and atom2 not in compatoms:
compatoms.append(atom2)
return clusteratoms, compatoms
def findNetworks(self,limit):
"""
Find hydrogen networks that should be optimized together.
Parameters
limit: The limit to see how close two boundatoms are
Returns
networks: A list of group ID networks (list)
"""
map = {}
networks = []
done = []
groups = self.groups
for i in range(len(groups)):
amb1 = groups[i]
residue1 = getattr(amb1, "residue")
hydrodef1 = getattr(amb1,"hdef")
for conf1 in hydrodef1.conformations:
boundatom1 = residue1.getAtom(conf1.boundatom)
for j in range(i+1, len(groups)):
amb2 = groups[j]
residue2 = getattr(amb2, "residue")
hydrodef2 = getattr(amb2,"hdef")
for conf2 in hydrodef2.conformations:
boundatom2 = residue2.getAtom(conf2.boundatom)
if distance(boundatom1.getCoords(), boundatom2.getCoords()) < limit:
if i not in map:
map[i] = [j]
elif j not in map[i]:
map[i].append(j)
break
for i in range(len(groups)):
if i in map and i not in done:
list = analyzeMap(map,i,[])
for item in list:
done.append(item)
networks.append(list)
elif i not in map and i not in done:
networks.append([i])
self.debug(networks)
return networks
def randomizeWaters(self):
"""
Randomize the waters found in a protein. Mimics the
optimizeWaters function, but instead of going through
all possible 5 degree increments, simply choose a random
angle.
"""
allatoms = self.findAmbiguities(1)
closeatoms = {}
overallenergy = 0.0
# Step 1: Get list of water residues
waters = []
for group in self.groups:
residue = getattr(group,"residue")
waters.append(residue)
# Step 2: Shuffle waters
shuffle(waters)
# Step 3: Satisfy all protein donors
for residue in waters:
self.watermap[residue] = None
closeatoms[residue] = []
bestdon = None
bestdondist = 999.99
bestnh = None
oxygen = residue.getAtom("O")
for atom in allatoms:
closedist = distance(oxygen.getCoords(), atom.getCoords())
if oxygen != atom and closedist < WATER_DIST: closeatoms[residue].append(atom)
if atom.get("residue").name == "WAT": continue
if atom.get("hdonor"):
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = atom.get("residue").getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
angle = self.getHbondangle(atom, oxygen, bondatom)
if dist < bestdondist and angle <= 20.0 :
bestdon = bondatom
bestdondist = dist
elif atom.get("name")[0:2] == "NH":
arg = atom.get("residue")
if atom.get("name") == "NH1": other = "NH2"
else: other = "NH1"
if arg.getAtom(other).get("hdonor") != 1:
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = arg.getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
angle = self.getHbondangle(atom, oxygen, bondatom)
if dist < bestdondist and angle <= 20.0:
bestdon = bondatom
bestdondist = dist
bestnh = atom
if bestnh != None:
if bestdon.get("name") in bestnh.get("intrabonds"):
bestnh.set("hdonor",1)
bestnh.set("hacceptor",0)
if bestdondist < 3.3:
#print "Optimizing WAT %i" % residue.resSeq
#print "\tBest Donor: ", bestdon.residue.name, bestdon.residue.resSeq, bestdon.name, bestdondist
R = bestdondist
refcoords, defcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([0,0,.3333+R]) # Donor
refcoords.append(oxygen.getCoords())
refcoords.append(bestdon.getCoords())
defatomcoords = [.9428,0,0] # Location 1
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defatomcoords = [-.4714,.8165,0] # Location 2
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",newcoords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = bestdon
# Now randomize
randangle = randint(0,71)*5.0 - 180
self.setWaterHydrogens(residue, randangle)
else: closeatoms[residue] = []
# Step 4: Place and orient hydrogens
for residue in waters:
#print "Optimizing WAT %i" % residue.resSeq
oxygen = residue.getAtom("O")
if self.watermap[residue] != None: continue
bestdon = None
bestacc = None
bestdondist = 999.99
bestaccdist = 999.99
for atom in allatoms:
if atom == oxygen: continue
closedist = distance(oxygen.getCoords(), atom.getCoords())
if closedist < WATER_DIST: closeatoms[residue].append(atom)
if atom.get("hacceptor"):
dist = closedist
if dist < bestaccdist:
bestacc = atom
bestaccdist = dist
if atom.get("hdonor"):
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = atom.get("residue").getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
if dist < bestdondist:
bestdon = bondatom
bestdondist = dist
#print "\tBest Donor: ", bestdon.residue.name, bestdon.residue.resSeq, bestdon.name, bestdondist
#print "\tBest Acc: ", bestacc.residue.name, bestacc.residue.resSeq, bestacc.name, bestaccdist
if bestdondist < bestaccdist: # Donor is closest
R = bestdondist
refcoords, defcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([0,0,.3333+R]) # Donor
refcoords.append(oxygen.getCoords())
refcoords.append(bestdon.getCoords())
defatomcoords = [.9428,0,0] # Location 1
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defatomcoords = [-.4714,.8165,0] # Location 2
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",newcoords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = bestdon
else: # Acceptor is closest
b = 1.0 # Oxygen (Donor) - H1 dist
r = 1.5 # Acceptor - H1 dist
if bestaccdist >= (b + r):
# Then H1 is perfectly placed on the vector
vec = subtract(bestacc.getCoords(), oxygen.getCoords())
x = oxygen.get("x") + b/bestaccdist * vec[0]
y = oxygen.get("y") + b/bestaccdist * vec[1]
z = oxygen.get("z") + b/bestaccdist * vec[2]
newcoords = [x,y,z]
residue.createAtom("H1",newcoords,"HETATM")
else:
# Minimize the H-O-A angle
defcoords, refcoords = [], []
R = distance(oxygen.getCoords(), bestacc.getCoords())
psi = acos((b*b + R*R - r*r)/(2*b*R))
defcoords.append([0,0,0])
refcoords.append(oxygen.getCoords())
defcoords.append([R,0,0])
refcoords.append(bestacc.getCoords())
y = random()
while y > sin(psi):
y = y/2
z = sqrt(sin(psi)*sin(psi) - y*y)
defatomcoords = [cos(psi), y, z]
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defcoords, refcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([.9428,0,0]) # H1
refcoords.append(oxygen.getCoords())
refcoords.append(newcoords)
defatomcoords = [-.4714,.8165,0] # Location 2
h2coords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",h2coords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = residue.getAtom("H1")
# Now randomize
randangle = randint(0,71)*5.0 - 180
self.setWaterHydrogens(residue, randangle)
def setWaterHydrogens(self, residue, newangle):
"""
Optimize a Water molecule
Parameters
residue: The water residue
newangle: The new chi angle (float)
"""
movenames = []
movecoords = []
hydrogen = self.watermap[residue]
oxygen = residue.getAtom("O")
initcoords = subtract(oxygen.getCoords(), hydrogen.getCoords())
# Determine which atoms to rotate
if hydrogen not in residue.get("atoms"):
movenames = ["H1","H2"]
elif hydrogen.get("name") == "H1":
movenames = ["H2"]
else:
raise ValueError, "Got improperly mapped water hydrogen!"
for name in movenames:
atom = residue.getAtom(name)
movecoords.append(subtract(atom.getCoords(), hydrogen.getCoords()))
newcoords = qchichange(initcoords, movecoords, newangle)
for i in range(len(movenames)):
name = movenames[i]
atom = residue.getAtom(name)
self.routines.removeCell(atom)
x = (newcoords[i][0] + hydrogen.get("x"))
y = (newcoords[i][1] + hydrogen.get("y"))
z = (newcoords[i][2] + hydrogen.get("z"))
atom.set("x", x)
atom.set("y", y)
atom.set("z", z)
self.routines.addCell(atom)
def optimizeWaters(self):
"""
Optimize the waters found in a protein
"""
allatoms = self.findAmbiguities(1)
closeatoms = {}
overallenergy = 0.0
# Step 1: Get list of water residues
waters = []
for group in self.groups:
residue = getattr(group,"residue")
waters.append(residue)
# Step 2: Shuffle waters
shuffle(waters)
# Step 3: Satisfy all protein donors
for residue in waters:
self.watermap[residue] = None
closeatoms[residue] = []
bestdon = None
bestdondist = 999.99
bestnh = None
oxygen = residue.getAtom("O")
for atom in allatoms:
closedist = distance(oxygen.getCoords(), atom.getCoords())
if oxygen != atom and closedist < WATER_DIST: closeatoms[residue].append(atom)
if atom.get("residue").name == "WAT": continue
if atom.get("hdonor"):
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = atom.get("residue").getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
angle = self.getHbondangle(atom, oxygen, bondatom)
if dist < bestdondist and angle <= 20.0 :
bestdon = bondatom
bestdondist = dist
elif atom.get("name")[0:2] == "NH":
arg = atom.get("residue")
if atom.get("name") == "NH1": other = "NH2"
else: other = "NH1"
if arg.getAtom(other).get("hdonor") != 1:
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = arg.getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
angle = self.getHbondangle(atom, oxygen, bondatom)
if dist < bestdondist and angle <= 20.0:
bestdon = bondatom
bestdondist = dist
bestnh = atom
if bestnh != None:
if bestdon.get("name") in bestnh.get("intrabonds"):
bestnh.set("hdonor",1)
bestnh.set("hacceptor",0)
if bestdondist < 3.3:
#print "Optimizing WAT %i" % residue.resSeq
#print "\tBest Donor: ", bestdon.residue.name, bestdon.residue.resSeq, bestdon.name, bestdondist
R = bestdondist
refcoords, defcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([0,0,.3333+R]) # Donor
refcoords.append(oxygen.getCoords())
refcoords.append(bestdon.getCoords())
defatomcoords = [.9428,0,0] # Location 1 on tetrahedral
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defatomcoords = [-.4714,.8165,0] # Location 2 on tetrahedral
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",newcoords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = bestdon
# Now optimize
amb = hydrogenAmbiguity(residue,None)
setattr(amb,"nearatoms",closeatoms[residue])
#energy = self.getHbondEnergy([oxygen], closeatoms[residue])
energy = self.getHbondEnergy(amb)
bestangle = None
bestenergy = energy
for angle in range(-180,180,5):
self.setWaterHydrogens(residue, angle)
#energy = self.getHbondEnergy([oxygen], closeatoms[residue])
energy = self.getHbondEnergy(amb)
if energy < bestenergy:
bestenergy = energy
bestangle = angle
if bestangle == None:
bestangle = randint(0,71)*5.0 - 180
self.setWaterHydrogens(residue, bestangle)
overallenergy += bestenergy
else: closeatoms[residue] = []
# Step 4: Place and orient hydrogens
for residue in waters:
#print "Optimizing WAT %i" % residue.resSeq
oxygen = residue.getAtom("O")
if self.watermap[residue] != None: continue
bestdon = None
bestacc = None
bestdondist = 999.99
bestaccdist = 999.99
for atom in allatoms:
if atom == oxygen: continue
closedist = distance(oxygen.getCoords(), atom.getCoords())
if closedist < WATER_DIST: closeatoms[residue].append(atom)
if atom.get("hacceptor"):
dist = closedist
if dist < bestaccdist:
bestacc = atom
bestaccdist = dist
if atom.get("hdonor"):
for bond in atom.get("intrabonds"):
if bond[0] != "H": continue
bondatom = atom.get("residue").getAtom(bond)
dist = distance(oxygen.getCoords(), bondatom.getCoords())
if dist < bestdondist:
bestdon = bondatom
bestdondist = dist
#print "\tBest Donor: ", bestdon.residue.name, bestdon.residue.resSeq, bestdon.name, bestdondist
#print "\tBest Acc: ", bestacc.residue.name, bestacc.residue.resSeq, bestacc.name, bestaccdist
if bestdondist < bestaccdist: # Donor is closest
R = bestdondist
refcoords, defcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([0,0,.3333+R]) # Donor
refcoords.append(oxygen.getCoords())
refcoords.append(bestdon.getCoords())
defatomcoords = [.9428,0,0] # Location 1 on tetrahedral
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defatomcoords = [-.4714,.8165,0] # Location 2 on tetrahedral
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",newcoords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = bestdon
else: # Acceptor is closest
b = 1.0 # Oxygen (Donor) - H1 dist
r = 1.5 # Acceptor - H1 dist
if bestaccdist >= (b + r):
# Then H1 is perfectly placed on the vector
vec = subtract(bestacc.getCoords(), oxygen.getCoords())
x = oxygen.get("x") + b/bestaccdist * vec[0]
y = oxygen.get("y") + b/bestaccdist * vec[1]
z = oxygen.get("z") + b/bestaccdist * vec[2]
newcoords = [x,y,z]
residue.createAtom("H1",newcoords,"HETATM")
else:
# Minimize the H-O-A angle
defcoords, refcoords = [], []
R = distance(oxygen.getCoords(), bestacc.getCoords())
psi = acos((b*b + R*R - r*r)/(2*b*R))
defcoords.append([0,0,0])
refcoords.append(oxygen.getCoords())
defcoords.append([R,0,0])
refcoords.append(bestacc.getCoords())
y = random()
while y > sin(psi):
y = y/2
z = sqrt(sin(psi)*sin(psi) - y*y)
defatomcoords = [cos(psi), y, z]
newcoords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H1",newcoords,"HETATM")
defcoords, refcoords = [], []
defcoords.append([0,0,.3333]) # Oxygen
defcoords.append([.9428,0,0]) # H1
refcoords.append(oxygen.getCoords())
refcoords.append(newcoords)
defatomcoords = [-.4714,.8165,0] # Location 2
h2coords = findCoordinates(2, refcoords, defcoords, defatomcoords)
residue.createAtom("H2",h2coords,"HETATM")
oxygen.intrabonds = ["H1","H2"]
self.watermap[residue] = residue.getAtom("H1")
# Now optimize
amb = hydrogenAmbiguity(residue,None)
setattr(amb,"nearatoms",closeatoms[residue])
energy = self.getHbondEnergy(amb)
#energy = self.getHbondEnergy([oxygen], closeatoms[residue])
bestangle = None
bestenergy = energy
for angle in range(-180,180,5):
self.setWaterHydrogens(residue, angle)
energy = self.getHbondEnergy(amb)
#energy = self.getHbondEnergy([oxygen], closeatoms[residue])
if energy < bestenergy:
bestenergy = energy
bestangle = angle
if bestangle == None:
bestangle = randint(0,71)*5.0 - 180
self.setWaterHydrogens(residue, bestangle)
overallenergy += bestenergy
#print "Overall energy: %.2f" % overallenergy
def findViableAngles(self, residue, nearatoms):
"""
Find the viable angles that a water molecule can be rotated to.
If there are no donor/acceptor atoms within
Parameters
residue: The water residue to examine
nearatoms: A list of nearby donor/acceptors
Returns
angle: A list of viable angles
"""
angles = []
bestmap = {} # Store best values by tuple (nearatom, hydrogen)
hydrogen = self.watermap[residue]
if hydrogen not in residue.get("atoms"):
moveatoms = [residue.getAtom("H1"),residue.getAtom("H2")]
elif hydrogen.get("name") == "H1":
moveatoms = [residue.getAtom("H2")]
for atom in nearatoms:
for moveableatom in moveatoms:
bestmap[(atom, moveableatom)] = (999.99, None)
for angle in range(-180,180,5):
self.optimizeWaterHydrogens(residue, angle)
for atom in nearatoms:
for moveableatom in moveatoms:
dist = distance(moveableatom.getCoords(), atom.getCoords())
bestdist = bestmap[(atom, moveableatom)][0]
if dist < bestdist:
bestmap[(atom, moveableatom)] = (dist, angle)
for atom in nearatoms:
for moveableatom in moveatoms:
angle = bestmap[(atom,moveableatom)][1]
if angle not in angles: angles.append(angle)
return angles
def findAmbiguities(self, water):
"""
Find the amibiguities within a protein according to the
DAT file, and set all boundatoms to their hydrogen donor/
acceptor state. Store the ambiguities as (residue, hydrodef)
tuples in self.groups.
Returns
allatoms: A list of all donors and acceptors in the
protein (list)
water: If 1, only put waters in groups, but fill allatoms
appropriately
"""
allatoms = []
hydrodefs = self.hydrodefs
for chain in self.protein.getChains():
for residue in chain.get("residues"):
resname = residue.get("name")
nter = residue.get("isNterm")
cter = residue.get("isCterm")
type = residue.get("type")
if type == 2: continue
for group in hydrodefs:
groupname = group.name
htype = group.type
if resname == groupname or \
(groupname == "APR") or \
(groupname == "APP" and resname != "PRO") or \
(groupname.endswith("FLIP") and resname == groupname[0:3]) or \
(groupname == "HISFLIP" and resname in ["HIP","HID","HIE","HSP","HSE","HSD"]) or \
(groupname == "NTR" and nter and resname != "PRO") or \
(groupname == "PNTR" and nter and resname == "PRO") or \
(groupname == "CTR" and cter):
if group.method != 0:
if not water and type == 1:
amb = hydrogenAmbiguity(residue, group)
self.groups.append(amb)
if water and type == 3:
amb = hydrogenAmbiguity(residue, group)
self.groups.append(amb)
for conf in group.conformations:
boundatom = conf.boundatom
atom = residue.getAtom(boundatom)
if atom != None:
atom.set("hacceptor",HACCEPTOR[htype])
atom.set("hdonor",HDONOR[htype])
if atom not in allatoms:
allatoms.append(atom)
return allatoms
def printAmbiguities(self):
"""
Print the list of ambiguities to stdout
"""
if self.hdebug == 0: return
i = 0
for amb in self.groups:
residue = getattr(amb,"residue")
hydrodef = getattr(amb,"hdef")
conf = hydrodef.conformations[0]
self.routines.write("Ambiguity #: %i, chain: %s, residue: %i %s, hyd_type: %i state: %i Grp_name: %s Hname: %s Boundatom: %s\n" % (i, residue.chainID, residue.resSeq, residue.name, hydrodef.type, hydrodef.standardconf, hydrodef.name, conf.hname, conf.boundatom))
i += 1
def parseHydrogen(self, lines):
"""
Parse a list of lines in order to make a hydrogen
definition
Parameters
lines: The lines to parse (list)
Returns
mydef: The hydrogen definition object (HydrogenDefinition)
"""
maininfo = string.split(lines[0])
name = maininfo[0]
group = maininfo[1]
numhydrogens = int(maininfo[2])
standardconf = int(maininfo[4])
type = int(maininfo[5])
chiangle = int(maininfo[6])
method = int(maininfo[7])
mydef = HydrogenDefinition(name, group, numhydrogens, standardconf, \
type, chiangle, method)
conf = []
for newline in lines[1:]:
if newline.startswith(">"):
if conf == []: continue
confinfo = string.split(conf[0])
hname = confinfo[0]
boundatom = confinfo[1]
bondlength = float(confinfo[2])
myconf = HydrogenConformation(hname, boundatom, bondlength)
count = 0
for line in conf[1:]:
textatom = string.split(line)
name = textatom[0]
x = float(textatom[1])
y = float(textatom[2])
z = float(textatom[3])
atom = DefinitionAtom(count, name, "", x,y,z)
myconf.addAtom(atom)
mydef.addConf(myconf)
conf = []
else:
conf.append(newline)
if conf != []:
confinfo = string.split(conf[0])
hname = confinfo[0]
boundatom = confinfo[1]
bondlength = float(confinfo[2])
myconf = HydrogenConformation(hname, boundatom, bondlength)
count = 0
for line in conf[1:]:
textatom = string.split(line)
name = textatom[0]
x = float(textatom[1])
y = float(textatom[2])
z = float(textatom[3])
atom = DefinitionAtom(count, name, "", x,y,z)
myconf.addAtom(atom)
mydef.addConf(myconf)
if lines[1:] == []: # FLIPS
myconf = HydrogenConformation(None, "CA", 0.0)
mydef.addConf(myconf)
return mydef
def readHydrogenDefinition(self):
"""
Read the Hydrogen Definition file
Returns
hydrodef: The hydrogen definition ()
"""
defpath = HYDROGENFILE
if not os.path.isfile(defpath):
for path in sys.path:
testpath = "%s/%s" % (path, defpath)
if os.path.isfile(testpath):
defpath = testpath
break
if not os.path.isfile(defpath):
raise ValueError, "%s not found!" % defpath
file = open(defpath)
lines = file.readlines()
file.close()
info = []
for line in lines:
if line.startswith("//"): pass
elif line.startswith("*") or line.startswith("!"):
if info == []: continue
mydef = self.parseHydrogen(info)
self.hydrodefs.append(mydef)
info = []
else:
info.append(string.strip(line))
class HydrogenDefinition:
"""
HydrogenDefinition class
The HydrogenDefinition class provides information on possible
ambiguities in amino acid hydrogens. It is essentially the hydrogen
definition file in object form.
"""
def __init__(self, name, group, numhydrogens, standardconf, type, \
chiangle, method):
"""
Initialize the object with information from the definition file
Parameters:
name: The name of the grouping (string)
group: The group of the definition
(acid/base/none, string)
numhydrogens: The number of hydrogens that can be added (int)
standardconf: The number of standard conformations (int)
type : Type of Hydrogen (int)
chiangle : The chiangle to be changed (int)
method : The standard optimization method (int)
See HYDROGENS.DAT for more information
"""
self.name = name
self.group = group
self.numhydrogens = numhydrogens
self.standardconf = standardconf
self.type = type
self.chiangle = chiangle
self.method = method
self.conformations = []
def __str__(self):
"""
Used for debugging purposes
Returns
output: The information about this definition (string)
"""
output = "Name: %s\n" % self.name
output += "Group: %s\n" % self.group
output += "# of Hydrogens: %i\n" % self.numhydrogens
output += "# of Conformations: %i\n" % len(self.conformations)
output += "Standard Conformation: %i\n" % self.standardconf
output += "Type of Hydrogen: %i\n" % self.type
output += "Chiangle to change: %i\n" % self.chiangle
output += "Optimization method: %i\n" % self.method
output += "Conformations:\n"
for conf in self.conformations:
output += "\n%s" % conf
output += "*****************************************\n"
return output
def addConf(self, conf):
"""
Add a HydrogenConformation to the list of conformations
Parameters
conf: The conformation to be added (HydrogenConformation)
"""
self.conformations.append(conf)
class HydrogenConformation:
"""
HydrogenConformation class
The HydrogenConformation class contains data about possible
hydrogen conformations as specified in the hydrogen data file.
"""
def __init__(self, hname, boundatom, bondlength):
"""
Initialize the object
Parameters
hname : The hydrogen name (string)
boundatom : The atom the hydrogen is bound to (string)
bondlength : The bond length (float)
"""
self.hname = hname
self.boundatom = boundatom
self.bondlength = bondlength
self.atoms = []
def __str__(self):
"""
Used for debugging purposes
Returns
output: Information about this conformation (string)
"""
output = "Hydrogen Name: %s\n" % self.hname
output += "Bound Atom: %s\n" % self.boundatom
output += "Bond Length: %.2f\n" % self.bondlength
for atom in self.atoms:
output += "\t%s\n" % atom
return output
def addAtom(self, atom):
"""
Add an atom to the list of atoms
Parameters
atom: The atom to be added (DefinitionAtom)
"""
self.atoms.append(atom)
```
#### File: pdb2pqr/src/aa.py
```python
__date__ = "28 December 2006"
__author__ = "<NAME>"
import string
from structures import *
class Amino(Residue):
"""
Amino class
This class provides standard features of the amino acids listed
below
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
ref: The reference object for the amino acid. Used to
convert from the alternate naming scheme to the
main naming scheme.
"""
def __init__(self, atoms, ref):
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.ffname = self.name
self.map = {}
self.dihedrals = []
self.patches = []
self.peptideC = None
self.peptideN = None
self.isNterm = 0
self.isCterm = 0
self.is5term = 0
self.is3term = 0
self.missing = []
self.reference = ref
self.fixed = 0
# Create each atom
for a in atoms:
if a.name in ref.altnames: # Rename atoms
a.name = ref.altnames[a.name]
if a.name not in self.map:
atom = Atom(a, "ATOM", self)
self.addAtom(atom)
def createAtom(self, atomname, newcoords):
"""
Create an atom. Override the generic residue's version of
createAtom().
Parameters
atomname: The name of the atom (string)
newcoords: The coordinates of the atom (list).
"""
oldatom = self.atoms[0]
newatom = Atom(oldatom, "ATOM", self)
newatom.set("x",newcoords[0])
newatom.set("y",newcoords[1])
newatom.set("z",newcoords[2])
newatom.set("name", atomname)
newatom.set("occupancy",1.00)
newatom.set("tempFactor",0.00)
newatom.added = 1
self.addAtom(newatom)
def addAtom(self, atom):
"""
Override the existing addAtom - include the link to the
reference object
"""
self.atoms.append(atom)
atomname = atom.get("name")
self.map[atomname] = atom
try:
atom.reference = self.reference.map[atomname]
for bond in atom.reference.bonds:
if self.hasAtom(bond):
bondatom = self.map[bond]
if bondatom not in atom.bonds: atom.bonds.append(bondatom)
if atom not in bondatom.bonds: bondatom.bonds.append(atom)
except KeyError:
atom.reference = None
def addDihedralAngle(self, value):
"""
Add the value to the list of chiangles
Parameters
value: The value to be added (float)
"""
self.dihedrals.append(value)
def setState(self):
"""
Set the name to use for the forcefield based on the current
state. Uses N* and C* for termini.
"""
if self.isNterm:
if "NEUTRAL-NTERM" in self.patches:
self.ffname = "NEUTRAL-N%s" % self.ffname
else:
self.ffname = "N%s" % self.ffname
elif self.isCterm:
if "NEUTRAL-CTERM" in self.patches:
self.ffname = "NEUTRAL-C%s" % self.ffname
else:
self.ffname = "C%s" % self.ffname
return
class ALA(Amino):
"""
Alanine class
This class gives data about the Alanine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class ARG(Amino):
"""
Arginine class
This class gives data about the Arginine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class ASN(Amino):
"""
Asparagine class
This class gives data about the Asparagine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class ASP(Amino):
"""
Aspartic Acid class
This class gives data about the Aspartic Acid object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
Set the name to use for the forcefield based on the current
state.
"""
if "ASH" in self.patches or self.name == "ASH": self.ffname = "ASH"
Amino.setState(self)
class CYS(Amino):
"""
Cysteine class
This class gives data about the Cysteine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
self.SSbonded = 0
self.SSbondedpartner = None
def setState(self):
"""
Set the state of the CYS object. If SS-bonded, use CYX. If
negatively charged, use CYM. If HG is not present, use CYX.
"""
if "CYX" in self.patches or self.name == "CYX": self.ffname = "CYX"
elif self.SSbonded: self.ffname = "CYX"
elif "CYM" in self.patches or self.name == "CYM": self.ffname = "CYM"
elif not self.hasAtom("HG"): self.ffname = "CYX"
Amino.setState(self)
class GLN(Amino):
"""
Glutamine class
This class gives data about the Glutamine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class GLU(Amino):
"""
Glutamic Acid class
This class gives data about the Glutamic Acid object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
Set the name to use for the forcefield based on the current
state.
"""
if "GLH" in self.patches or self.name == "GLH": self.ffname = "GLH"
Amino.setState(self)
class GLY(Amino):
"""
Glycine class
This class gives data about the Glycine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class HIS(Amino):
"""
Histidine class
This class gives data about the Histidine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
Histidines are a special case due to the presence of
several different forms. This function sets all non-
positive incarnations of HIS to neutral HIS by
checking to see if optimization removed hacceptor or
hdonor flags. Otherwise HID is used as the default.
"""
if "HIP" not in self.patches and self.name not in ["HIP", "HSP"]:
if self.getAtom("ND1").hdonor and not \
self.getAtom("ND1").hacceptor:
if self.hasAtom("HE2"): self.removeAtom("HE2")
elif self.getAtom("NE2").hdonor and not \
self.getAtom("NE2").hacceptor:
if self.hasAtom("HD1"): self.removeAtom("HD1")
else: # Default to HID
if self.hasAtom("HE2"): self.removeAtom("HE2")
if self.hasAtom("HD1") and self.hasAtom("HE2"): self.ffname = "HIP"
elif self.hasAtom("HD1"): self.ffname = "HID"
elif self.hasAtom("HE2"): self.ffname = "HIE"
else:
raise ValueError, "Invalid type for %s!" % str(self)
Amino.setState(self)
class ILE(Amino):
"""
Isoleucine class
This class gives data about the Isoleucine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class LEU(Amino):
"""
Leucine class
This class gives data about the Leucine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class LYS(Amino):
"""
Lysine class
This class gives data about the Lysine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
Determine if this is LYN or not
"""
if "LYN" in self.patches or self.name == "LYN": self.ffname = "LYN"
Amino.setState(self)
class MET(Amino):
"""
Methionine class
This class gives data about the Methionine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class PHE(Amino):
"""
Phenylalanine class
This class gives data about the Phenylalanine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class PRO(Amino):
"""
Proline class
This class gives data about the Proline object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
Set the name to use for the forcefield based on the current
state. Uses N* and C* for termini.
"""
if self.isNterm:
self.ffname = "N%s" % self.ffname
elif self.isCterm:
if "NEUTRAL-CTERM" in self.patches:
self.ffname = "NEUTRAL-C%s" % self.ffname
else:
self.ffname = "C%s" % self.ffname
class SER(Amino):
"""
Serine class
This class gives data about the Serine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class THR(Amino):
"""
Threonine class
This class gives data about the Threonine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class TRP(Amino):
"""
Tryptophan class
This class gives data about the Tryptophan object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class TYR(Amino):
"""
Tyrosine class
This class gives data about the Tyrosine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
def setState(self):
"""
See if the TYR is negative or not
"""
if "TYM" in self.patches or self.name == "TYM": self.ffname = "TYM"
Amino.setState(self)
class VAL(Amino):
"""
Valine class
This class gives data about the Valine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
Amino.__init__(self, atoms, ref)
self.reference = ref
class WAT(Residue):
"""
Water class
This class gives data about the Water object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.fixed = 0
self.ffname = "WAT"
self.map = {}
self.reference = ref
# Create each atom
for a in atoms:
if a.name in ref.altnames: # Rename atoms
a.name = ref.altnames[a.name]
atom = Atom(a, "HETATM", self)
atomname = atom.get("name")
if atomname not in self.map:
self.addAtom(atom)
else: # Don't add duplicate atom with altLoc field
oldatom = self.getAtom(atomname)
oldatom.set("altLoc","")
def createAtom(self, atomname, newcoords):
"""
Create a water atom. Note the HETATM field.
Parameters
atomname: The name of the atom (string)
newcoords: The new coordinates of the atom (list)
"""
oldatom = self.atoms[0]
newatom = Atom(oldatom, "HETATM", self)
newatom.set("x",newcoords[0])
newatom.set("y",newcoords[1])
newatom.set("z",newcoords[2])
newatom.set("name", atomname)
newatom.set("occupancy",1.00)
newatom.set("tempFactor",0.00)
newatom.added = 1
self.addAtom(newatom)
def addAtom(self, atom):
"""
Override the existing addAtom - include the link to the
reference object
"""
self.atoms.append(atom)
atomname = atom.get("name")
self.map[atomname] = atom
try:
atom.reference = self.reference.map[atomname]
for bond in atom.reference.bonds:
if self.hasAtom(bond):
bondatom = self.map[bond]
if bondatom not in atom.bonds: atom.bonds.append(bondatom)
if atom not in bondatom.bonds: bondatom.bonds.append(atom)
except KeyError:
atom.reference = None
class LIG(Residue):
"""
Generic ligand class
This class gives data about the generic ligand object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
(list)
"""
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.fixed = 0
self.ffname = "WAT"
self.map = {}
self.reference = ref
# Create each atom
for a in atoms:
if a.name in ref.altnames: # Rename atoms
a.name = ref.altnames[a.name]
atom = Atom(a, "HETATM", self)
atomname = atom.get("name")
if atomname not in self.map:
self.addAtom(atom)
else: # Don't add duplicate atom with altLoc field
oldatom = self.getAtom(atomname)
oldatom.set("altLoc","")
def createAtom(self, atomname, newcoords):
"""
Create a water atom. Note the HETATM field.
Parameters
atomname: The name of the atom (string)
newcoords: The new coordinates of the atom (list)
"""
oldatom = self.atoms[0]
newatom = Atom(oldatom, "HETATM", self)
newatom.set("x",newcoords[0])
newatom.set("y",newcoords[1])
newatom.set("z",newcoords[2])
newatom.set("name", atomname)
newatom.set("occupancy",1.00)
newatom.set("tempFactor",0.00)
newatom.added = 1
self.addAtom(newatom)
def addAtom(self, atom):
"""
Override the existing addAtom - include the link to the
reference object
"""
self.atoms.append(atom)
atomname = atom.get("name")
self.map[atomname] = atom
try:
atom.reference = self.reference.map[atomname]
for bond in atom.reference.bonds:
if self.hasAtom(bond):
bondatom = self.map[bond]
if bondatom not in atom.bonds: atom.bonds.append(bondatom)
if atom not in bondatom.bonds: bondatom.bonds.append(atom)
except KeyError:
atom.reference = None
```
#### File: MGLToolsPckgs/MolKit/PROSS.py
```python
USAGE = """
python PROSS.py pdbfile [oldmeso | fgmeso]
Choose old mesostate definitions or finegrained mesostate definitions.
Default is finegrained.
"""
import sys
import string, re
import copy
import gzip
import math
import types
# This script does not require Numeric
HAVE_NUMPY = 0
_RAD_TO_DEG = 180.0/math.pi
_DEG_TO_RAD = math.pi/180.0
RESIDUES = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'CYX', 'GLN', 'GLU',
'GLX', 'GLY', 'HIS', 'HIP', 'ILE', 'LEU', 'LYS', 'MET',
'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', 'ACE',
'NME', 'PCA', 'FOR', 'ASX', 'AMD']
ONE_LETTER_CODES = {
'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', 'CYS': 'C',
'GLN': 'Q', 'GLU': 'E', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I',
'LEU': 'L', 'MET': 'M', 'PHE': 'F', 'PRO': 'P', 'SER': 'S',
'THR': 'T', 'TRP': 'W', 'TYR': 'Y', 'VAL': 'V', 'LYS': 'K'}
_CHI1_DEFAULT = ('N', 'CA', 'CB', 'CG')
CHI1_ATOMS = {
'ARG': _CHI1_DEFAULT,
'ASN': _CHI1_DEFAULT,
'ASP': _CHI1_DEFAULT,
'CYS': ('N', 'CA', 'CB', 'SG'),
'SER': ('N', 'CA', 'CB', 'OG'),
'GLN': _CHI1_DEFAULT,
'GLU': _CHI1_DEFAULT,
'HIS': _CHI1_DEFAULT,
'ILE': ('N', 'CA', 'CB', 'CG1'),
'LEU': _CHI1_DEFAULT,
'LYS': _CHI1_DEFAULT,
'MET': _CHI1_DEFAULT,
'PHE': _CHI1_DEFAULT,
'PRO': _CHI1_DEFAULT,
'THR': ('N', 'CA', 'CB', 'OG1'),
'TRP': _CHI1_DEFAULT,
'TYR': _CHI1_DEFAULT,
'VAL': ('N', 'CA', 'CB', 'CG1'),
'GLX': _CHI1_DEFAULT,
'ASX': _CHI1_DEFAULT,
'CYX': _CHI1_DEFAULT,
'PCA': _CHI1_DEFAULT
}
CHI2_ATOMS = {
'ARG': ('CA', 'CB', 'CG', 'CD'),
'ASN': ('CA', 'CB', 'CG', 'OD1'),
'ASP': ('CA', 'CB', 'CG', 'OD1'),
'ASX': ('CA', 'CB', 'CG', 'OD1'),
'GLN': ('CA', 'CB', 'CG', 'CD'),
'GLU': ('CA', 'CB', 'CG', 'CD'),
'GLX': ('CA', 'CB', 'CG', 'CD'),
'HIS': ('CA', 'CB', 'CG', 'ND1'),
'ILE': ('CA', 'CB', 'CG1', 'CD1'),
'LEU': ('CA', 'CB', 'CG', 'CD1'),
'LYS': ('CA', 'CB', 'CG', 'CD'),
'MET': ('CA', 'CB', 'CG', 'SD'),
'PHE': ('CA', 'CB', 'CG', 'CD1'),
'PRO': ('CA', 'CB', 'CG', 'CD'),
'TRP': ('CA', 'CB', 'CG', 'CD1'),
'TYR': ('CA', 'CB', 'CG', 'CD1')
}
CHI3_ATOMS = {
'ARG': ('CB', 'CG', 'CD', 'NE'),
'GLN': ('CB', 'CG', 'CD', 'OE1'),
'GLU': ('CB', 'CG', 'CD', 'OE1'),
'GLX': ('CB', 'CG', 'CD', 'OE1'),
'LYS': ('CB', 'CG', 'CD', 'CE'),
'MET': ('CB', 'CG', 'SD', 'CE')
}
CHI4_ATOMS = {
'ARG': ('CG', 'CD', 'NE', 'CZ'),
'LYS': ('CG', 'CD', 'CE', 'NZ')
}
# Unpack PDB Line Constants - used for simple index changes
UP_SERIAL = 0
UP_NAME = 1
UP_ALTLOC = 2
UP_RESNAME = 3
UP_CHAINID = 4
UP_RESSEQ = 5
UP_ICODE = 6
UP_X = 7
UP_Y = 8
UP_Z = 9
UP_OCCUPANCY = 10
UP_TEMPFACTOR = 11
##########################
# Start Mesostate Definition Code
##########################
# This is redundant but kept for compatibility
default = 'fgmeso'
MSDEFS = {}
# Setup Fine Grain Mesostate Bins (ala <NAME>)
MSDEFS['fgmeso'] = {}
mydefs = MSDEFS['fgmeso']
mydefs['RC_DICT'] = {( 180,-165): 'Aa', ( 180,-135): 'Ab', ( 180,-105): 'Ac',
( 180, -75): 'Ad', ( 180, -45): 'Ae', ( 180, -15): 'Af',
( 180, 15): 'Ag', ( 180, 45): 'Ah', ( 180, 75): 'Ai',
( 180, 105): 'Aj', ( 180, 135): 'Ak', ( 180, 165): 'Al',
(-150,-165): 'Ba', (-150,-135): 'Bb', (-150,-105): 'Bc',
(-150, -75): 'Bd', (-150, -45): 'Be', (-150, -15): 'Bf',
(-150, 15): 'Bg', (-150, 45): 'Bh', (-150, 75): 'Bi',
(-150, 105): 'Bj', (-150, 135): 'Bk', (-150, 165): 'Bl',
(-120,-165): 'Ca', (-120,-135): 'Cb', (-120,-105): 'Cc',
(-120, -75): 'Cd', (-120, -45): 'Ce', (-120, -15): 'Cf',
(-120, 15): 'Cg', (-120, 45): 'Ch', (-120, 75): 'Ci',
(-120, 105): 'Cj', (-120, 135): 'Ck', (-120, 165): 'Cl',
( -90,-165): 'Da', ( -90,-135): 'Db', ( -90,-105): 'Dc',
( -90, -75): 'Dd', ( -90, -45): 'De', ( -90, -15): 'Df',
( -90, 15): 'Dg', ( -90, 45): 'Dh', ( -90, 75): 'Di',
( -90, 105): 'Dj', ( -90, 135): 'Dk', ( -90, 165): 'Dl',
( -60,-165): 'Ea', ( -60,-135): 'Eb', ( -60,-105): 'Ec',
( -60, -75): 'Ed', ( -60, -45): 'Ee', ( -60, -15): 'Ef',
( -60, 15): 'Eg', ( -60, 45): 'Eh', ( -60, 75): 'Ei',
( -60, 105): 'Ej', ( -60, 135): 'Ek', ( -60, 165): 'El',
( -30,-165): 'Fa', ( -30,-135): 'Fb', ( -30,-105): 'Fc',
( -30, -75): 'Fd', ( -30, -45): 'Fe', ( -30, -15): 'Ff',
( -30, 15): 'Fg', ( -30, 45): 'Fh', ( -30, 75): 'Fi',
( -30, 105): 'Fj', ( -30, 135): 'Fk', ( -30, 165): 'Fl',
( 0,-165): 'Ja', ( 0,-135): 'Jb', ( 0,-105): 'Jc',
( 0, -75): 'Jd', ( 0, -45): 'Je', ( 0, -15): 'Jf',
( 0, 15): 'Jg', ( 0, 45): 'Jh', ( 0, 75): 'Ji',
( 0, 105): 'Jj', ( 0, 135): 'Jk', ( 0, 165): 'Jl',
( 30,-165): 'Ha', ( 30,-135): 'Hb', ( 30,-105): 'Hc',
( 30, -75): 'Hd', ( 30, -45): 'He', ( 30, -15): 'Hf',
( 30, 15): 'Hg', ( 30, 45): 'Hh', ( 30, 75): 'Hi',
( 30, 105): 'Hj', ( 30, 135): 'Hk', ( 30, 165): 'Hl',
( 60,-165): 'Ia', ( 60,-135): 'Ib', ( 60,-105): 'Ic',
( 60, -75): 'Id', ( 60, -45): 'Ie', ( 60, -15): 'If',
( 60, 15): 'Ig', ( 60, 45): 'Ih', ( 60, 75): 'Ii',
( 60, 105): 'Ij', ( 60, 135): 'Ik', ( 60, 165): 'Il',
( 90,-165): 'Ja', ( 90,-135): 'Jb', ( 90,-105): 'Jc',
( 90, -75): 'Jd', ( 90, -45): 'Je', ( 90, -15): 'Jf',
( 90, 15): 'Jg', ( 90, 45): 'Jh', ( 90, 75): 'Ji',
( 90, 105): 'Jj', ( 90, 135): 'Jk', ( 90, 165): 'Jl',
( 120,-165): 'Ka', ( 120,-135): 'Kb', ( 120,-105): 'Kc',
( 120, -75): 'Kd', ( 120, -45): 'Ke', ( 120, -15): 'Kf',
( 120, 15): 'Kg', ( 120, 45): 'Kh', ( 120, 75): 'Ki',
( 120, 105): 'Kj', ( 120, 135): 'Kk', ( 120, 165): 'Kl',
( 150,-165): 'La', ( 150,-135): 'Lb', ( 150,-105): 'Lc',
( 150, -75): 'Ld', ( 150, -45): 'Le', ( 150, -15): 'Lf',
( 150, 15): 'Lg', ( 150, 45): 'Lh', ( 150, 75): 'Li',
( 150, 105): 'Lj', ( 150, 135): 'Lk', ( 150, 165): 'Ll'}
# What mesostate to use when the angles are invalid (e.g. 999.99)
mydefs['INVALID'] = '??'
# What mesostate to use when the omega angle is odd (e.g. < 90.0)
mydefs['OMEGA'] = '**'
# The size of mesostate codes used in this set.
mydefs['CODE_LENGTH'] = 2
# Geometric parameters: DELTA is the size of the bins, XXX_OFF is
# the offset from 0 degrees of the centers of the bins.
mydefs['DELTA'] = 30.0
mydefs['PHI_OFF'] = 0.0
mydefs['PSI_OFF'] = 15.0
# Set up turns and turn dictionary. Dictionary contains the number of
# occurences in the PDB. This number isn't used, so for new turn types
# '1' is sufficient (as is used for PII, below)
mydefs['TURNS'] = {'EfDf': 5226, 'EeEf': 4593, 'EfEf': 4061, 'EfDg': 3883,
'EeDg': 2118, 'EeEe': 1950, 'EfCg': 1932, 'EeDf': 1785,
'EkJf': 1577, 'EkIg': 1106, 'EfEe': 995, 'EkJg': 760,
'EeCg': 553, 'DfDf': 479, 'EfCf': 395, 'DgDf': 332,
'DfDg': 330, 'IhIg': 310, 'EfDe': 309, 'EkIh': 298,
'DgCg': 275, 'DfCg': 267, 'IbDg': 266, 'DfEe': 260,
'FeEf': 250, 'IbEf': 249, 'DfEf': 219, 'IhJf': 216,
'IhJg': 213, 'IgIg': 207, 'EfCh': 188, 'DgEe': 180,
'DgEf': 176, 'EeEg': 172, 'IhIh': 153, 'EeDe': 150,
'IgJg': 147, 'EkKf': 147, 'EeCh': 147, 'IbDf': 131,
'DgDg': 128, 'EgDf': 127, 'FeDg': 114, 'ElIg': 111,
'IgIh': 107, 'DfDe': 107, 'EjIg': 101, 'EeCf': 100,
'DfCh': 94, 'DgCf': 91, 'DfCf': 91, 'DeEe': 91,
'DkIh': 88, 'FeDf': 79, 'EkIf': 78, 'EeDh': 76,
'DgCh': 74, 'IgJf': 71, 'EjJg': 71, 'FeEe': 69,
'DlIh': 66, 'EgCg': 65, 'ElIh': 62, 'EjJf': 62,
'FeCg': 59, 'DlIg': 56, 'IbCg': 54, 'EfEg': 54,
'EkJe': 53, 'FkJf': 52, 'ElJg': 51, 'DgDe': 49,
'DlJg': 46, 'EgCf': 45, 'IaEf': 40, 'FkIg': 39,
'JaEf': 38, 'EjIh': 38, 'EgEf': 38, 'DkJg': 36,
'DeEf': 34, 'EeCi': 31, 'JgIh': 29, 'IcEf': 29,
'EkKe': 29, 'DkIg': 29, 'IbEe': 27, 'EgDg': 27,
'EeFe': 27, 'EjKf': 26, 'IaDf': 25, 'HhIg': 24,
'HbDg': 24, 'ElJf': 24, 'EfDh': 24, 'IcDf': 23,
'EfBh': 23, 'IcDg': 22, 'IcCg': 22, 'FkJg': 21,
'FeCh': 21, 'IgKf': 20, 'FdDg': 20, 'EkHh': 20,
'DfDh': 20, 'DgBh': 19, 'DfBh': 19, 'DeDf': 19,
'DfFe': 18, 'EfFe': 17, 'EgEe': 16, 'EgDe': 16,
'DkJf': 16, 'JgJg': 15, 'IbEg': 15, 'IbCh': 15,
'EfBg': 15, 'DgCe': 15, 'JlEf': 14, 'CgCg': 14,
'HhJf': 13, 'EeBi': 13, 'DfBi': 13, 'IhIf': 12,
'FeEg': 12, 'FdEf': 12, 'EdEf': 12, 'DlJf': 12,
'DhCg': 12, 'JgIg': 11, 'IeBg': 11, 'FjIg': 11,
'FdCh': 11, 'EdEe': 11, 'JfIh': 10, 'JaEe': 10,
'HhJg': 10, 'HbEf': 10, 'HbCh': 10, 'FkIh': 10,
'FjJf': 10, 'ElJe': 10, 'DhDf': 10, 'CgDf': 10}
# Set up the PII defitions, similar to dictionary above.
mydefs['PII'] = {'Dk':1, 'Dl':1, 'Ek':1, 'El':1}
# Set up the codes that define helix and strand. Here, rather than storing
# the dictionary like we did above, we'll store the regular expression
# matcher directly. This prevents us from recompiling it every time we
# want to find a helix or strand.
helix = ('De', 'Df', 'Ed', 'Ee', 'Ef', 'Fd', 'Fe')
strand = ('Bj', 'Bk', 'Bl', 'Cj', 'Ck', 'Cl', 'Dj', 'Dk', 'Dl')
pat_helix = "(%s){5,}" % string.join(map(lambda x: "(%s)" % x, helix), '|')
pat_strand = "(%s){3,}" % string.join(map(lambda x: "(%s)" % x, strand), '|')
mydefs['HELIX'] = re.compile(pat_helix)
mydefs['STRAND'] = re.compile(pat_strand)
###########################
# Setup Old Mesostate Bins (ala <NAME>)
##########################
MSDEFS['oldmeso'] = {}
mydefs = MSDEFS['oldmeso']
mydefs['RC_DICT'] = {( 180, 180): 'A', ( 180,-120): 'B', ( 180, -60): 'C',
( 180, 0): 'D', ( 180, 60): 'E', ( 180, 120): 'F',
(-120, 180): 'G', (-120,-120): 'H', (-120, -60): 'I',
(-120, 0): 'J', (-120, 60): 'K', (-120, 120): 'L',
( -60, 180): 'M', ( -60,-120): 'N', ( -60, -60): 'O',
( -60, 0): 'P', ( -60, 60): 'Q', ( -60, 120): 'R',
( 0, 180): 'S', ( 0,-120): 'T', ( 0, -60): 'U',
( 0, 0): 'V', ( 0, 60): 'W', ( 0, 120): 'X',
( 60, 180): 'm', ( 60,-120): 'r', ( 60, -60): 'q',
( 60, 0): 'p', ( 60, 60): 'o', ( 60, 120): 'n',
( 120, 180): 'g', ( 120,-120): 'l', ( 120, -60): 'k',
( 120, 0): 'j', ( 120, 60): 'i', ( 120, 120): 'h'}
# What mesostate to use when the angles are invalid (e.g. 999.99)
mydefs['INVALID'] = '?'
# What mesostate to use when the omega angle is odd (e.g. < 90.0)
mydefs['OMEGA'] = '*'
# The size of mesostate codes used in this set.
mydefs['CODE_LENGTH'] = 1
# Geometric parameters: DELTA is the size of the bins, XXX_OFF is
# the offset from 0 degrees of the centers of the bins.
mydefs['DELTA'] = 60.0
mydefs['PHI_OFF'] = 0.0
mydefs['PSI_OFF'] = 0.0
# Set up turns and turn dictionary. Dictionary contains the type
# of the turn (no primes)
mydefs['TURNS'] = {'OO': 1, 'OP': 1, 'OJ': 1, 'PO': 1, 'PP': 1, 'PJ': 1,
'JO': 1, 'JP': 1, 'JJ': 1,
'Mo': 2, 'Mp': 2, 'Mj': 2, 'Ro': 2, 'Rp': 2, 'Rj': 2,
'oo': 3, 'op': 3, 'oj': 3, 'po': 3, 'pp': 3, 'pj': 3,
'jo': 3, 'jp': 3, 'jj': 3,
'mO': 4, 'mP': 4, 'mJ': 4, 'rO': 4, 'rP': 4, 'rJ': 4}
# Set up the PII defitions, similar to dictionary above.
mydefs['PII'] = {'M':1, 'R':1}
# Set up the codes that define helix and strand. Here, rather than storing
# the dictionary like we did above, we'll store the regular expression
# matcher directly. This prevents us from recompiling it every time we
# want to find a helix or strand.
helix = ('O', 'P')
strand = ('L', 'G', 'F', 'A')
pat_helix = "(%s){5,}" % string.join(map(lambda x: "(%s)" % x, helix), '|')
pat_strand = "(%s){3,}" % string.join(map(lambda x: "(%s)" % x, strand), '|')
mydefs['HELIX'] = re.compile(pat_helix)
mydefs['STRAND'] = re.compile(pat_strand)
##########################
# End Mesostate Definition Code
##########################
def res_rc(r1, r2, r3=180, mcodes=None):
"""res_rc(r1, r2, r3) - get mesostate code for a residue
Given a phi (r1), psi (r2), and omega (r3) torsion angle, calculate
the mesostate code that describes that residue.
A mesostate will be returned in
all but two cases: if omega deviates from planarity by more than 90
degrees, '*' is returned. Also, if any torsions are greater than
180.0 (biomol assignes 999.0 degrees to angles that that are
indeterminate), prosst.INVALID is returned. Here, r3 defaults to
180.0.
"""
if not mcodes: mcodes = default
ms = MSDEFS[mcodes]
OMEGA = ms['OMEGA']
INVALID = ms['INVALID']
PHI_OFF = ms['PHI_OFF']
PSI_OFF = ms['PSI_OFF']
DELTA = ms['DELTA']
RC_DICT = ms['RC_DICT']
if (abs(r3) <= 90.0):
return OMEGA
elif r1>180.0 or r2>180.0 or r3>180.0:
return INVALID
ir1 = -int(PHI_OFF) + int(round((r1+PHI_OFF)/DELTA )) * int(DELTA)
ir2 = -int(PSI_OFF) + int(round((r2+PSI_OFF)/DELTA )) * int(DELTA)
while ir1 <= -180: ir1 = ir1 + 360
while ir1 > 180: ir1 = ir1 - 360
while ir2 <= -180: ir2 = ir2 + 360
while ir2 > 180: ir2 = ir2 - 360
return RC_DICT[(ir1,ir2)]
def rc_codes(chain, phi=None, psi=None, ome=None, mcodes=None):
"""rc_codes(chain, phi, psi, ome) - return rotamer codes
Given a protein chain (and optionally phi, psi, omega), this
function will return a list of mesostate codes that
applies to the chain, as determined by res_rc.
"""
if not mcodes: mcodes = default
n = range(len(chain))
if phi is None: phi = map(chain.phi, n)
if psi is None: psi = map(chain.psi, n)
if ome is None: ome = map(chain.omega, n)
return map(lambda x, y, z: res_rc(x, y, z, mcodes), phi, psi, ome)
def rc_ss(chain, phi=None, psi=None, ome=None, mcodes=None):
"""rc_ss(chain, phi, psi, ome) - calculate secondary structure
This function calculates the secondary structure using the PROSS method
with rotamer codes. Given a chain, and optionally a list of phi,
psi, and omega, it calculates the backbone secondary structure of
the chain. The return value is (phi, psi, ome, sst), where
phi, psi, and ome are calculated if not specified, and sst is the
secondary structure codes: H = helix, E = strand, P = PII, C = coil.
"""
if not mcodes: mcodes = default
ms = MSDEFS[mcodes]
PII = ms['PII']
TURNS = ms['TURNS']
HELIX = ms['HELIX']
STRAND = ms['STRAND']
if phi is None:
chain.gaps()
nres = len(chain)
phi = map(chain.phi, xrange(nres))
else:
nres = len(chain)
if psi is None: psi = map(chain.psi, xrange(nres))
if ome is None: ome = map(chain.omega, xrange(nres))
codes = rc_codes(chain, phi, psi, ome, mcodes)
chain.gaps()
sst = ['C']*nres
is_PII = PII.has_key
for i in xrange(nres-1):
code = codes[i]
if is_PII(code):
sst[i] = 'P'
is_turn = TURNS.has_key
for i in xrange(nres-1):
code = codes[i] + codes[i+1]
if is_turn(code):
sst[i] = sst[i+1] = 'T'
helices = _rc_find(codes, HELIX, mcodes)
strands = _rc_find(codes, STRAND, mcodes)
for helix in helices:
i, j = helix
for k in range(i, j):
sst[k] = 'H'
for strand in strands:
i, j = strand
for k in range(i, j):
if sst[k] in ('C', 'P'): sst[k] = 'E'
# if sst[k] == 'C': sst[k] = 'E'
return phi, psi, ome, sst
def _rc_find(codes, pattern, mcodes=None):
"""_rc_find(codes, pat_obj) - find a endpoints of a regexp
Given a list of mesostate codes, this function identifies a endpoints
of a match <pattern>. <pat_obj> is a compiled regular expression
pattern whose matches will be returned as pairs indicated start,
end in <codes>
"""
if not mcodes: mcodes = default
CODE_LENGTH = MSDEFS[mcodes]['CODE_LENGTH']
if not type(codes) == type(''):
codes = string.join(codes, '')
matches = []
it = pattern.finditer(codes)
try:
while 1:
mat = it.next()
matches.append((mat.start()/CODE_LENGTH, mat.end()/CODE_LENGTH))
except StopIteration:
pass
return matches
##############################
# Protein objects and methods
##############################
def is_atom(o):
return hasattr(o, '_is_an_atom3d')
def is_residue(o):
return hasattr(o, '_is_a_residue')
def is_chain(o):
return hasattr(o, '_is_a_chain')
def is_mol(o):
return hasattr(o, '_is_a_mol')
####################
HAVE_POP = hasattr([], 'pop')
HAVE_EXTEND = hasattr([], 'extend')
class TypedList:
"""A Python list restricted to having objects of the same type.
An instance of a TypedList is created as follows:
mylist = TypedList(function, [elements])
where function is a python function which takes an argument
and returns 1 or 0 indicating whether the object represented
by the argument is of the correct type, and elements is an optional
list of elements to be added into the instance. Here is a
full blown example.
def is_int(o):
return type(o) == type(0)
mylist = TypedList(is_int, [0, 1, 2, 3])
New elements are added to the list as follows:
mylist.append(25)
Instances of TypedList support all operations available for
Python Lists (as of Python version 1.5.2a2)
"""
_is_a_typed_list = 1
def __init__(self, function, elements=None):
self._func = function
self.elements = []
if not elements is None:
if self._func(elements):
self.elements.append(elements)
else:
for el in elements:
self.append(el)
def append(self, el):
if self._func(el):
self.elements.append(el)
else:
raise TypeError, 'Element to be added to list has incorrect type.'
def __len__(self): return len(self.elements)
def __repr__(self):
return "%s(%s, %s)" % (self.__class__, self._func.__name__,
`self.elements`)
def __str__(self):
return `self.elements`
def __getitem__(self, i): return self.elements[i]
def __setitem__(self, i, v):
if self._func(v):
self.elements[i] = v
else:
raise TypeError, 'Item not of correct type in __setitem__'
def __delitem__(self, i): del self.elements[i]
def __getslice__(self, i, j):
new = self.__class__(self._func)
new.elements = self.elements[i:j]
return new
def __setslice__(self, i, j, v):
if self._alltrue(v):
self.elements[i:j] = v
def __delslice__(self, i, j):
del self.elements[i:j]
def __add__(self, other):
if not hasattr(other, '_is_a_typed_list'):
raise TypeError,'List to be concatenated not instance of %s' %\
self.__class__
if self._func <> other._func:
raise TypeError, 'Lists to be added not of same type'
new = self.__class__(self._func)
new.elements = self.elements + other.elements
return new
def __mul__(self, other):
if type(other) == type(0):
new = self.__class__(self._func)
new.elements = self.elements * other
return new
else:
raise TypeError, "can't multiply list with non-int"
__rmul__ = __mul__
def __copy__(self):
new = self.__class__(self._func)
for el in self.elements:
new.elements.append(el.__copy__())
have = new.__dict__.has_key
for key in self.__dict__.keys():
if not have(key):
new.__dict__[key] = copy.deepcopy(self.__dict__[key])
return new
__deepcopy__ = clone = __copy__
def _alltrue(self, els):
return len(els) == len(filter(None, map(self._func, els)))
def sort(self): self.elements.sort()
def reverse(self): self.elements.reverse()
def count(self, el): return self.elements.count(el)
def extend(self, els):
if self._alltrue(els):
if HAVE_EXTEND:
self.elements.extend(els)
else:
for el in els:
self.elements.append(el)
else:
raise TypeError, 'One or more elements of list not of correct type'
def pop(self):
if HAVE_POP:
return self.elements.pop()
else:
el = self.elements[-1]
del self.elements[-1]
return el
def index(self, el): return self.elements.index(el)
def remove(self, el): self.elements.remove(el)
def insert(self, pos, el):
if self._func(el):
self.elements.insert(pos, el)
else:
raise TypeError, 'Item not of correct type in insert'
def indices(self, len=len):
return xrange(len(self.elements))
def reverse_indices(self, len=len):
return xrange(len(self.elements)-1, -1, -1)
####################
class molResidue(TypedList):
_is_a_residue = 1
def __init__(self, name='', atoms=None, **kw):
TypedList.__init__(self, is_atom, atoms)
self.name = name
for key, value in kw.items():
setattr(self, key, value)
def num_atoms(self):
"""returns the number of atoms in residue"""
return len(self.elements)
def has_atom(self, name):
"""returns true if residue has an atom named 'name'"""
for atom in self.elements:
if atom.name == name:
return 1
return 0
def atoms(self):
return self.elements
def atoms_with_name(self, *names):
"""returns atoms in residue with specified names"""
ret = []
Append = ret.append
for name in names:
for atom in self.elements:
if atom.name == name:
Append(atom)
break
return ret
def delete_atoms_with_name(self, *names):
"""delete atoms in residue with specified names"""
els = self.elements
for i in self.reverse_indices():
atom = els[i]
if atom.name in names:
del els[i]
def atoms_not_with_name(self, *names):
"""returns atoms in residue excluding specified names"""
ret = []
for atom in self.elements:
if not atom.name in names:
ret.append(atom)
return ret
def atom_coordinates(self, *names):
"""returns coordinates of named atoms.
If names is omitted all atom coordinates are returned."""
if len(names)==0:
atoms = self.elements
else:
atoms = apply(self.atoms_with_name, names)
na = len(atoms)
if na == 0: return
if HAVE_NUMPY:
a = Numeric.zeros((na, 3), 'd')
else:
a = [None]*na
pos = 0
for atom in atoms:
a[pos] = atom.coords()
pos = pos + 1
return a
def assign_radii(self):
raise AttributeError, 'Should be defined in specialized class'
def type(self):
return 'residue'
class molChain(TypedList):
_is_a_chain = 1
def __init__(self, name='', residues=None, **kw):
self.name = name
TypedList.__init__(self, is_residue, residues)
for key, value in kw.items():
setattr(self, key, value)
def num_residues(self): return len(self)
def num_atoms(self):
na = 0
for res in self.elements:
na = na + len(res.elements)
return na
def atoms(self):
ret = []
Append = ret.append
for res in self.elements:
for atom in res.elements:
Append(atom)
return ret
def residues_with_name(self, *names):
"""returns named residues as a python list"""
if len(names) == 0:
return
l = []
for res in self.elements:
if res.name in names:
l.append(res)
return l
def delete_residues_with_name(self, *names):
"""delete named residues from Chain"""
if len(names) == 0:
return
els = self.elements
for i in self.reverse_indices():
if els[i].name in names:
del els[i]
def residues_not_with_name(self, *names):
"""returns residues excluding specified names as a python list"""
ret = []
for res in self.elements:
if not res.name in names:
ret.append(res)
return ret
def atoms_with_name(self, *names):
ret = []
Append = ret.append
if len(names) > 0:
for res in self.elements:
for name in names:
for atom in res.elements:
if atom.name == name:
Append(atom)
break
else:
for res in self.elements:
for atom in res.elements:
Append(atom)
return ret
def delete_atoms_with_name(self, *names):
"""delete atoms in residue with specified names"""
for res in self.elements:
apply(res.delete_atoms_with_name, names)
def atoms_not_with_name(self, *names):
"""returns atoms in residue excluding specified names"""
ret = []
for res in self.elements:
ret[len(ret):] = apply(res.atoms_not_with_name, names)
return ret
def atom_coordinates(self, *names):
"""returns coordinates of named atoms. if names is None
all atom coordinates are returned."""
coords = []
if len(names) > 0:
for res in self.elements:
for atom in res.elements:
if atom.name in names:
coords.append(atom.coords())
else:
atoms = apply(self.atoms_with_name, names)
coords = map(lambda a:a.coords(), atoms)
if HAVE_NUMPY:
return Numeric.array(coords)
else:
return coords
def atoms(self):
atoms = []
for res in self.elements:
for atom in res: atoms.append(atom)
return atoms
def delete_alt_locs(self):
"""delete_alt_locs - remove secondary conformations in the chain
In a chain with multiple occupancy and alternate location identifiers,
it is often desirable to eliminate the secondary conformations for
use in simulation, etc. This function (abitrarily) finds and selects
the first given conformation and deletes all other conformations.
"""
AtomCount = self.present
chain = self.elements
delete = []
for i in xrange(len(chain)):
residue = chain[i]
rid = (residue.idx, residue.icode)
for j in xrange(len(residue)):
atom = residue[j]
anam = atom.name
try:
acnt = AtomCount[rid][anam]
except KeyError:
print "Unable to locate %s %s %s in present dictionary."%\
(rid[0], rid[1], anam)
return
if acnt == 1:
continue
if acnt < 1:
AtomCount[rid][anam] = acnt + 1
delete.append((i, j))
continue
atom.alt = ' '
AtomCount[rid][anam] = -acnt + 2
delete.reverse()
for r, a in delete:
del chain[r][a]
def assign_radii(self):
for res in self:
res.assign_radii()
def preserve_chain_hetero(self):
"""prevent hetero residues from being deleted as hetero atoms
Normally, delete_hetero will delete all hetero atoms from a
molecule. This includes waters and heterogroups (hemes, etc.),
but it also includes hetero residues--nonstandard residues
that have backbone connectivity but perhaps extra atoms (e.g.
S-hydroxy-cysteine). Deleting these residues may disrupt an
otherwise continuous chain and may be undesirable.
Given that a chain has a valid SEQRES entry, this function will
'unset' the hetero flag for heterogroups that are involved in
the sequence itself. When delete_hetero is run, these atoms
will be preserved.
"""
for i in xrange(self.num_residues()):
if hasattr(self[i], 'chain_het') and hasattr(self[i], 'het'):
delattr(self[i], 'het')
def delete_hetero(self):
"""delete all hetero atoms from a protein
This function removes all HETATM records from the molecular
structure. This include waters, heme groups, as well as residues
with nonstandard structures
"""
for i in xrange(self.num_residues()-1, -1, -1):
if hasattr(self[i], 'het'):
del self[i]
def delete_waters(self):
for i in xrange(self.num_residues()-1, -1, -1):
if self[i].name == 'HOH':
del self[i]
def translate(self, dx, dy=None, dz=None):
for res in self.elements:
res.translate(dx, dy, dz)
def rotatex(self, theta):
for res in self.elements:
res.rotatex(theta)
def rotatey(self, theta):
res.rotatey(theta)
def rotatez(self, theta):
for res in self.elements:
res.rotatez(theta)
def type(self):
return 'Chain'
class molMol(TypedList):
_is_a_mol = 1
def __init__(self, name='', chains=None):
self.name = name
self.resolution = None
self.method = []
self.rprog = None
self.rfree = None
self.rvalu = None
TypedList.__init__(self, is_chain, chains)
def num_chain(self): return len(self)
def num_res(self):
nr = 0
for chain in self: nr = nr + len(chain)
return nr
def num_atoms(self):
na = 0
for chain in self: na = na + chain.num_atoms()
return na
def atoms(self):
ret = []
Append = ret.append
for chain in self.elements:
for res in chain.elements:
for atom in res.elements:
Append(atom)
return ret
def chains_with_name(self, *names):
chains = []
for chain in self.elements:
if chain.name in names: chains.append(chain)
return chains
def residues_with_name(self, *names):
residues = []
for chain in self.elements:
for res in chain.elements:
if res.name in names: residues.append(res)
return residues
def atoms_with_name(self, *names):
ret = []
Append = ret.append
for chain in self.elements:
for res in chain.elements:
for name in names:
for atom in res.elements:
if atom.name == name:
Append(atom)
break
return ret
def delete_atoms_with_name(self, *names):
"""delete atoms in assembly with specified names"""
for chain in self.elements:
apply(chain.delete_atoms_with_name, names)
def atoms_not_with_name(self, *names):
"""returns atoms in assembly excluding specified names"""
ret = []
for chain in self.elements:
ret[len(ret):] = apply(chain.atoms_not_with_name, names)
return ret
def atom_coordinates(self, *names):
coords = []
if len(names) == 0:
for chain in self.elements:
for res in chain.elements:
for atom in res.elements:
coords.append(atom.coords())
else:
atoms = apply(self.atoms_with_name, names)
coords = map(lambda a:a.coords(), atoms)
del atoms
if HAVE_NUMPY:
return Numeric.array(coords)
else:
return coords
def delete_alt_locs(self):
"""delete_alt_locs - remove all secondary conformations"""
for chain in self:
chain.delete_alt_locs()
def assign_radii(self):
for chain in self:
chain.assign_radii()
def delete_water(self):
for chain in self:
chain.delete_water()
def preserve_chain_hetero(self):
for i in self.indices():
self[i].preserve_chain_hetero()
def delete_hetero(self):
for i in self.reverse_indices():
self[i].delete_hetero()
if len(self[i]) == 0:
del self[i]
def pdb(self, file, renum=0, seq=1):
"""pdb(file, renum=0, seq=1) - write a PDB file
Given a file name/open file handle (with .gz option), this function
will write the PDB coordinate file corresponding to the current
molecular object. If renum is true, then residue indices will be
renumbered starting from 1, if seq is true, then SEQRES records
will be written in the PDB file.
This function is a wrapper for pdbout.write_pdb.
"""
pdbout.write_pdb(self, file, renum, seq)
def pack_pdb_line(atom, idx, aan, aanum, ic, cn, f, fmt):
"""pack_pdb_line - construct an ATOM record for a PDB file
pack_pdb_line takes the following arguments:
o atom An atom3d object, used for extracting coordinates, occupancy
atom name, alternate location, and B-factor. If these
attributes aren't contained in the object, reasonable defaults
are used.
o idx The atom serial number
o aan The name of the containing amino residue (DNA base)
o aanum The number of the containing residue (DNA base)
o ic The insertion code for homologous residue numbering
o cn The name of the chain
o f An open file handle where the format will be written.
o fmt A format to be used. Generally this is either for ATOM or
HETATM records.
"""
try:
atn = pad(atom.name)
except AttributeError:
atn = " X "
try:
al = atom.alt
except AttributeError:
al = ' '
try:
occ = atom.occ
bf = atom.bf
except AttributeError:
occ = 1.00
bf = 25.00
x = atom.xcoord()
y = atom.ycoord()
z = atom.zcoord()
# fmt = '%s %s %s %s %s %s %s %s %s %s %s\n'
# atfmt = 'ATOM %5i %4s%1s%3s %1s%4s%1s %8.3f%8.3f%8.3f%6.2f%6.2f\n'
# htfmt = 'HETATM%5i %4s%1s%3s %1s%4s%1s %8.3f%8.3f%8.3f%6.2f%6.2f\n'
f.write(fmt % (idx, atn, al, aan, cn, aanum, ic, x, y, z, occ, bf))
def pad(nm):
"""pad(nm) - a function to pad an atom name with appropraiate spaces"""
space = ' '
if len(nm) >= 4:
return nm
try:
int(nm[0])
except ValueError:
nm = ' ' + nm
return nm + space[0:4-len(nm)]
def write_pdb(myMol, f, renum=0, seq=None, pack=pack_pdb_line):
"""write_pdb - write a PDB file from a molecular object
write_pdb takes a biomol.Mol object and creates a PDB file
based on the definitions given. It can support all atomic
properties as well as insertion codes and alternate locations.
Essentially, biomol is designed such that if the original molecule
has all that stuff it will be retained in the final PDB file. If
that is not desired, you must make the modifications to the Mol
object yourself (or use one of the utilities).
write_pdb takes the following arguments:
o myMol The **mol.Mol** object to be written.
o f A file instruction. This can be a string, in which
case f will be interpreted as a filename. If the
string f ends with .gz, the resulting file will be
compressed using gzip. Alternatively, f can be an
open file object (it must have the write attribute).
If f is an object, the PDB will be written to the
object. When f is a file object, SEQRES and END
records will not be written by default.
o seq A boolean that determines whether SEQRES records
will be written. By default this is true (except in
the case where f is an object).
"""
if not is_mol(myMol):
print "This function only works for biomol.mol types."
return
default_seq = 1
if hasattr(f, 'write'):
out = f
close = 0
elif f[-3:] == '.gz':
import gzip
out = gzip.open(f, 'w')
close = 1
else:
out = open(f, 'w')
default_seq = 0
close = 1
if seq is None:
seq = default_seq
if seq:
for chain in myMol:
write_sequences(chain, out)
atfmt = 'ATOM %5i %4s%1s%3s %1s%4s%1s %8.3f%8.3f%8.3f%6.2f%6.2f\n'
htfmt = 'HETATM%5i %4s%1s%3s %1s%4s%1s %8.3f%8.3f%8.3f%6.2f%6.2f\n'
snum = 1
for chain in myMol:
cname = chain.name
rname = ''
rnum = 0
rlast = int(chain[0].idx)-1
for res in chain:
rname = res.name
icode = res.icode
fmt = atfmt
if hasattr(res, 'het') or hasattr(res, 'chain_het'):
fmt = htfmt
if not renum:
rnum = int(res.idx)
else:
rnum = rnum + (int(res.idx) - rlast)
icode = ' '
for atom in res:
pack(atom, snum, rname, rnum, icode, cname, out, fmt)
snum = snum + 1
if hasattr(res, 'gap'):
terminate(snum, rname, cname, rnum, icode, out)
snum = snum + 1
rlast = int(res.idx)
terminate(snum, rname, cname, rnum, icode, out)
snum = snum + 1
if close:
out.write('END\n')
out.close()
def write_sequences(chain, f):
"""write_sequences - write SEQRES records to a PDB file
write_sequences takes the following arguments:
o chain A mol.Chain type whose residues/bases will be displayed
o f An open file handle where information will be written.
"""
nr = len(chain)
nm = chain.name
sn = 1
elem = 0
fmt = 'SEQRES %2i %1s %4i '
for i in xrange(nr):
if elem == 0:
f.write(fmt % (sn, nm, nr))
sn = sn + 1
f.write('%3s ' % chain[i].name)
elem = elem + 1
if elem == 13:
f.write('\n')
elem = 0
if elem != 0:
f.write('\n')
def terminate(snum, rn, cn, rnum, icode, f):
"""terminate - write a TER record to a PDB file"""
fmt = 'TER %5i %3s %1s%4s%1s\n'
f.write(fmt % (snum, rn, cn, rnum, icode))
class Atom3d:
_is_an_atom3d = 1
def __init__(self, x, y, z, cnf={}):
self.x = float(x)
self.y = float(y)
self.z = float(z)
if cnf:
for key, value in cnf.items():
self.__dict__[key] = value
def __repr__(self):
return "Atom3d(%s, %s, %s)" % (self.x, self.y, self.z)
__str__ = __repr__
def coords(self):
if HAVE_NUMPY:
return Numeric.array((self.x, self.y, self.z))
else:
return [self.x, self.y, self.z]
def set_coords(self, x, y=None, z=None):
if y is None:
self.x, self.y, self.z = map(float, x)
else:
self.x, self.y, self.z = float(x), float(y), float(z)
def xcoord(self, v=None):
if v is None:
return self.x
else:
self.x = float(v)
def ycoord(self, v=None):
if v is None:
return self.y
else:
self.y = float(v)
def zcoord(self, v=None):
if v is None:
return self.z
else:
self.z = float(v)
def clone(self):
new = Atom3d(0., 0., 0.)
new.__dict__.update(self.__dict__)
return new
__copy__ = clone
# def __deepcopy__(self):
# cnf = copy.deepcopy(self.__dict__)
# return self.__class__(0, 0, 0, cnf)
def distance(self, other, sqrt=math.sqrt):
if not hasattr(other, '_is_an_atom3d'):
raise TypeError, 'distance argument must be Atom3d type'
return sqrt( (self.x - other.x)**2 +
(self.y - other.y)**2 +
(self.z - other.z)**2 )
def sqr_distance(self, other):
if not hasattr(other, '_is_an_atom3d'):
raise TypeError, 'sqr_distance argument must be Atom3d type'
return (self.x - other.x)**2 + \
(self.y - other.y)**2 + \
(self.z - other.z)**2
def angle(self, a, b, sqrt=math.sqrt, acos=math.acos):
if not hasattr(a, '_is_an_atom3d') or \
not hasattr(b, '_is_an_atom3d'):
raise TypeError, 'angle arguments must be Atom3d type'
x1, y1, z1 = self.x - a.x, self.y - a.y, self.z - a.z
x2, y2, z2 = b.x - a.x, b.y - a.y, b.z - a.z
v11 = x1**2 + y1**2 + z1**2
v22 = x2**2 + y2**2 + z2**2
if (v11 == 0.0 or v22 == 0.0):
raise ValueError, 'Null vector in angle'
v12 = x1*x2 + y1*y2 + z1*z2
ang = v12/sqrt(v11*v22)
if ang >= 1.0:
return 0.0
elif ang <= -1.0:
return 180.0
else:
return acos(ang) * _RAD_TO_DEG
def torsion(self, a, b, c, sqrt=math.sqrt, acos=math.acos):
if not hasattr(a, '_is_an_atom3d') or \
not hasattr(b, '_is_an_atom3d') or \
not hasattr(c, '_is_an_atom3d'):
raise TypeError, 'torsion arguments must be Atom3d type'
v12x, v12y, v12z = self.x - a.x, self.y - a.y, self.z - a.z
v32x, v32y, v32z = b.x - a.x, b.y - a.y, b.z - a.z
v43x, v43y, v43z = c.x - b.x, c.y - b.y, c.z - b.z
vn13x = v12y*v32z - v12z*v32y
vn13y = v12z*v32x - v12x*v32z
vn13z = v12x*v32y - v12y*v32x
vn24x = v32z*v43y - v32y*v43z
vn24y = v32x*v43z - v32z*v43x
vn24z = v32y*v43x - v32x*v43y
v12 = vn13x*vn24x + vn13y*vn24y + vn13z*vn24z
v11 = vn13x**2 + vn13y**2 + vn13z**2
v22 = vn24x**2 + vn24y**2 + vn24z**2
ang = v12/sqrt(v11*v22)
if ang >= 1.0:
return 0.0
elif ang <= -1.0:
return -180.0
else:
ang = acos(ang) * _RAD_TO_DEG
vtmp = vn13x * (vn24y*v32z - vn24z*v32y) + \
vn13y * (vn24z*v32x - vn24x*v32z) + \
vn13z * (vn24x*v32y - vn24y*v32x) < 0.0
if vtmp:
return -ang
else:
return ang
########################
# functions that operate on a collection of atoms
########################
def fromint(v1, dis, v2, a, v3, t, sqrt=math.sqrt, sin=math.sin, cos=math.cos):
ang = a * _DEG_TO_RAD
sina = sin(ang)
cosa = cos(ang)
tors = t * _DEG_TO_RAD
sint = sina * sin(tors)
cost = sina * cos(tors)
x1, y1, z1 = v1.coords()
x2, y2, z2 = v2.coords()
x3, y3, z3 = v3.coords()
u1x = x2 - x3
u1y = y2 - y3
u1z = z2 - z3
d = 1.0 / sqrt(u1x*u1x + u1y*u1y + u1z*u1z)
u1x = u1x*d
u1y = u1y*d
u1z = u1z*d
u2x = x1 - x2
u2y = y1 - y2
u2z = z1 - z2;
d = 1.0 / sqrt(u2x*u2x + u2y*u2y + u2z*u2z)
u2x = u2x*d
u2y = u2y*d
u2z = u2z*d
cosine = u1x*u2x + u1y*u2y + u1z*u2z
if (abs(cosine) < 1.0):
sine = 1.0/sqrt(1.0 - cosine*cosine)
else:
sine = 1.0/sqrt(cosine*cosine - 1.0)
u3x = sine * (u1y*u2z - u1z*u2y)
u3y = sine * (u1z*u2x - u1x*u2z)
u3z = sine * (u1x*u2y - u1y*u2x)
u4x = cost * (u3y*u2z - u3z*u2y)
u4y = cost * (u3z*u2x - u3x*u2z)
u4z = cost * (u3x*u2y - u3y*u2x)
return Atom3d(x1 + dis*(-u2x*cosa + u4x + u3x*sint),
y1 + dis*(-u2y*cosa + u4y + u3y*sint),
z1 + dis*(-u2z*cosa + u4z + u3z*sint))
def _atof(s, atof=string.atof):
try:
return atof(s)
except:
return None
def _atoi(s, atoi=string.atoi):
try:
return atoi(s)
except:
return None
def get_sequences(file):
if file[-3:] == '.gz':
ff = gzip.GzipFile(file)
else:
ff = open(file, 'r')
# read until we find a line with SEQRES card
line = ff.readline()
while line:
if line[:6] == 'SEQRES':
break
else:
line = ff.readline()
if not line: # no SEQRES records
return {}
sequences = {}
chain = line[11]
sequences[chain] = []
while line[:6] == 'SEQRES':
chain = line[11]
residues = string.split(line[19:71])
if not sequences.has_key(chain):
sequences[chain] = []
sequences[chain].extend(residues)
line = ff.readline()
return sequences
def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.strip):
return (ATOI(line[6:11]),
STRIP(line[12:16]),
line[16],
STRIP(line[17:21]),
line[21],
STRIP(line[22:26]),
line[26], # Insertion of residues (?)
ATOF(line[30:38]),
ATOF(line[38:46]),
ATOF(line[46:54]),
ATOF(line[54:60]),
ATOF(line[60:66]))
def atom_build(t, atom=Atom3d):
atm = atom(t[UP_X], t[UP_Y], t[UP_Z]);
atm.occ = t[UP_OCCUPANCY];
atm.bf = t[UP_TEMPFACTOR];
atm.name = t[UP_NAME];
atm.idx = t[UP_SERIAL];
atm.alt = t[UP_ALTLOC];
return atm
def _type_mol(mol):
if not len(mol):
return mol
for i in range(len(mol)):
chain = mol[i]
if is_protein(chain):
Chain = Protein
Residue = AminoAcid
else:
continue
new_chain = Chain(chain.name, present=chain.present, model=chain.model)
Append = new_chain.elements.append
for res in chain.elements:
new_res = Residue(res.name, idx=res.idx, icode=res.icode)
new_res.elements = res.elements[:]
Append(new_res)
if hasattr(res, 'het'):
new_res.het = 1
if hasattr(res, 'chain_het'):
new_res.chain_het = 1
mol[i] = new_chain
del chain
return mol
def is_protein(chain):
for res in chain.elements:
if res.name in RESIDUES:
return 1
#elif hasattr(res, 'het') and not hasattr(res, 'chain_het'):
# return 0
return 0
###########################
# End of protein objects and functions
###########################
def read_pdb(f, as_protein=0, as_rna=0, as_dna=0, all_models=0,
unpack=unpack_pdb_line, atom_build=atom_build):
"""read_pdb - read the entire contents of a PDB file as a molcule object
This function parses a PDB file and returns a heirarchic data structure
that can be used to browse atomic contents. The heirarchic data elements
are built on 'typed' lists. The first level is a list of 'chains',
where a chain can be non-specific or a protein, DNA, or RNA chain. A
chain (of any type) is a list of residues, and a residue is a list of
atoms. Atoms are defined as a full-blown Python object, with its own
member functions and data (including x, y, z). Residues and chains are
derived from the TypedList object, but can have their own member data
and functions--for example, the *pross* function is only available for
Protein chains, and chains in general have a public variable *name*
the described the SegID for that chain.
read_pdb takes the following arguments:
o f A file containing PDB data. If *f* is a string, it will
be checked for a '.gz' extension. Given that it contains
GZipped data, the file will be opened as a GZipFile and
parsed accordingly. If no '.gz' extension is present,
the file will be opened as a regular text file.
Alternatively, f can be an open file object with the
'readline' member function. If this is the case, the file
will not be closed upon exiting, and read_pdb will read
until the 'END' token is reached.
o as_protein Read the PDB as a protein. It will have the protein
specific member functions that allow calculation of torsion
angles, etc. By default this is false, and the type is
determined automatically from the residue types.
o as_rna Read the PDB as RNA. As above, this is false by default
and determined automatically.
o as_dna Read the PDB as DNA. As above, this is false by default
and determined automatically.
o all_models A boolean. The default is false. If true, all NMR models
will be read in as differing chains rather than just the
first one.
"""
if type(f) is type(''):
close = 1
if f[-3:] == '.gz':
inp = gzip.GzipFile(f)
else:
inp = open(f, 'r')
else:
inp = f
close = 0
try:
sequences = get_sequences(inp.name)
except AttributeError:
sequences = get_sequences(inp.filename)
Mol = molMol
Chain = molChain
Residue = molResidue
if as_protein:
Chain = Protein
Residue = AminoAcid
new_mol = Mol('')
nextline = inp.readline
while 1:
line = nextline()
if not line:
break
# Try to determine the resolution, in angstroms.
try:
if len(line) > 10 and line[:6] == 'REMARK' and line[9] == '2':
line = line[10:70].upper()
rpos = string.find(line, 'RESOLUTION.')
if rpos >= 0:
new_mol.resolution = float(line[rpos+11:].split()[0])
except:
pass
# Try to pick out expdata information, but don't attempt to
# parse the specific type.
try:
if line[:6] == 'EXPDTA':
for meth in line[10:].split(';'):
new_mol.method.append(meth.strip())
except:
pass
# Try to identify refinement parameters: Program name,
# free-R, and standard refinement factor.
try:
if len(line) > 10 and line[:6] == 'REMARK' and line[9] == '3':
line = line[10:70].upper()
if string.find(line, ':') >= 0:
get_val = lambda x: string.split(x, ':')[1].strip()
else:
get_val = lambda x: string.split(x)[0]
ppos = string.find(line, ' PROGRAM ')
rfpos = string.find(line, ' FREE R VALUE ')
rvpos = string.find(line, ' R VALUE ')
if ppos >= 0:
new_mol.rprog = get_val(line[ppos+11:])
if rfpos >= 0:
new_mol.rfree = float(get_val(line[rfpos+16:]))
if rvpos >= 0:
new_mol.rvalu = float(get_val(line[rvpos+11:]))
except:
pass
if line[:6] == 'COMPND':
if string.find(line, 'MOL_ID') <> -1: continue
new_mol.name = new_mol.name + string.strip(line[10:72]) + ' '
if line[:4] == 'ATOM' or line[:4] == 'HETA' or line[:5] == 'MODEL':
break
new_mol.name = string.strip(new_mol.name)
data = inp.readlines()
if line[:4] in ('ATOM', 'HETA', 'MODE'):
data.insert(0, line)
old_chain = None
old_res = None
old_icode = None
modnum = 0
for line in data:
key = line[:4]
if key == 'ATOM' or key == 'HETA':
t = unpack(line)
if t[UP_CHAINID] <> old_chain:
old_chain = t[UP_CHAINID]
new_chain = Chain(old_chain, present={}, model=modnum)
AppendResidue = new_chain.elements.append
AtomsPresent = new_chain.present
new_mol.append(new_chain)
old_res = None
old_icode = None
if t[UP_RESSEQ] <> old_res or t[UP_ICODE] <> old_icode:
old_res = t[UP_RESSEQ]
old_icode = t[UP_ICODE]
new_res = Residue(t[UP_RESNAME], idx=old_res, icode=old_icode)
#if key == 'HETA' and not t[UP_RESNAME] in \
# sequences.get(t[UP_CHAINID], (' ',)):
# new_res.het = 1
# All hetero groups are marked as hetero, but hetero
# residues that are part of the actual chain
# connectivity are marked as chain_het. These atoms
# can be 'unmarked as hetero' using the preserve_chain_hetero
# function.
if key == 'HETA':
if t[UP_RESNAME] in sequences.get(t[UP_CHAINID], (' ',)):
new_res.chain_het = 1
new_res.het = 1
AppendAtom = new_res.elements.append
AppendResidue(new_res)
if not AtomsPresent.has_key((old_res, old_icode)):
AtomsPresent[(old_res, old_icode)] = {}
if AtomsPresent[(old_res, old_icode)].has_key(t[UP_NAME]):
AtomsPresent[(old_res, old_icode)][t[UP_NAME]] = \
AtomsPresent[(old_res, old_icode)][t[UP_NAME]] + 1
else:
AtomsPresent[(old_res, old_icode)][t[UP_NAME]] = 1
AppendAtom(atom_build(t))
elif key == 'MODE':
if len(new_mol) > 0 and not all_models:
break
#new_chain = Chain(string.split(line)[1])
#AppendResidue = new_chain.elements.append
#new_mol.append(new_chain)
#old_chain = ' '
modnum = int(string.split(line)[1])
old_chain = None
old_res = None
old_icode = None
del data
if close:
inp.close()
if as_protein or as_dna or as_rna:
return new_mol
else:
return _type_mol(new_mol)
def _read_chain(f, as_protein=0, as_rna=0, as_dna=0, unpack=unpack_pdb_line,
atom_build = atom_build):
if as_protein:
Chain = Protein
Residue = AminoAcid
else:
Chain = molChain
Residue = molResidue
nextline = f.readline
new_chain = Chain('')
AppendResidue = new_chain.elements.append
old_chain = ' '
old_res = None
old_icode = None
while 1:
line = nextline()
if not line:
break
key = line[:4]
if key == 'ATOM' or key == 'HETA':
break
elif key == 'MODE':
new_chain.name = string.split(line)[1]
line = None
if line:
t = unpack(line)
new_res = Residue(t[UP_RESNAME], idx=t[UP_RESSEQ], icode=t[UP_ICODE])
AppendResidue(new_res)
old_res = t[UP_RESSEQ]
old_icode = t[UP_ICODE]
AppendAtom = new_res.elements.append
AppendAtom(atom_build(t))
ResidueHasAtom = new_res.atoms_with_name
while 1:
line = nextline()
if not line:
break
key = line[:4]
if key == 'ATOM' or key == 'HETA':
t = unpack(line)
if t[UP_RESSEQ] <> old_res or t[UP_ICODE] <> old_icode:
old_res = t[UP_RESSEQ]
old_icode = t[UP_ICODE]
new_res = Residue(old_res, idx=t[UP_RESSEQ], icode=t[UP_ICODE])
AppendResidue(new_res)
AppendAtom = new_res.elements.append
ResidueHasAtom = new_res.atoms_with_name
if not ResidueHasAtom(t[UP_NAME]):
AppendAtom(atom_build(t))
elif key[:3] in ('TER', 'END'):
break
if as_protein or as_dna or as_rna:
return new_chain
else:
return _type_mol([new_chain])[0]
##########################
class Protein(molChain):
_is_a_protein = 1
def clean(self):
"""clean() - remove residues if they lack N, CA, or C atoms"""
res = self.elements
for i in self.reverse_indices():
tmp = len(res[i].atoms_with_name('N', 'CA', 'C'))
if tmp <> 3:
del res[i]
def gaps(self):
"""gaps() - identify gaps in the chain
This function does a simple check to determine whether CA atoms are
contiguous in the peptide chain. First it, checks that CA atoms
exist for all residues. If that's okay, it checks to see if the
distance is less than 18**0.5 A. If either of these checks fail,
residues involved in a gap have their .gap attribute set to true.
"""
residues = self.elements
dlist = []
for i in xrange(len(self)-1):
ca1 = residues[i].atoms_with_name('CA')
if residues[i].name == 'ACE':
ca1 = residues[i].atoms_with_name('CH3')
ca2 = residues[i+1].atoms_with_name('CA')
if residues[i+1].name == 'NME':
ca2 = residues[i+1].atoms_with_name('CH3')
if not ca1 or not ca2:
if hasattr(residues[i+1], 'het'): continue
self[i].gap = 1
else:
d = ca1[0].sqr_distance(ca2[0])
if d > 18.0:
residues[i].gap = 1
elif d <= 0.1:
dlist.append(i+1)
dlist.reverse()
for i in dlist:
del residues[i]
def phi(self, i):
res = self.elements[i]
if i==0 or hasattr(self.elements[i-1], 'gap'):
return 999.99
try:
a, b, c = res.atoms_with_name('N', 'CA', 'C')
except:
return 999.99
try:
if self[i-1].name == 'ACE':
prev = self[i-1].atoms_with_name('CH3')[0]
else:
prev = self[i-1].atoms_with_name('C')[0]
except IndexError:
return 999.99
else:
return prev.torsion(a, b, c)
def psi(self, i):
res = self.elements[i]
if i >= len(self)-1 or hasattr(res, 'gap'):
return 999.99
try:
a, b, c = res.atoms_with_name('N', 'CA', 'C')
except:
return 999.99
try:
next = self[i+1].atoms_with_name('N')[0]
except IndexError:
return 999.99
else:
return a.torsion(b, c, next)
def omega(self, i):
"""omega(i) - calculate omega torsion for index i
This function calcualtes the value of the omega torsion for
index i. Note: this value is widely calculated using atoms
CA(i-1), C(i-1), N(i), and CA(i). These atoms are used for
this calculation. However, other LINUS programs use the fllowing
atoms: CA(i), C(i), N(i+1), CA(i+1). Forewarned is forearmed.
"""
res = self.elements[i]
# if i >= len(self)-1 or hasattr(res, 'gap'):
# return 999.99
# try:
# a, b = res.atoms_with_name('CA', 'C')
# except:
# return 999.99
# try:
# c, d = self[i+1].atoms_with_name('N', 'CA')
# except:
# return 999.99
if not i or hasattr(res, 'gap'):
return 999.99
try:
if self[i-1].name == 'ACE':
a, b = self[i-1].atoms_with_name('CH3', 'C')
else:
a, b = self[i-1].atoms_with_name('CA', 'C')
except:
return 999.99
try:
c, d = res.atoms_with_name('N', 'CA')
except:
return 999.99
return a.torsion(b, c, d)
def chi1(self, i):
res = self.elements[i]
atoms = CHI1_ATOMS.get(res.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(res.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi2(self, i):
res = self.elements[i]
atoms = CHI2_ATOMS.get(res.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(res.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi3(self, i):
res = self.elements[i]
atoms = CHI3_ATOMS.get(res.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(res.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi4(self, i):
res = self.elements[i]
atoms = CHI4_ATOMS.get(res.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(res.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def backbone_atoms(self, *ids):
if not len(ids):
ids = xrange(len(self))
bb_atoms = ('N', 'CA', 'C', 'O')
residues = []
Append = residues.append
res_class = res.__class__
Strip = string.strip
for i in ids:
res = self[i]
atoms = []
for atom in res:
if atom.name in bb_atoms: atoms.append(atom)
new = res_class(res.name)
res.elements = atoms
Append(res)
new_chain = self.__class__(self.name)
new_chain.elements = residues
return new_chain
def torsions(self, i=None, map=map):
if not i is None:
return self.phi(i), self.psi(i), self.omega(i), self.chi1(i),\
self.chi2(i), self.chi3(i), self.chi4(i)
else:
n = range(len(self))
return map(self.phi, n),\
map(self.psi, n),\
map(self.omega, n),\
map(self.chi1, n),\
map(self.chi2, n),\
map(self.chi3, n),\
map(self.chi4, n)
def pross(self, phi=None, psi=None, ome=None, mcodes=None):
return rc_ss(self, phi, psi, ome, mcodes)
def codes(self, phi=None, psi=None, ome=None, mcodes=None):
return rc_codes(self, phi, psi, ome, mcodes)
def type(self):
return 'protein'
def sequence(self, one=0):
n = self.num_residues()
seq = map(getattr, self.elements, ('name',)*n)
if one:
get_one = ONE_LETTER_CODES.get
seq = map(get_one, seq, 'X'*n)
return seq
class AminoAcid(molResidue):
def chi1(self):
atoms = CHI1_ATOMS.get(self.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(self.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi2(self):
atoms = CHI2_ATOMS.get(self.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(self.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi3(self):
atoms = CHI3_ATOMS.get(self.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(self.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def chi4(self):
atoms = CHI4_ATOMS.get(self.name, None)
if atoms is None:
return 999.99
try:
a, b, c, d = apply(self.atoms_with_name, atoms)
except:
return 999.99
else:
return a.torsion(b, c, d)
def assign_radii(self):
d_get = SASARAD[self.name].get
for atom in self.elements:
atom.radius = d_get(atom.name,0.0)
##########################
class PDBFile:
def __init__(self, filename):
self.filename = filename
self._openfile()
def _openfile(self):
if self.filename[-3:] == '.gz':
self.file = gzip.GzipFile(self.filename)
else:
self.file = open(self.filename)
def read(self, as_protein=0, as_rna=0, as_dna=0):
return read_pdb(self.file, as_protein, as_rna, as_dna)
def read_chain(self, as_protein=0, as_rna=0, as_dna=0):
return _read_chain(self.file, as_protein, as_rna, as_dna)
def run(file,mcode):
mol = read_pdb(file)
mol.delete_hetero()
fmt = "%5s %3s %s %s %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f %8.2f\n"
# Default is to screen, change here if file output wanted
# angfile = open('angles.dat', 'w')
angfile = sys.stdout
for chain in mol:
if chain.type() <> 'protein': continue
chain.gaps()
angfile.write('Chain: %s\n' % chain.name)
angfile.write(' SS MS phi psi omega chi1 chi2 chi3 chi4\n')
phi, psi, ome, chi1, chi2, chi3, chi4 = chain.torsions()
phi, psi, ome, ss = chain.pross(phi, psi, ome)
pos = 0
for res in chain.elements:
ms = res_rc(phi[pos], psi[pos],mcodes=mcode)
angfile.write( fmt % (res.idx, res.name, ss[pos], ms, phi[pos], psi[pos], ome[pos],
chi1[pos], chi2[pos], chi3[pos], chi4[pos]))
pos = pos + 1
# angfile.close()
if __name__ == "__main__":
import sys
if len(sys.argv) < 1:
print USAGE
sys.exit()
# Default is finegrained mesostates
if len(sys.argv) < 3:
mcode = 'fgmeso'
else:
mcode = sys.argv[2]
file = sys.argv[1]
run(file, mcode)
```
#### File: opengltk/extent/utillib.py
```python
import _utillib
import new
new_instancemethod = new.instancemethod
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import types
try:
_object = types.ObjectType
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
del types
void_void_array_get = _utillib.void_void_array_get
void_void_dim = _utillib.void_void_dim
void_void_NULL = _utillib.void_void_NULL
void_GLenum_array_get = _utillib.void_GLenum_array_get
void_GLenum_dim = _utillib.void_GLenum_dim
void_GLenum_NULL = _utillib.void_GLenum_NULL
void_int_array_get = _utillib.void_int_array_get
void_int_dim = _utillib.void_int_dim
void_int_NULL = _utillib.void_int_NULL
void_int_int_array_get = _utillib.void_int_int_array_get
void_int_int_dim = _utillib.void_int_int_dim
void_int_int_NULL = _utillib.void_int_int_NULL
void_int_int_int_array_get = _utillib.void_int_int_int_array_get
void_int_int_int_dim = _utillib.void_int_int_int_dim
void_int_int_int_NULL = _utillib.void_int_int_int_NULL
void_int_int_int_int_array_get = _utillib.void_int_int_int_int_array_get
void_int_int_int_int_dim = _utillib.void_int_int_int_int_dim
void_int_int_int_int_NULL = _utillib.void_int_int_int_int_NULL
void_unsignedchar_int_int_array_get = _utillib.void_unsignedchar_int_int_array_get
void_unsignedchar_int_int_dim = _utillib.void_unsignedchar_int_int_dim
void_unsignedchar_int_int_NULL = _utillib.void_unsignedchar_int_int_NULL
void_unsignedint_int_int_int_array_get = _utillib.void_unsignedint_int_int_int_array_get
void_unsignedint_int_int_int_dim = _utillib.void_unsignedint_int_int_int_dim
void_unsignedint_int_int_int_NULL = _utillib.void_unsignedint_int_int_int_NULL
void_int_voidstar_array_get = _utillib.void_int_voidstar_array_get
void_int_voidstar_dim = _utillib.void_int_voidstar_dim
void_int_voidstar_NULL = _utillib.void_int_voidstar_NULL
sizeof_GLbitfield = _utillib.sizeof_GLbitfield
sizeof_GLboolean = _utillib.sizeof_GLboolean
sizeof_GLbyte = _utillib.sizeof_GLbyte
sizeof_GLclampd = _utillib.sizeof_GLclampd
sizeof_GLclampf = _utillib.sizeof_GLclampf
sizeof_GLdouble = _utillib.sizeof_GLdouble
sizeof_GLenum = _utillib.sizeof_GLenum
sizeof_GLfloat = _utillib.sizeof_GLfloat
sizeof_GLint = _utillib.sizeof_GLint
sizeof_GLshort = _utillib.sizeof_GLshort
sizeof_GLsizei = _utillib.sizeof_GLsizei
sizeof_GLubyte = _utillib.sizeof_GLubyte
sizeof_GLuint = _utillib.sizeof_GLuint
sizeof_GLushort = _utillib.sizeof_GLushort
glCleanRotMat = _utillib.glCleanRotMat
extractedGlutSolidSphere = _utillib.extractedGlutSolidSphere
solidCylinder = _utillib.solidCylinder
namedPoints = _utillib.namedPoints
glDrawSphereSet = _utillib.glDrawSphereSet
glDrawCylinderSet = _utillib.glDrawCylinderSet
glDrawIndexedGeom = _utillib.glDrawIndexedGeom
triangleNormalsPerFace = _utillib.triangleNormalsPerFace
triangleNormalsPerVertex = _utillib.triangleNormalsPerVertex
triangleNormalsBoth = _utillib.triangleNormalsBoth
def glTriangleNormals(vertices, triangles, mode = "PER_FACE" ):
if mode == "PER_FACE":
return triangleNormalsPerFace(vertices, triangles)
elif mode == "PER_VERTEX":
return triangleNormalsPerVertex(vertices, triangles)
elif mode == "BOTH":
return triangleNormalsBoth(vertices, triangles)
attachCurrentThread = _utillib.attachCurrentThread
detachCurrentThread = _utillib.detachCurrentThread
attachedThread = _utillib.attachedThread
glTrackball = _utillib.glTrackball
```
#### File: MGLToolsPckgs/Pmv/APBSCommands.py
```python
import string, os, pickle, sys, threading, select, time, shutil
import numpy.oldnumeric as Numeric
import Tkinter, Pmw
from mglutil.gui.InputForm.Tk.gui import InputFormDescr, InputForm, \
CallBackFunction
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import LoadButton, \
SaveButton, SliderWidget, ExtendedSliderWidget
from mglutil.gui.BasicWidgets.Tk.progressBar import ProgressBar
from mglutil.util.callback import CallBackFunction
from mglutil.util.misc import ensureFontCase
from Pmv.mvCommand import MVCommand
from ViewerFramework.VFCommand import CommandGUI
from MolKit.pdbParser import PQRParser
from MolKit.molecule import Atom, MoleculeSet
import MolKit
import tkMessageBox
global APBS_ssl
APBS_ssl = False # Flags whether to run Secured APBS Web Services
from mglutil.util.packageFilePath import getResourceFolderWithVersion
ResourceFolder = getResourceFolderWithVersion()
#Proxy retrieved from the GAMA service
if ResourceFolder is not None:
APBS_proxy = ResourceFolder + os.sep + 'ws' + os.sep + 'proxy_gama'
else:
APBS_proxy = None
def closestMatch(value, _set):
"""Returns an element of the set that is closest to the supplied value"""
a = 0
element = _set[0]
while(a<len(_set)):
if((_set[a]-value)*(_set[a]-value)<(element-value)*(element-value)):
element=_set[a]
a = a + 1
return element
PROFILES = ('Default',)
from MolKit.APBSParameters import *
try:
import sys, webbrowser, urllib, httplib
APBSservicesFound = True
from mglutil.web.services.AppService_client import AppServiceLocator, launchJobRequest, \
getOutputsRequest, queryStatusRequest
from mglutil.web.services.AppService_types import ns0
class APBSCmdToWebService:
"""
This object takes an APBSParams instance the Pmv.APBSCommands.py
"""
def __init__(self, params, mol_1, mol_2 = None, _complex = None):
"""
Constructor for class APBSCmdToWebService
params is APBSPrams instance
mol_1,mol_2 and complex are molecule instances
Parallel_flag used to indicate parallel mode
npx npy npz are number of processors in x-, y- and z-directions
ofrac is the amount of overlap between processor meshes
"""
# set the parameters for the request
self.req = launchJobRequest()
inputFiles = []
input_molecule1 = ns0.InputFileType_Def('inputFile')
input_molecule1._name = os.path.split(params.molecule1Path)[-1]
input_molecule1._contents = open(params.molecule1Path).read()
inputFiles.append(input_molecule1)
if mol_2:
input_molecule2 = ns0.InputFileType_Def()
input_molecule2._name = os.path.split(params.molecule2Path)[-1]
input_molecule2._contents = open(params.molecule2Path).read()
inputFiles.append(input_molecule2)
if not _complex:
import warnings
warnings.warn("Complex is missing!")
return
input_complex = ns0.InputFileType_Def()
input_complex._name = os.path.split(params.complexPath)[-1]
input_complex._contents = open(params.complexPath).read()
inputFiles.append(input_complex)
apbs_input = "apbs-input-file.apbs"
apbs_input_path = params.projectFolder + os.path.sep + apbs_input
params.molecule1Path = os.path.basename(params.molecule1Path)
if mol_2:
params.molecule2Path = os.path.basename(params.molecule2Path)
params.complexPath = os.path.basename(params.complexPath)
params.SaveAPBSInput(apbs_input_path)
input_apbs = ns0.InputFileType_Def('inputFile')
input_apbs._name = apbs_input
input_apbs._contents = open(apbs_input_path).read()
inputFiles.append(input_apbs)
self.req._argList = apbs_input
self.req._inputFile = inputFiles
def run(self, portAddress):
"""Runs APBS through Web Services"""
# retrieve a reference to the remote port
import httplib
self.appLocator = AppServiceLocator()
global APBS_ssl
if APBS_ssl:
self.appServicePort = self.appLocator.getAppServicePortType(
portAddress,
ssl = 1, cert_file = APBS_proxy,
key_file = APBS_proxy, transport=httplib.HTTPSConnection)
else:
self.appServicePort = self.appLocator.getAppServicePort(
portAddress)
# make remote invocation
resp = self.appServicePort.launchJob(self.req)
self.JobID = resp._jobID
return resp
except:
APBSservicesFound = False
state_GUI = 'disabled'
blinker = 0
class APBSSetup(MVCommand):
"""APBSSetup setups all necessary parameters for Adaptive Poisson-Boltzmann
Solver (APBS)\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSSetup
\nCommand name : APBSSetup
\nSynopsis:\n
None <--- APBSSetup(**kw)\n
\nDescription:\n
Pmv-->APBS-->Setup creates Pmw.NoteBook with three tabbed pages:\n
Calculation, Grid and Physics.
Calculation page contains the following groups:
Mathematics - is used to setup up Calculation type (kw['calculationType']),
Poisson-Boltzmann equation type (kw['pbeType']), Boundary conditions
(kw['boundaryConditions']),Charge discretization (kw['chargeDiscretization'])
Surface-based coefficients (kw['surfaceCalculation']), and Spline window in
Angstroms (kw['splineWindow'], present only when surfaceCalculation is set to
'Spline-based')
Molecules - allows to select molecule(s)
Output - sets output file formats
Profiles - is used to add, remove, load, save and run different profiles
APBS Web Services - is present only when APBSService_services module is
installed. It allows APBS to be run remotely
Grid page contains the following groups:
General - lets you select number of grid point along X, Y and Z directions
Coarse Grid - allows changing the length and the center of the coarse grid.
It also allows to autoceter, autosize as well as visualize the coarse grid.
Fine Grid - dos the same for the fine grid
System Resources - shows total grid point and memory to be allocated for APBS
Grid page contains the following groups:
Parameters - allows to change protein and solevent dielectric constants,
solvent radius and system temperature
Ions - allows to add and/or remove different ions
"""
def __init__(self, func=None):
"""Constructor for class APBSSetup"""
MVCommand.__init__(self)
self.params = APBSParams()
self.cmp_APBSParams = APBSParams()
self.flag_grid_changed = False
try:
self.RememberLogin_var = Tkinter.BooleanVar()
self.salt_var =Tkinter.BooleanVar()
self.salt_var.set(1)
except:
self.RememberLogin_var = False
self.salt_var = True
def doit(self,*args, **kw):
"""doit function"""
self.cmp_APBSParams.Set(**kw)
def __call__(self, **kw):
"""Call method"""
self.params.Set(**kw)
self.refreshAll()
def onAddObjectToViewer(self, object):
"""Called when object is added to viewer"""
if self.cmdForms.has_key('default'):
try:
ebn = self.cmdForms['moleculeSelect'].descr.entryByName
w = ebn['moleculeListSelect']['widget']
molNames = self.vf.Mols.name
w.setlist(molNames)
descr = self.cmdForms['default'].descr
descr.entryByName['APBSservicesLabel1']['widget'].\
configure(text = "")
descr.entryByName['APBSservicesLabel2']['widget'].\
configure(text = "")
descr.entryByName['APBSservicesLabel3']['widget'].\
configure(text = "")
descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "")
except KeyError:
pass
if hasattr(object,'chains'):
object.APBSParams = {}
# object.APBSParams['Default'] = APBSParams()
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.cmdForms.has_key('default'):
try:
ebn = self.cmdForms['moleculeSelect'].descr.entryByName
w = ebn['moleculeListSelect']['widget']
molNames = self.vf.Mols.name
w.setlist(molNames)
descr = self.cmdForms['default'].descr
if hasattr(object,'chains'):
molName = object.name
if molName in descr.entryByName['molecule1']['widget'].get():
descr.entryByName['molecule1']['widget'].setentry('')
if molName in descr.entryByName['molecule2']['widget'].get():
descr.entryByName['molecule2']['widget'].setentry('')
if molName in descr.entryByName['complex']['widget'].get():
descr.entryByName['complex']['widget'].setentry('')
except KeyError:
pass
def onAddCmdToViewer(self):
"""Called when APBSSetup are added to viewer"""
from DejaVu.bitPatterns import patternList
from opengltk.OpenGL import GL
from DejaVu import viewerConst
from DejaVu.Box import Box
face=((0,3,2,1),(3,7,6,2),(7,4,5,6),(0,1,5,4),(1,2,6,5),(0,4,7,3))
coords=((1,1,-1),(-1,1,-1),(-1,-1,-1),(1,-1,-1),(1,1,1),(-1,1,1),
(-1,-1,1),(1,-1,1))
materials=((0,0,1),(0,1,0),(0,0,1),(0,1,0),(1,0,0),(1,0,0))
box=Box('CoarseAPBSbox', materials=materials, vertices=coords,
faces=face, listed=0, inheritMaterial=0)
box.Set(frontPolyMode=GL.GL_FILL, tagModified=False)
box.polygonstipple.Set(pattern=patternList[0])
box.Set(matBind=viewerConst.PER_PART, visible=0,
inheritStipplePolygons=0, shading=GL.GL_FLAT, inheritShading=0,
stipplePolygons=1, frontPolyMode=GL.GL_FILL,
tagModified=False)
box.oldFPM = None
self.coarseBox = box
if self.vf.hasGui:
self.vf.GUI.VIEWER.AddObject(box, redo=0)
box=Box('FineAPBSbox', materials=materials, vertices=coords,
faces=face, listed=0, inheritMaterial=0)
box.polygonstipple.Set(pattern=patternList[3])
box.Set(matBind=viewerConst.PER_PART, visible=0,
inheritStipplePolygons=0, shading=GL.GL_FLAT,
inheritShading=0, stipplePolygons=1,
frontPolyMode=GL.GL_FILL, tagModified=False)
box.oldFPM = None
self.fineBox = box
if self.vf.hasGui:
self.vf.GUI.VIEWER.AddObject(box, redo=0)
def guiCallback(self):
"""GUI callback for APBSSetup"""
self.refreshAll()
mainform = self.showForm('default', modal=0, blocking=1,
initFunc=self.refreshAll)
if mainform:
# self.paramUpdateAll()
tmp_dict = {}
for key, value in self.params.__dict__.items():
if self.params.__dict__[key] != \
self.cmp_APBSParams.__dict__[key]:
if type(value) is types.TupleType:
value = value[0]
if key == 'ions':
for ion in value:
self.vf.message("self.APBSSetup.params.ions.\
append(Pmv.APBSCommands.Ion("+ion.toString()+"))")
self.vf.log("self.APBSSetup.params.ions.\
append(Pmv.APBSCommands.Ion("+ion.toString()+"))")
self.cmp_APBSParams.ions = self.params.ions
continue
tmp_dict[key] = value
if len(tmp_dict) != 0:
self.doitWrapper(**tmp_dict)
def dismiss(self, event = None):
"""Withdraws 'default' GUI"""
self.cmdForms['default'].withdraw()
def coarseResolutionX(self):
"""Returns coarse grid resolution in X direction"""
return self.params.coarseLengthX/float(self.params.gridPointsX-1)
def coarseResolutionY(self):
"""Returns coarse grid resolution in Y direction"""
return self.params.coarseLengthY/float(self.params.gridPointsY-1)
def coarseResolutionZ(self):
"""Returns coarse grid resolution in Z direction"""
return self.params.coarseLengthZ/float(self.params.gridPointsZ-1)
def fineResolutionX(self):
"""Returns fine grid resolution in X direction"""
return self.params.fineLengthX/float(self.params.gridPointsX-1)
def fineResolutionY(self):
"""Returns fine grid resolution in Y direction"""
return self.params.fineLengthY/float(self.params.gridPointsY-1)
def fineResolutionZ(self):
"""Returns fine grid resolution in Z direction"""
return self.params.fineLengthZ/float(self.params.gridPointsZ-1)
def memoryToBeAllocated(self):
"""Returns memory to be allocated for APBS run"""
return self.params.MEGABYTES_PER_GRID_POINT*self.totalGridPoints()
def totalGridPoints(self):
"""Returns total number of grid points"""
return self.params.gridPointsX*self.params.gridPointsY*\
self.params.gridPointsZ
def autocenterCoarseGrid(self):
"""Autocenters coarse grid"""
coords = self.getCoords()
center=(Numeric.maximum.reduce(coords)+Numeric.minimum.reduce(coords))*0.5
center = center.tolist()
self.params.coarseCenterX = round(center[0],4)
self.params.coarseCenterY = round(center[1],4)
self.params.coarseCenterZ = round(center[2],4)
self.refreshGridPage()
def autosizeCoarseGrid(self):
"""Autosizes coarse grid"""
coords = self.getCoords()
length = Numeric.maximum.reduce(coords) - Numeric.minimum.reduce(coords)
self.params.coarseLengthX = self.params.CFAC*(length.tolist())[0] + 10.
self.params.coarseLengthY = self.params.CFAC*(length.tolist())[1] + 10.
self.params.coarseLengthZ = self.params.CFAC*(length.tolist())[2] + 10.
self.refreshGridPage()
def autocenterFineGrid(self):
"""Autocenters fine grid"""
coords = self.getCoords()
center=(Numeric.maximum.reduce(coords)+Numeric.minimum.reduce(coords))*0.5
center = center.tolist()
self.params.fineCenterX = round(center[0],4)
self.params.fineCenterY = round(center[1],4)
self.params.fineCenterZ = round(center[2],4)
self.refreshGridPage()
def autosizeFineGrid(self):
"""Autosizes fine grid"""
coords = self.getCoords()
length=Numeric.maximum.reduce(coords)-Numeric.minimum.reduce(coords)
self.params.fineLengthX = (length.tolist())[0] + 10.0
self.params.fineLengthY = (length.tolist())[1] + 10.0
self.params.fineLengthZ = (length.tolist())[2] + 10.0
self.refreshGridPage()
def getCoords(self):
"""Returns coordinates of atoms included in calculation"""
if not hasattr(self, 'mol1Name'): return [[0,0,0]]
mol = self.vf.getMolFromName(self.mol1Name)
coords = mol.findType(Atom).coords
if self.params.calculationType == 'Binding energy':
if hasattr(self, 'mol2Name'):
mol = self.vf.getMolFromName(self.mol2Name)
if mol:
coords += mol.findType(Atom).coords
if hasattr(self, 'complexName'):
mol = self.vf.getMolFromName(self.complexName)
if mol:
coords += mol.findType(Atom).coords
return coords
# Callbacks
def refreshCalculationPage(self):
"""Refreshes calculation page"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
if(self.params.calculationType=='Binding energy'):
apply(descr.entryByName['molecule2Select']['widget'].grid,
(), descr.entryByName['molecule2Select']['gridcfg'])
apply(descr.entryByName['molecule2']['widget'].grid, (),
descr.entryByName['molecule2']['gridcfg'])
apply(descr.entryByName['complexSelect']['widget'].grid, (),
descr.entryByName['complexSelect']['gridcfg'])
apply(descr.entryByName['complex']['widget'].grid, (),
descr.entryByName['complex']['gridcfg'])
#self.params.energyOutput = 'Total'
elif(self.params.calculationType=='Solvation energy'):
descr.entryByName['molecule2Select']['widget'].grid_forget()
descr.entryByName['molecule2']['widget'].grid_forget()
descr.entryByName['complexSelect']['widget'].grid_forget()
descr.entryByName['complex']['widget'].grid_forget()
#self.params.energyOutput = 'Total'
elif(self.params.calculationType=='Electrostatic potential'):
descr.entryByName['molecule2Select']['widget'].grid_forget()
descr.entryByName['molecule2']['widget'].grid_forget()
descr.entryByName['complexSelect']['widget'].grid_forget()
descr.entryByName['complex']['widget'].grid_forget()
descr.entryByName['calculationType']['widget'].\
selectitem(self.params.calculationType)
descr.entryByName['pbeType']['widget'].\
selectitem(self.params.pbeType)
descr.entryByName['boundaryConditions']['widget'].\
selectitem(self.params.boundaryConditions)
descr.entryByName['chargeDiscretization']['widget'].\
selectitem(self.params.chargeDiscretization)
descr.entryByName['surfaceCalculation']['widget'].\
selectitem(self.params.surfaceCalculation)
descr.entryByName['sdens']['widget'].setentry(self.params.sdens)
descr.entryByName['splineWindow']['widget'].\
setentry(self.params.splineWindow)
if self.params.surfaceCalculation == 'Cubic B-spline' or \
self.params.surfaceCalculation == '7th Order Polynomial':
apply(descr.entryByName['splineWindowLabel']['widget'].grid,
(), descr.entryByName['splineWindowLabel']['gridcfg'])
apply(descr.entryByName['splineWindow']['widget'].grid, (),
descr.entryByName['splineWindow']['gridcfg'])
descr.entryByName['sdensLabel']['widget'].grid_forget()
descr.entryByName['sdens']['widget'].grid_forget()
else:
apply(descr.entryByName['sdensLabel']['widget'].grid,
(), descr.entryByName['sdensLabel']['gridcfg'])
apply(descr.entryByName['sdens']['widget'].grid, (),
descr.entryByName['sdens']['gridcfg'])
descr.entryByName['splineWindowLabel']['widget'].grid_forget()
descr.entryByName['splineWindow']['widget'].grid_forget()
descr.entryByName['molecule1']['widget'].\
setentry(self.params.molecule1Path)
descr.entryByName['molecule2']['widget'].\
setentry(self.params.molecule2Path)
descr.entryByName['complex']['widget'].\
setentry(self.params.complexPath)
descr.entryByName['energyOutput']['widget'].\
selectitem(self.params.energyOutput)
descr.entryByName['forceOutput']['widget'].\
selectitem(self.params.forceOutput)
descr.entryByName['forceOutput']['widget'].\
selectitem(self.params.forceOutput)
descr.entryByName['Profiles']['widget'].\
selectitem(self.params.name)
def testCalculationWidgets(self):
"""Tests calculation widgets"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
if(descr.entryByName['splineWindow']['widget'].get() == ''):
self.errorMsg = 'You must enter a spline window value.'
errorform = self.showForm('error',modal=1,blocking=1,force = 1)
return 1
return 0
def calculationParamUpdate(self, selectItem=0):
"""Updates calculation parameters"""
if self.cmdForms.has_key('default'):
if selectItem == 'Binding energy':
self.params.calculationType = 'Binding energy'
self.refreshCalculationPage()
return
descr = self.cmdForms['default'].descr
# Prevent forcing a particular calculation type on the user
self.params.calculationType = descr.entryByName\
['calculationType']['widget'].get()
if self.testCalculationWidgets()==0:
self.params.calculationType = descr.entryByName\
['calculationType']['widget'].get()
self.params.pbeType = descr.entryByName['pbeType']['widget'].\
get()
self.params.boundaryConditions = descr.entryByName\
['boundaryConditions']['widget'].get()
self.params.chargeDiscretization = descr.entryByName\
['chargeDiscretization']['widget'].get()
self.params.surfaceCalculation = descr.entryByName\
['surfaceCalculation']['widget'].get()
self.params.sdens = float(descr.entryByName['sdens']['widget'].\
get())
self.params.splineWindow = float(descr.entryByName\
['splineWindow']['widget'].get())
self.params.molecule1Path = descr.entryByName['molecule1']\
['widget'].get()
self.params.molecule2Path = descr.entryByName['molecule2']\
['widget'].get()
self.params.complexPath = descr.entryByName['complex']\
['widget'].get()
self.params.energyOutput = descr.entryByName['energyOutput']\
['widget'].get()
self.params.forceOutput = descr.entryByName['forceOutput']\
['widget'].get()
self.params.name = descr.entryByName['Profiles']['widget'].\
get()
else:
return "ERROR"
self.refreshCalculationPage()
def refreshGridPage(self):
"""Refreshes grid page"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
descr.entryByName['gridPointsX']['widget'].set(closestMatch(self.
params.gridPointsX, self.params.GRID_VALUES), update = 0)
descr.entryByName['gridPointsY']['widget'].set(closestMatch(self.
params.gridPointsY, self.params.GRID_VALUES), update = 0)
descr.entryByName['gridPointsZ']['widget'].set(closestMatch(self.
params.gridPointsZ, self.params.GRID_VALUES), update = 0)
descr.entryByName['coarseLengthX']['widget'].set(self.params.
coarseLengthX, update = 0)
descr.entryByName['coarseLengthY']['widget'].set(self.params.
coarseLengthY, update = 0)
descr.entryByName['coarseLengthZ']['widget'].set(self.params.
coarseLengthZ, update = 0)
descr.entryByName['coarseCenterX']['widget'].set(self.params.
coarseCenterX, update = 0)
descr.entryByName['coarseCenterY']['widget'].set(self.params.
coarseCenterY, update = 0)
descr.entryByName['coarseCenterZ']['widget'].set(self.params.
coarseCenterZ, update = 0)
descr.entryByName['coarseResolutionX']['widget'].configure(text =
"%5.3f"%self.coarseResolutionX())
descr.entryByName['coarseResolutionY']['widget'].configure(text =
"%5.3f"%self.coarseResolutionY())
descr.entryByName['coarseResolutionZ']['widget'].configure(text =
"%5.3f"%self.coarseResolutionZ())
descr.entryByName['fineLengthX']['widget'].set(self.params.
fineLengthX, update = 0)
descr.entryByName['fineLengthY']['widget'].set(self.params.
fineLengthY, update = 0)
descr.entryByName['fineLengthZ']['widget'].set(self.params.
fineLengthZ, update = 0)
descr.entryByName['fineCenterX']['widget'].set(self.params.
fineCenterX, update = 0)
descr.entryByName['fineCenterY']['widget'].set(self.
params.fineCenterY, update = 0)
descr.entryByName['fineCenterZ']['widget'].set(self.params.
fineCenterZ, update = 0)
descr.entryByName['fineResolutionX']['widget'].configure(text =
"%5.3f"%self.fineResolutionX())
descr.entryByName['fineResolutionY']['widget'].configure(text =
"%5.3f"%self.fineResolutionY())
descr.entryByName['fineResolutionZ']['widget'].configure(text =
"%5.3f"%self.fineResolutionZ())
descr.entryByName['gridPointsNumberLabel']['widget'].\
configure(text = "%d"%self.totalGridPoints())
descr.entryByName['mallocSizeLabel']['widget'].configure(text =
"%5.3f"%self.memoryToBeAllocated())
self.coarseBox.Set(visible = descr.\
entryByName['showCoarseGrid']['wcfg']['variable'].get(),
xside = self.params.coarseLengthX,
yside = self.params.coarseLengthY,
zside = self.params.coarseLengthZ,
center = [self.params.coarseCenterX, self.params.coarseCenterY,
self.params.coarseCenterZ], tagModified=False)
self.fineBox.Set(visible = descr.\
entryByName['showFineGrid']['wcfg']['variable'].get(),
xside = self.params.fineLengthX,yside = self.params.fineLengthY,
zside = self.params.fineLengthZ,
center = [self.params.fineCenterX, self.params.fineCenterY,
self.params.fineCenterZ], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def testGridWidgets(self):
"""Tests grid widget"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
#Boundary check: make sure coarse grid encloses fine grid
ccx = descr.entryByName['coarseCenterX']['widget'].value
ccy = descr.entryByName['coarseCenterY']['widget'].value
ccz = descr.entryByName['coarseCenterZ']['widget'].value
clx = descr.entryByName['coarseLengthX']['widget'].value/2
cly = descr.entryByName['coarseLengthY']['widget'].value/2
clz = descr.entryByName['coarseLengthZ']['widget'].value/2
fcx = descr.entryByName['fineCenterX']['widget'].value
fcy = descr.entryByName['fineCenterY']['widget'].value
fcz = descr.entryByName['fineCenterZ']['widget'].value
flx = descr.entryByName['fineLengthX']['widget'].value/2
fly = descr.entryByName['fineLengthY']['widget'].value/2
flz = descr.entryByName['fineLengthZ']['widget'].value/2
if (fcx+flx>ccx+clx) or (fcx-flx<ccx-clx) or (fcy+fly>ccy+cly) or \
(fcy-fly<ccy-cly) or (fcz+flz>ccz+clz) or (fcz-flz<ccz-clz):
self.errorMsg = 'The coarse grid must enclose the fine grid.'
errorform = self.showForm('error',modal=1,blocking=1,force=1)
return 1
return 0
else :
#Boundary check: make sure coarse grid encloses fine grid
ccx = self.params.coarseCenterX
ccy = self.params.coarseCenterY
ccz = self.params.coarseCenterZ
clx = self.params.coarseLengthX
cly = self.params.coarseLengthY
clz = self.params.coarseLengthZ
fcx = self.params.fineCenterX
fcy = self.params.fineCenterY
fcz = self.params.fineCenterZ
flx = self.params.fineLengthX
fly = self.params.fineLengthY
flz = self.params.fineLengthZ
if (fcx+flx>ccx+clx) or (fcx-flx<ccx-clx) or (fcy+fly>ccy+cly) or \
(fcy-fly<ccy-cly) or (fcz+flz>ccz+clz) or (fcz-flz<ccz-clz):
self.errorMsg = 'The coarse grid must enclose the fine grid.'
errorform = self.showForm('error',modal=1,blocking=1,force=1)
return 1
return 0
def gridParamUpdate(self, selectItem=0):
"""Updates grid parameters. Returns "ERROR" is failed"""
if self.testGridWidgets() == 0:
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
self.params.gridPointsX = closestMatch(descr.entryByName
['gridPointsX']['widget'].get(), self.params.GRID_VALUES)
self.params.gridPointsY = closestMatch(descr.entryByName
['gridPointsY']['widget'].get(), self.params.GRID_VALUES)
self.params.gridPointsZ = closestMatch(descr.entryByName
['gridPointsZ']['widget'].get(), self.params.GRID_VALUES)
self.params.coarseLengthX = descr.entryByName['coarseLengthX']\
['widget'].value
self.params.coarseLengthY = descr.entryByName['coarseLengthY']\
['widget'].value
self.params.coarseLengthZ = descr.entryByName['coarseLengthZ']\
['widget'].value
self.params.coarseCenterX = descr.entryByName['coarseCenterX']\
['widget'].value
self.params.coarseCenterY = descr.entryByName['coarseCenterY']\
['widget'].value
self.params.coarseCenterZ = descr.entryByName['coarseCenterZ']\
['widget'].value
self.params.fineLengthX = descr.entryByName['fineLengthX']\
['widget'].value
self.params.fineLengthY = descr.entryByName['fineLengthY']\
['widget'].value
self.params.fineLengthZ = descr.entryByName['fineLengthZ']\
['widget'].value
self.params.fineCenterX = descr.entryByName['fineCenterX']\
['widget'].value
self.params.fineCenterY = descr.entryByName['fineCenterY']\
['widget'].value
self.params.fineCenterZ = descr.entryByName['fineCenterZ']\
['widget'].value
self.flag_grid_changed = True
else:
return "ERROR"
self.refreshGridPage()
def refreshPhysicsPage(self):
"""Refreshes physics page"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
descr.entryByName['proteinDielectric']['widget'].\
setentry(self.params.proteinDielectric)
descr.entryByName['solventDielectric']['widget'].\
setentry(self.params.solventDielectric)
descr.entryByName['solventRadius']['widget'].\
setentry(self.params.solventRadius)
descr.entryByName['systemTemperature']['widget'].\
setentry(self.params.systemTemperature)
descr.entryByName['ionsList']['widget'].clear()
for i in range(len(self.params.ions)):
descr.entryByName['ionsList']['widget'].\
insert('end', self.params.ions[i].toString())
if self.params.saltConcentration:
self.salt_var.set(1)
else:
self.salt_var.set(0)
def testPhysicsWidgets(self):
"""Tests physics widget"""
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
if(descr.entryByName['proteinDielectric']['widget'].get() == ''):
self.errorMsg = 'You must enter a protein dielectric\
value.'
errorform = self.showForm('error', modal=1, blocking=1,
force = 1)
return 1
if(descr.entryByName['solventDielectric']['widget'].get() == ''):
self.errorMsg = 'You must enter a solvent dielectric\
value.'
errorform = self.showForm('error', modal=1, blocking=1,
force = 1)
return 1
if(descr.entryByName['solventRadius']['widget'].get() == ''):
self.errorMsg = 'You must enter a solvent radius value.'
errorform = self.showForm('error', modal=1, blocking=1,
force = 1)
return 1
if(descr.entryByName['systemTemperature']['widget'].get() == ''):
self.errorMsg = 'You must enter a system temperature \
value.'
errorform = self.showForm('error', modal=1, blocking=1,
force = 1)
return 1
return 0
def physicsParamUpdate(self):
"""Updates physics parameter. Returns "ERROR" is failed"""
if self.testPhysicsWidgets() != 1:
if self.cmdForms.has_key('default'):
descr = self.cmdForms['default'].descr
self.params.proteinDielectric = float(descr.entryByName\
['proteinDielectric']['widget'].get())
self.params.solventDielectric = float(descr.entryByName\
['solventDielectric']['widget'].get())
self.params.solventRadius = float(descr.entryByName\
['solventRadius']['widget'].get())
self.params.systemTemperature = float(descr.entryByName\
['systemTemperature']['widget'].get())
salt = self.salt_var.get()
if salt:
self.params.saltConcentration = float(descr.entryByName\
['saltConcentration']['widget'].get())
else:
self.params.saltConcentration = 0
else:
return "ERROR"
self.refreshPhysicsPage()
def refreshAll(self,cmdForm = None):
"""Refreshes calculation, grid and physics pages"""
if cmdForm:
self.cmdForms['default'] = cmdForm
descr = cmdForm.descr
if APBSservicesFound:
ResourceFolder = getResourceFolderWithVersion()
if os.path.isdir(ResourceFolder):
pass
else:
os.mkdir(ResourceFolder)
self.rc_apbs = ResourceFolder + os.sep + "ws"
if os.path.isdir(self.rc_apbs):
pass
else:
os.mkdir(self.rc_apbs)
self.rc_apbs += os.sep + "rc_apbs"
if not os.path.exists(self.rc_apbs):
open(self.rc_apbs,'w')
else:
file = open(self.rc_apbs)
text = file.read()
text = text.split()
for line in text:
tmp_line = line.split('User:')
if len(tmp_line) > 1:
descr.entryByName['UserName_Entry']['wcfg']\
['textvariable'].set(tmp_line[1])
tmp_line = line.split('Password:')
if len(tmp_line) > 1:
descr.entryByName['Password_Entry']['wcfg']\
['textvariable'].set(tmp_line[1])
file.close()
# descr.entryByName['ParallelGroup']['widget'].toggle()
if not descr.entryByName['web service address']['widget'].get():
descr.entryByName['web service address']['widget']\
.selectitem(0)
url = descr.entryByName['web service address']['widget'].get()
url = url.strip()
if url.find('https://') != 0:
descr.entryByName['UserName_Label']['widget'].grid_forget()
descr.entryByName['UserName_Entry']['widget'].grid_forget()
descr.entryByName['Password_Label']['widget'].grid_forget()
descr.entryByName['Password_Entry']['widget'].grid_forget()
descr.entryByName['Remember_Label']['widget'].grid_forget()
descr.entryByName['Remember_Checkbutton']['widget']\
.grid_forget()
self.progressBar = ProgressBar(
descr.entryByName['WS_ProgressBar']['widget']
, labelside=None,
width=200, height=20, mode='percent')
self.progressBar.setLabelText('Progress...')
self.progressBar.set(0)
descr.entryByName['WS_ProgressBar']['widget'].grid_forget()
else:
descr.entryByName['WS_http']['widget'].bind(
sequence = "<Button-1>", func = self.WS_http)
descr.entryByName['calculationType']['widget']._entryWidget.\
config(state = 'readonly')
descr.entryByName['pbeType']['widget']._entryWidget.\
config(state = 'readonly')
descr.entryByName['boundaryConditions']['widget']._entryWidget.\
config(state = 'readonly')
descr.entryByName['chargeDiscretization']['widget'].\
_entryWidget.config(state = 'readonly')
descr.entryByName['surfaceCalculation']['widget']._entryWidget.\
config(state = 'readonly')
descr.entryByName['energyOutput']['widget']._entryWidget.\
config(state = 'readonly')
descr.entryByName['forceOutput']['widget']._entryWidget.\
config(state = 'readonly')
self.refreshCalculationPage()
self.refreshGridPage()
self.refreshPhysicsPage()
def paramUpdateAll(self):
"""Updates all parameters. Returns "ERROR" if failed """
if self.calculationParamUpdate() == "ERROR":
return "ERROR"
if self.gridParamUpdate() == "ERROR":
return "ERROR"
if self.physicsParamUpdate() == "ERROR":
return "ERROR"
def setOutputFiles(self):
"""Sets output files using outputFilesForm GUI"""
outputFilesForm = self.showForm('outputFilesForm', \
modal = 1, blocking = 1,force=1,master=self.cmdForms['default'].f)
descr = self.cmdForms['outputFilesForm'].descr
self.params.chargeDistributionFile = descr.entryByName\
['chargeDistributionFile']['widget'].get()
self.params.potentialFile = descr.entryByName['potentialFile']\
['widget'].get()
self.params.solventAccessibilityFile = descr.entryByName\
['solventAccessibilityFile']['widget'].get()
self.params.splineBasedAccessibilityFile = descr.entryByName\
['splineBasedAccessibilityFile']['widget'].get()
self.params.VDWAccessibilityFile = descr.entryByName\
['VDWAccessibilityFile']['widget'].get()
self.params.ionAccessibilityFile = descr.entryByName\
['ionAccessibilityFile']['widget'].get()
self.params.laplacianOfPotentialFile = descr.entryByName\
['laplacianOfPotentialFile']['widget'].get()
self.params.energyDensityFile = descr.entryByName\
['energyDensityFile']['widget'].get()
self.params.ionNumberFile = descr.entryByName\
['ionNumberFile']['widget'].get()
self.params.ionChargeDensityFile = descr.entryByName\
['ionChargeDensityFile']['widget'].get()
self.params.xShiftedDielectricFile = descr.entryByName\
['xShiftedDielectricFile']['widget'].get()
self.params.yShiftedDielectricFile = descr.entryByName\
['yShiftedDielectricFile']['widget'].get()
self.params.zShiftedDielectricFile = descr.entryByName\
['zShiftedDielectricFile']['widget'].get()
self.params.kappaFunctionFile = descr.entryByName\
['kappaFunctionFile']['widget'].get()
def addIon(self):
"""Adds an Ion"""
ionForm = self.showForm('ionForm', modal = 0, blocking = 1,
master=self.cmdForms['default'].f)
descr = self.cmdForms['ionForm'].descr
ion = Ion()
ion.charge = float(descr.entryByName['ionCharge']['widget'].get())
ion.concentration = float(descr.entryByName['ionConcentration']
['widget'].get())
ion.radius = float(descr.entryByName['ionRadius']['widget'].get())
self.params.ions.append(ion)
self.vf.message("self.APBSSetup.params.ions.append(Pmv.APBSCommands.Ion\
("+ion.toString()+"))")
self.vf.log("self.APBSSetup.params.ions.append(Pmv.APBSCommands.Ion(" \
+ion.toString()+"))")
f = self.cmdForms['default']
f.descr.entryByName['ionsList']['widget'].insert('end', ion.toString())
def removeIon(self):
"""Removes an Ion"""
descr = self.cmdForms['default'].descr
s = repr(descr.entryByName['ionsList']['widget'].getcurselection())
for i in range(descr.entryByName['ionsList']['widget'].size()):
if(string.find(s,descr.entryByName['ionsList']['widget']
.get(i))>-1):
break
descr.entryByName['ionsList']['widget'].delete(i)
self.params.ions.pop(i)
self.vf.message("self.APBSSetup.params.ions.pop("+`i`+")")
self.vf.log("self.APBSSetup.params.ions.pop("+`i`+")")
def moleculeListSelect(self, molName):
"""None <--- moleculeListSelect(molName)\n
Selects molecule with molName.\n
If the molecule was not read as pqr file moleculeListSelect\n
"""
if self.cmdForms.has_key('default'):
self.cmdForms['default'].root.config(cursor='watch')
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.VIEWER.master.config(cursor='watch')
#self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='watch')
molName = molName.replace('-','_')
mol = self.vf.getMolFromName(molName)
assert mol, "Error: molecule is not loaded " + molName
file, ext = os.path.splitext(mol.parser.filename)
if ext:
ext = ext.lower()
if ext == '.pqr':
filename = mol.parser.filename
mol.flag_copy_pqr = True
else: #create pqr file using pdb2pqr.py
filename = mol.name+".pqr"
#full_filename = os.path.join(self.params.projectFolder,filename)
#filename = full_filename
flag_overwrite = True
if not os.path.exists(filename) or \
self.vf.APBSPreferences.overwrite_pqr:
if not self.vf.commands.has_key('writePDB'):
self.vf.browseCommands("fileCommands",
commands=['writePDB',])
from user import home
tmp_pdb = home + os.path.sep + 'tmp.pdb'
filename = home + os.path.sep + filename
self.vf.writePDB(mol,tmp_pdb, pdbRec=('ATOM','HETATM'), log=0)
# Exe_String = sys.executable + \
# " -Wignore::DeprecationWarning " + self.params.pdb2pqr_Path\
# + " --ff="+self.params.pdb2pqr_ForceField + " tmp.pdb " + \
# "\""+full_filename+"\""
sys.argv = [sys.executable , self.params.pdb2pqr_Path]
if self.vf.APBSPreferences.nodebump.get():
sys.argv.append('--nodebump')
if self.vf.APBSPreferences.nohopt.get():
sys.argv.append('--noopt')
sys.argv.append('--ff='+self.params.pdb2pqr_ForceField)
sys.argv.append(tmp_pdb)
sys.argv.append(filename)
os.path.split(self.params.pdb2pqr_Path)[0]
import subprocess
returncode = subprocess.call(sys.argv)
if returncode:
if not hasattr(self.vf,"spin"):
#spin is not available during unit testing
return ''
msg = "Could not convert " + mol.name +""" to pqr!
Please try the latest pdb2pqr from: http://pdb2pqr.sourceforge.net."""
if self.cmdForms.has_key('default') and \
self.cmdForms['default'].f.winfo_toplevel().wm_state()==\
'normal':
tkMessageBox.showerror("ERROR: ", msg,
parent = self.cmdForms['default'].root)
else:
tkMessageBox.showerror("ERROR: ", msg)
self.vf.GUI.ROOT.config(cursor='')
self.vf.GUI.VIEWER.master.config(cursor='')
if self.cmdForms.has_key('default'):
self.cmdForms['default'].root.config(cursor='')
return ''
try:
os.remove(mol.name + '-typemap.html')
except:
pass
if self.cmdForms.has_key('default'):
self.cmdForms['default'].root.config(cursor='')
self.vf.GUI.ROOT.config(cursor='')
self.vf.GUI.VIEWER.master.config(cursor='')
#self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='xterm')
os.remove(tmp_pdb)
mol_tmp = self.vf.readPQR(filename, topCommand=0)
mol_tmp.name = str(mol.name)
self.vf.deleteMol(mol,topCommand=0)
mol = mol_tmp
mol.flag_copy_pqr = False
self.vf.assignAtomsRadii(mol, overwrite=True,log=False)
if self.vf.hasGui:
change_Menu_state(self.vf.APBSSaveProfile, 'normal')
if self.cmdForms.has_key('default'):
self.cmdForms['default'].root.config(cursor='')
self.vf.GUI.ROOT.config(cursor='')
self.vf.GUI.VIEWER.master.config(cursor='')
# self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='xterm')
if self.cmdForms.has_key('default'):
form_descr = self.cmdForms['default'].descr
#form_descr.entryByName['Profiles']['widget'].setentry('Default')
form_descr.entryByName['Profiles_Add']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Remove']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Run']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Save']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Load']['widget'].config(state =
"normal")
if APBSservicesFound:
form_descr.entryByName['WS_Run']['widget'].config(state =
"normal")
else:
global state_GUI
state_GUI = 'normal'
mol = self.vf.getMolFromName(molName.replace('-','_'))
if self.cmdForms.has_key('default'):
APBSParamName = self.cmdForms['default'].descr.\
entryByName['Profiles']['widget'].get()
mol.APBSParams[APBSParamName] = self.params
else:
mol.APBSParams['Default'] = self.params
self.flag_grid_changed = False #to call autosize Grid when running APBS
return filename
def molecule1Select(self):
"""Seclects molecule1 and setups molecule1Path"""
val = self.showForm('moleculeSelect', modal = 0, \
blocking = 1,master=self.cmdForms['default'].f)
if val:
if len(val['moleculeListSelect'])==0: return
molName = val['moleculeListSelect'][0]
self.params.molecule1Path = self.moleculeListSelect(molName)
self.mol1Name = molName
if not self.params.molecule1Path:
return
self.refreshCalculationPage()
if not self.vf.APBSSetup.flag_grid_changed:
self.autocenterCoarseGrid()
self.autosizeCoarseGrid()
self.autocenterFineGrid()
self.autosizeFineGrid()
self.refreshGridPage()
def molecule2Select(self):
"""Seclects molecule2 and setups molecule2Path"""
val = self.showForm('moleculeSelect', modal = 0, \
blocking = 1,master=self.cmdForms['default'].f)
if val:
if len(val['moleculeListSelect'])==0: return
molName = val['moleculeListSelect'][0]
self.params.molecule2Path = self.moleculeListSelect(molName)
self.mol2Name = molName
self.refreshCalculationPage()
def complexSelect(self):
"""Seclects complex and setups complexPath"""
val = self.showForm('moleculeSelect', modal=0, blocking=1,\
master=self.cmdForms['default'].f)
if val:
if len(val['moleculeListSelect'])==0: return
molName = val['moleculeListSelect'][0]
self.params.complexPath = self.moleculeListSelect(molName)
self.complexName = molName
self.refreshCalculationPage()
if not self.params.complexPath:
return
if not self.vf.APBSSetup.flag_grid_changed:
self.autocenterCoarseGrid()
self.autosizeCoarseGrid()
self.autocenterFineGrid()
self.autosizeFineGrid()
self.refreshGridPage()
def apbsOutput(self, molecule1=None, molecule2=None, _complex=None, blocking=False ):
"""Runs APBS using mglutil.popen2Threads.SysCmdInThread"""
self.add_profile()
if self.paramUpdateAll() == "ERROR":
return
if molecule1:
self.params.SaveAPBSInput(self.params.projectFolder+os.path.sep\
+"apbs-input-file.apbs")
self.changeMenuState('disabled')
cmdstring = "\""+self.params.APBS_Path+"\" "+'apbs-input-file.apbs'
self.cwd = os.getcwd()
if blocking==False and self.vf.hasGui:
from mglutil.popen2Threads import SysCmdInThread
os.chdir(self.params.projectFolder)
self.cmd = SysCmdInThread(cmdstring, shell=True)
self.cmd.start()
time.sleep(1)
else:
from popen2 import Popen4
os.chdir(self.params.projectFolder)
exec_cmd = Popen4(cmdstring)
status = exec_cmd.wait()
if status==0:
print exec_cmd.fromchild.read()
else:
print exec_cmd.childerr.read()
self.SaveResults(self.params.name, )
os.chdir(self.cwd)
else:
file_name, ext = os.path.splitext(self.params.molecule1Path)
molecule1 = os.path.split(file_name)[-1]
if self.cmdForms.has_key('default'):
APBSParamName = self.cmdForms['default'].descr.\
entryByName['Profiles']['widget'].get()
else:
APBSParamName = 'Default'
if self.params.calculationType == 'Binding energy':
file_name, ext = os.path.splitext(self.params.molecule2Path)
molecule2 = os.path.split(file_name)[-1]
file_name, ext = os.path.splitext(self.params.complexPath)
_complex = os.path.split(file_name)[-1]
try:
self.doitWrapper(self.params.__dict__)
self.vf.APBSRun(molecule1, molecule2, _complex, APBSParamName=APBSParamName)
except Exception, inst:
print inst
tkMessageBox.showerror("Error Running APBS", "Please make sure that Molecule(s) have corrent path.\n\n"+
"Use Select botton to ensure your molecules(s) exists.",
parent=self.vf.APBSSetup.cmdForms['default'].root)
def SaveResults(self,params_name):
"""Checks the queue for results until we get one"""
if hasattr(self, 'cmd') is False \
or self.cmd.ok.configure()['state'][-1] == 'normal':
self.saveProfile(Profilename=params_name, fileFlag=True)
self.changeMenuState('normal')
if hasattr(self, 'cmd') is True:
self.cmd.com.wait()
potential_dx = self.params.projectFolder
file_name, ext = os.path.splitext(self.params.molecule1Path)
mol_name = os.path.split(file_name)[-1]
potential = os.path.join(potential_dx, mol_name+'.potential.dx')
if not os.path.exists(potential):
return
self.vf.Grid3DReadAny(potential, show=False, normalize=False)
self.vf.grids3D[mol_name+'.potential.dx'].geomContainer['Box'].Set(visible=0)
self.potential = mol_name+'.potential.dx'
if self.vf.hasGui:
change_Menu_state(self.vf.APBSDisplayIsocontours, 'normal')
change_Menu_state(self.vf.APBSDisplayOrthoSlice, 'normal')
if hasattr(self.vf,'APBSVolumeRender'):
change_Menu_state(self.vf.APBSVolumeRender, 'normal')
return
else:
self.vf.GUI.ROOT.after(10, self.SaveResults, params_name)
def select_profile(self,profile_name):
"""Selects profile"""
if self.paramUpdateAll() == "ERROR":
self.remove_profile()
return
file_name, ext = os.path.splitext(self.params.molecule1Path)
tmp_mol_name = os.path.split(file_name)[-1]
molecule1 = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
if molecule1.APBSParams.has_key(profile_name):
self.params = molecule1.APBSParams[profile_name]
self.refreshAll()
else:
self.params.name = profile_name
molecule1.APBSParams[profile_name] = self.params
def add_profile(self):
"""Adds profile"""
if self.cmdForms.has_key('default'):
ComboBox = self.cmdForms['default'].descr.entryByName['Profiles']\
['widget']
profile_name = ComboBox._entryfield.get()
list_items = ComboBox._list.get()
if not profile_name in list_items:
list_items += (profile_name,)
file_name, ext = os.path.splitext(self.params.molecule1Path)
tmp_mol_name = os.path.split(file_name)[-1]
molecule1 = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
self.params.name = profile_name
molecule1.APBSParams[profile_name] = self.params
ComboBox.setlist(list_items)
ComboBox.setentry(profile_name)
def remove_profile(self):
"""Removes current profile"""
ComboBox = self.cmdForms['default'].descr.entryByName['Profiles']\
['widget']
profile_name = ComboBox._entryfield.get()
list_items = ComboBox._list.get()
if profile_name in list_items:
list_items = list(list_items)
list_items.remove(profile_name)
list_items = tuple(list_items)
ComboBox.clear()
ComboBox.setlist(list_items)
try:
ComboBox.setentry(list_items[0])
except IndexError:
pass
file_name, ext = os.path.splitext(self.params.molecule1Path)
tmp_mol_name = os.path.split(file_name)[-1]
molecule1 = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
if molecule1 and molecule1.APBSParams.has_key(profile_name):
del molecule1.APBSParams[profile_name]
def saveProfile(self, Profilename="Default", fileFlag=False, flagCommand=False):
"""Saves current profile
fileFlag is used to decide if Profilename is a file: False means that we need to aks for a file first
flagCommand is isued to check if this functionm is called from APBSSave_Profile Command """
if fileFlag:
if not flagCommand and self.cmdForms.has_key('default'):
Profilename = self.cmdForms['default'].descr.\
entryByName['Profiles']['widget'].get()
file_name,ext = os.path.splitext(self.params.molecule1Path)
mol_name = os.path.split(file_name)[-1]
potential_dx = os.path.join(self.params.projectFolder, mol_name+
'.potential.dx')
if os.path.exists(potential_dx):
tmp_string = os.path.basename(Profilename).\
replace(".apbs.pf","")
dest_path = os.path.join(self.params.projectFolder, tmp_string +
'_' + mol_name + '_potential.dx')
shutil.copyfile(potential_dx,dest_path)
if self.params.calculationType == 'Solvation energy':
potential_dx = os.path.join(self.params.projectFolder, mol_name+
'_Vacuum.potential.dx')
if os.path.exists(potential_dx):
tmp_string = os.path.basename(Profilename).\
replace(".apbs.pf","")
dest_path = os.path.join(self.params.projectFolder,
tmp_string + '_' + mol_name + '_Vacuum_potential.dx')
shutil.copyfile(potential_dx,dest_path)
if self.params.calculationType == 'Binding energy':
file_name,ext = os.path.splitext(self.params.molecule2Path)
mol_name = os.path.split(file_name)[-1]
potential_dx = os.path.join(self.params.projectFolder, mol_name+
'.potential.dx')
if os.path.exists(potential_dx):
tmp_string = os.path.basename(Profilename).\
replace(".apbs.pf","")
dest_path = os.path.join(self.params.projectFolder,
tmp_string + '_' + mol_name + '_potential.dx')
shutil.copyfile(potential_dx,dest_path)
file_name,ext = os.path.splitext(self.params.complexPath)
mol_name = os.path.split(file_name)[-1]
potential_dx = os.path.join(self.params.projectFolder, mol_name+
'.potential.dx')
if os.path.exists(potential_dx):
tmp_string = os.path.basename(Profilename).\
replace(".apbs.pf","")
dest_path = os.path.join(self.params.projectFolder,
tmp_string + '_' + mol_name + '_potential.dx')
shutil.copyfile(potential_dx,dest_path)
if os.path.isdir(self.params.projectFolder):
Profilename = os.path.join(self.params.projectFolder, Profilename)
if(string.find(Profilename,'.apbs.pf')<0):
Profilename = Profilename + '.apbs.pf'
fp = open(Profilename, 'w')
pickle.dump(self.params, fp)
pickle.dump(self.params.ions, fp)
fp.close()
else:
self.vf.APBSSaveProfile()
def loadProfile(self, filename = None):
"""Loads profile"""
if filename:
fp = open(filename, 'r')
self.params = pickle.load(fp)
self.doit(**self.params.__dict__)
fp.close()
profile_name = os.path.basename(filename).replace(".apbs.pf","")
if self.params.calculationType=='Solvation energy' or self.params.\
calculationType=='Electrostatic potential':
if not self.vf.getMolFromName(os.path.basename(os.path.\
splitext(self.params.molecule1Path)[0])):
molecule1Path = os.path.join(self.params.projectFolder,
self.params.molecule1Path)
self.vf.readPQR(molecule1Path, topCommand=0)
if(self.params.calculationType=='Binding energy'):
if not self.vf.getMolFromName(os.path.basename(os.path.\
splitext(self.params.molecule1Path)[0])):
molecule1Path = os.path.join(self.params.projectFolder,
self.params.molecule1Path)
self.vf.readPQR(molecule1Path, topCommand=0)
if not self.vf.getMolFromName(os.path.basename(os.path.\
splitext(self.params.molecule2Path)[0])):
molecule2Path = os.path.join(self.params.projectFolder,
self.params.molecule2Path)
self.vf.readPQR(molecule2Path, topCommand=0)
if not self.vf.getMolFromName(os.path.basename(os.path.\
splitext(self.params.complexPath)[0])):
complexPath = os.path.join(self.params.projectFolder,
self.params.complexPath)
self.vf.readPQR(complexPath, topCommand=0)
# the following part updates Profiles ComboBox
if self.cmdForms.has_key('default'):
ComboBox = self.cmdForms['default'].descr.entryByName\
['Profiles']['widget']
list_items = ComboBox._list.get()
if not profile_name in list_items:
list_items += (profile_name,)
ComboBox.setlist(list_items)
ComboBox.setentry(profile_name)
else:
global PROFILES
PROFILES += (profile_name,)
if self.cmdForms.has_key('default'):
form_descr = self.cmdForms['default'].descr
form_descr.entryByName['Profiles_Add']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Remove']['widget'].config(state
= "normal")
form_descr.entryByName['Profiles_Run']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Save']['widget'].config(state =
"normal")
form_descr.entryByName['Profiles_Load']['widget'].config(state =
"normal")
if APBSservicesFound:
form_descr.entryByName['WS_Run']['widget'].config(state =
"normal")
else:
global state_GUI
state_GUI = 'normal'
if self.vf.hasGui:
change_Menu_state(self.vf.APBSSaveProfile, 'normal')
self.refreshAll()
file_name,ext = os.path.splitext(self.params.molecule1Path)
mol_name = os.path.split(file_name)[-1]
file_potential = os.path.join(self.params.projectFolder,profile_name
+ '_' + mol_name + '_potential.dx')
if os.path.exists(file_potential):
shutil.copyfile(file_potential,os.path.join(self.params.\
projectFolder,mol_name + '.potential.dx'))
self.changeMenuState('normal')
self.potential = mol_name+'.potential.dx'
if self.vf.hasGui:
change_Menu_state(self.vf.APBSDisplayIsocontours, 'normal')
change_Menu_state(self.vf.APBSDisplayOrthoSlice, 'normal')
if hasattr(self.vf,'APBSVolumeRender'):
change_Menu_state(self.vf.APBSVolumeRender, 'normal')
self.vf.Grid3DReadAny(os.path.join(self.params.projectFolder,mol_name + '.potential.dx'),
show=False, normalize=False)
self.vf.grids3D[mol_name+'.potential.dx'].geomContainer['Box'].Set(visible=0)
else:
self.vf.APBSLoadProfile()
def apbsRunRemote(self):
"""Runs APBS Web Services in a thread and checks for the results"""
if self.paramUpdateAll() == "ERROR":
return
file_name, ext = os.path.splitext(self.params.molecule1Path)
tmp_mol_name = os.path.split(file_name)[-1]
mol = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
f = self.cmdForms['default']
address = f.descr.entryByName['web service address']['widget'].get()
address = address.strip()
global APBS_ssl
if address.find('https://') != 0:
#first check to see if APBS Web Services is up and running
import urllib
opener = urllib.FancyURLopener({})
try:
servlet = opener.open(address)
except IOError:
self.errorMsg=address+" could not be found"
self.errorMsg += "\nPlease make sure that server is up and running"
self.errorMsg += "\nFor more info on APBS Web Services visit http://www.nbcr.net/services"
self.showForm('error')
return
APBS_ssl = False
else:
from mgltools.web.services.SecuritymyproxyloginImplService_services import \
loginUserMyProxyRequestWrapper, \
SecuritymyproxyloginImplServiceLocator
gamaLoginLocator = SecuritymyproxyloginImplServiceLocator()
gamaLoginService = gamaLoginLocator.getSecuritymyproxyloginImpl(
ssl=1,transport=httplib.HTTPSConnection)
req = loginUserMyProxyRequestWrapper()
username = self.cmdForms['default'].descr.\
entryByName['UserName_Entry']['widget'].get()
passwd = self.cmdForms['default'].descr.\
entryByName['Password_Entry']['widget'].get()
req._username = username
req._passwd = <PASSWORD>
resp = gamaLoginService.loginUserMyProxy(req)
f = open(APBS_proxy, "w")
f.write(resp._loginUserMyProxyReturn)
f.close()
APBS_ssl = True
if self.RememberLogin_var.get():
file = open(self.rc_apbs,'w')
user = self.cmdForms['default'].descr.entryByName\
['UserName_Entry']['widget'].get()
passwd = self.cmdForms['default'].descr.entryByName\
['Password_Entry']['widget'].get()
file.write("User:%s\nPassword:%<PASSWORD>"%(user,passwd))
self.params.projectFolder=os.path.join(os.getcwd(),"apbs-"+mol.name)
from thread import start_new_thread
if self.params.calculationType == 'Binding energy':
file_name, ext = os.path.splitext(self.params.molecule2Path)
tmp_mol_name = os.path.split(file_name)[-1]
mol2 = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
file_name, ext = os.path.splitext(self.params.complexPath)
tmp_mol_name = os.path.split(file_name)[-1]
_complex = self.vf.getMolFromName(tmp_mol_name.replace('-','_'))
self.params.projectFolder += "_" + mol2.name + "_"+ _complex.name
if not os.path.exists(self.params.projectFolder):
os.mkdir(self.params.projectFolder)
self.runWS(address, self.params, mol, mol2, _complex)
else:
if not os.path.exists(self.params.projectFolder):
os.mkdir(self.params.projectFolder)
self.runWS(address, self.params, mol)
#start_new_thread( self.checkForRemoteResults, (self.webServiceResultsQueue,))
def runWS(self, address, params, mol1, mol2 = None, _complex = None):
"""Runs APBS Web Services"""
if self.cmdForms.has_key('default'):
self.apbsWS = APBSCmdToWebService(params, mol1,mol2, _complex)
self.Parallel_flag = False
else:
self.apbsWS = APBSCmdToWebService(params, mol1, mol2, _complex)
self.Parallel_flag = False
try:
f = self.cmdForms['default']
f.descr.entryByName['APBSservicesLabel1']['widget'].\
configure(text = 'Connecting to '+ address)
f.descr.entryByName['APBSservicesLabel2']['widget'].\
configure(text = "")
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "")
f.descr.entryByName['APBSservicesLabel3']['widget'].\
configure(text = "Please wait ...")
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "")
self.vf.GUI.ROOT.update()
resp = self.apbsWS.run(address)
f.descr.entryByName['APBSservicesLabel1']['widget'].\
configure(text = "Received Job ID: " + resp._jobID)
self.vf.GUI.ROOT.after(5, self.checkForRemoteResults)
f.descr.entryByName['WS_Run']['widget'].configure(state = 'disabled')
# f.descr.entryByName['APBSservicesLabel1']['widget'].\
# configure(text = 'Remote APBS calculation is done')
self.rml = mol1.name
except Exception, inst:
f.descr.entryByName['APBSservicesLabel3']['widget'].\
configure(text = "")
from ZSI import FaultException
if isinstance(inst, FaultException):
tmp_str = inst.fault.AsSOAP()
tmp_str = tmp_str.split('<message>')
tmp_str = tmp_str[1].split('</message>')
if self.cmdForms.has_key('default') and \
self.cmdForms['default'].f.winfo_toplevel().wm_state() == \
'normal':
tkMessageBox.showerror("ERROR: ",tmp_str[0],parent =
self.cmdForms['default'].root)
else:
tkMessageBox.showerror("ERROR: ",tmp_str[0])
else:
import traceback
traceback.print_stack()
traceback.print_exc()
f.descr.entryByName['APBSservicesLabel1']['widget'].\
configure(text = "")
f.descr.entryByName['APBSservicesLabel2']['widget'].\
configure(text = "ERROR!!! Unable to complete the Run")
f.descr.entryByName['APBSservicesLabel3']['widget'].\
configure(text = "Please open Python Shell for Traceback")
def checkForRemoteResults(self):
"""Checks the queue for remote results until we get one"""
resp = self.apbsWS.appServicePort.queryStatus(queryStatusRequest(self.apbsWS.JobID))
if resp._code == 8: # 8 = GramJob.STATUS_DONE
f = self.cmdForms['default']
f.descr.entryByName['APBSservicesLabel2']['widget'].\
configure(text = resp._message)
webbrowser.open(resp._baseURL)
f.descr.entryByName['APBSservicesLabel3']['widget'].\
configure(text = resp._baseURL,fg='Blue',cursor='hand1')
def openurl(event):
webbrowser.open(resp._baseURL)
f.descr.entryByName['APBSservicesLabel3']['widget'].\
bind(sequence="<Button-1>",func = openurl)
# read the potential back
opener = urllib.FancyURLopener(cert_file = APBS_proxy, key_file = APBS_proxy)
if self.Parallel_flag:
if self.npx*self.npy*self.npz == 1:
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "Downloading %s.potential-PE0.dx"%self.rml)
f.descr.entryByName['WS_ProgressBar']['widget'].\
grid(sticky='ew', row = 9, column = 0, columnspan = 2)
f.descr.entryByName['APBS_WS_DX_Label']['widget'].\
configure(text = "URI: "+resp._baseURL+"/%s.potential-PE0.dx"%self.rml)
self.progressBar.configure(progressformat='precent',
labeltext='Progress ... ', max =100)
self.progressBar.set(0)
self._dx = opener.open(resp._baseURL+"/%s.potential-PE0.dx"%self.rml)
self._dx_out = open(os.path.join(self.params.projectFolder,
"%s.potential.dx"%self.rml),"w")
bytes = int(self._dx.headers.dict['content-length'])
self._progress_counter = 0
self._download_bytes = bytes/100
if self._download_bytes == 0: self._download_bytes = 1
self.Download()
else:
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "Downloading %s.potential.dx. Please wait ..."%self.rml)
f.descr.entryByName['WS_ProgressBar']['widget'].\
grid(sticky='ew', row = 9, column = 0, columnspan = 2)
f.descr.entryByName['APBS_WS_DX_Label']['widget'].\
configure(text = "URI: "+resp._baseURL+"/%s.potential-PE*.dx"%self.rml)
self.progressBar.configure(progressformat='ratio',
labeltext='Progress ... ', max =self.npx*self.npy*self.npz)
self._progress_counter = 0
self.progressBar.set(0)
self._dx_files = []
for i in range(self.npx*self.npy*self.npz):
self._dx_files.append(opener.open(resp._baseURL+
"/%s.potential-PE%d.dx"%(self.rml,i)))
self._dx_out = open(os.path.join(self.params.projectFolder,
"%s.potential.dx"%self.rml),"w")
self._dx_out.write("# Data from %s\n"%resp._baseURL)
self._dx_out.write("#\n# POTENTIAL (kT/e)\n#\n")
self.Download_and_Merge()
else:
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text = "Downloading %s.potential.dx"%self.rml)
f.descr.entryByName['WS_ProgressBar']['widget'].\
grid(sticky='ew', row = 9, column = 0, columnspan = 2)
f.descr.entryByName['APBS_WS_DX_Label']['widget'].\
configure(text = "URI: "+resp._baseURL + "/%s.potential.dx"%self.rml)
self.progressBar.configure(progressformat='percent',
labeltext='Progress ... ', max =100)
self.progressBar.set(0)
self._dx = opener.open(resp._baseURL + "/%s.potential.dx"%self.rml)
filePath = os.path.join(self.params.projectFolder,"%s.potential.dx"%self.rml)
try:
self._dx_out = open(filePath,"w")
except IOError:
showerror("Download Failed!",
"Permission denied: " +filePath)
bytes = int(self._dx.headers.dict['content-length'])
self._progress_counter = 0
self._download_bytes = bytes/100
if self._download_bytes == 0: self._download_bytes = 1
self.Download()
return
else:
f = self.cmdForms['default']
f.descr.entryByName['APBSservicesLabel2']['widget'].\
configure(text = "Status: " + resp._message)
self.vf.GUI.ROOT.after(500, self.checkForRemoteResults)
def Download(self):
self._progress_counter += 1
if self._progress_counter > 100:
self._progress_counter = 100
self.progressBar.set(self._progress_counter)
tmp = self._dx.read(self._download_bytes)
if tmp:
self._dx_out.write(tmp)
else:
self._dx.close()
self._dx_out.close()
f = self.cmdForms['default']
f.descr.entryByName['WS_ProgressBar']['widget'].grid_forget()
f.descr.entryByName['APBS_WS_DX_Label']['widget'].\
configure(text = '')
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text="%s.potential.dx has been saved"%self.rml)
self.saveProfile(self.params.name, fileFlag=True)
self.changeMenuState('normal')
f.descr.entryByName['WS_Run']['widget'].configure(state = 'normal')
return
self.vf.GUI.ROOT.after(10, self.Download)
def Download_and_Merge(self):
self._dx_files[0].readline()
self._dx_files[0].readline()
self._dx_files[0].readline()
self._dx_files[0].readline()
tmp_str = self._dx_files[0].readline()
from string import split
w = split(tmp_str)
nx, ny, nz = int(w[5]), int(w[6]), int(w[7])
self._dx_out.write("object 1 class gridpositions counts %d %d %d\n"
%(nx*self.npx,ny*self.npy,nz*self.npz))
self._dx_out.write(self._dx_files[0].readline())
self._dx_out.write(self._dx_files[0].readline())
self._dx_out.write(self._dx_files[0].readline())
self._dx_out.write(self._dx_files[0].readline())
self._dx_out.write("object 2 class gridconnections counts %d %d %d\n"
%(nx*self.npx,ny*self.npy,nz*self.npz))
self._dx_out.write("object 3 class array type double rank 0 items %d"
%(nx*self.npx*ny*self.npy*nz*self.npz)+" data follows\n")
for file in self._dx_files[1:]:
for i in range(11):
file.readline()
self._dx_files[0].readline()
self._dx_files[0].readline()
arrays = []
for file in self._dx_files:
self._progress_counter += 1
self.progressBar.set(self._progress_counter)
data = file.readlines()
file.close()
array = Numeric.zeros( (nx,ny,nz), Numeric.Float32)
values = map(split, data[0:-5])
ind=0
size = nx*ny*nz
for line in values:
if ind>=size:
break
l = len(line)
array.flat[ind:ind+l] = map(float, line)
ind = ind + l
arrays.append(array)
self.progressBar.configure(labeltext='Merging ... ')
for k in range(self.npz):
for j in range(self.npy):
for i in range(self.npx):
if i == 0:
array_x = arrays[self.npx*j+
self.npx*self.npy*k]
else:
array_x = Numeric.concatenate(
(array_x,arrays[i+self.npx*j+
self.npx*self.npy*k]),axis=0)
if j == 0:
array_y = array_x
else:
array_y = Numeric.concatenate(
(array_y,array_x),axis=1)
if k == 0:
array_out = array_y
else:
array_out = Numeric.concatenate(
(array_out,array_y),axis=2)
for z in array_out:
for y in z:
for x in y:
self._dx_out.write(str(x)+" ")
self._dx_out.write('\n')
self._dx_out.write("attribute \"dep\" string \"positions\"\n")
self._dx_out.write("object \"regular positions regular connections\" class field\n")
self._dx_out.write("component \"positions\" value 1\n")
self._dx_out.write("component \"connections\" value 2\n")
self._dx_out.write("component \"data\" value 3\n")
self._dx_out.close()
f = self.cmdForms['default']
f.descr.entryByName['WS_ProgressBar']['widget'].grid_forget()
f.descr.entryByName['APBS_WS_DX_Label']['widget'].\
configure(text = '')
f.descr.entryByName['APBSservicesLabel4']['widget'].\
configure(text="%s.potential.dx has been saved"%self.rml)
self.saveProfile(self.params.name, fileFlag=True)
self.changeMenuState('normal')
f.descr.entryByName['WS_Run']['widget'].configure(state = 'normal')
# Forms defined here
def buildFormDescr(self, formName):
"""Builds 'error','ionForm','outputFilesForm','moleculeSelect' and
'default' forms'"""
if formName == 'error':
if self.cmdForms.has_key('default') and \
self.cmdForms['default'].f.winfo_toplevel().wm_state() == \
'normal':
tkMessageBox.showerror("ERROR: ", self.errorMsg,parent =
self.cmdForms['default'].root)
else:
tkMessageBox.showerror("ERROR: ", self.errorMsg)
return
if formName == 'ionForm':
ifd = InputFormDescr(title = "Add Ion")
ifd.append({'name':'ionChargeLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Charge (e):'},
'gridcfg':{'row':0, 'column':0, 'sticky':'wens'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'ionCharge',
'wcfg':{'validate':{'validator':'real'}, 'value':1},
'gridcfg':{'row':0, 'column':1, 'sticky':'wens'}
})
ifd.append({'name':'ionConcentrationLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Concentration (M):'},
'gridcfg':{'row':1, 'column':0, 'sticky':'wens'}
})
ifd.append({'widgetType':ThumbWheel,
'name':'ionConcentration',
'wcfg':{'text':None, 'showLabel':1,
'min':0,
'value':0.01, 'oneTurn':0.1,
'type':'float',
'increment':0.01,
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'continuous':1,
'wheelPad':1, 'width':150,'height':14},
'gridcfg':{'row':1, 'column':1, 'sticky':'wens'}
})
ifd.append({'name':'ionRadiusLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Radius (Angstroms):'},
'gridcfg':{'row':2, 'column':0, 'sticky':'wens'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'ionRadius',
'wcfg':{'validate':{'validator':'real','min':0}, 'value':1},
'gridcfg':{'row':2, 'column':1, 'sticky':'wens'}
})
return ifd
elif formName =='outputFilesForm':
ifd = InputFormDescr(title = "Select output files")
ifd.append({'name':'fileTypeLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'File Type'},
'gridcfg':{'sticky':'e', 'row':1, 'column':0}
})
ifd.append({'name':'fileFormatLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'File format'},
'gridcfg':{'sticky':'e', 'row':1, 'column':1}
})
ifd.append({'name':'chargeDistributionFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Charge distribution file: '},
'gridcfg':{'sticky':'e', 'row':2, 'column':0}
})
ifd.append({'name':'chargeDistributionFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'dropdown':1, 'history':0,},
'defaultValue':self.params.chargeDistributionFile,
'gridcfg':{'sticky':'wens', 'row':2, 'column':1}
})
ifd.append({'name':'potentialFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Potential file: '},
'gridcfg':{'sticky':'e', 'row':3, 'column':0}
})
ifd.append({'name':'potentialFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.potentialFile,
'gridcfg':{'sticky':'wens', 'row':3, 'column':1}
})
ifd.append({'name':'solventAccessibilityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Solvent accessibility file: '},
'gridcfg':{'sticky':'e', 'row':4, 'column':0}
})
ifd.append({'name':'solventAccessibilityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.solventAccessibilityFile,
'gridcfg':{'sticky':'wens', 'row':4, 'column':1}
})
ifd.append({'name':'splineBasedAccessibilityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Spline-based accessibility file: '},
'gridcfg':{'sticky':'e', 'row':5, 'column':0}
})
ifd.append({'name':'splineBasedAccessibilityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.splineBasedAccessibilityFile,
'gridcfg':{'sticky':'wens', 'row':5, 'column':1}
})
ifd.append({'name':'VDWAccessibilityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'VDW accessibility file: '},
'gridcfg':{'sticky':'e', 'row':6, 'column':0}
})
ifd.append({'name':'VDWAccessibilityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.VDWAccessibilityFile,
'gridcfg':{'sticky':'wens', 'row':6, 'column':1}
})
ifd.append({'name':'ionAccessibilityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Ion accessibility file: '},
'gridcfg':{'sticky':'e', 'row':7, 'column':0}
})
ifd.append({'name':'ionAccessibilityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.ionAccessibilityFile,
'gridcfg':{'sticky':'wens', 'row':7, 'column':1}
})
ifd.append({'name':'laplacianOfPotentialFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Laplacian of potential file: '},
'gridcfg':{'sticky':'e', 'row':8, 'column':0}
})
ifd.append({'name':'laplacianOfPotentialFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.laplacianOfPotentialFile,
'gridcfg':{'sticky':'wens', 'row':8, 'column':1}
})
ifd.append({'name':'energyDensityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Energy density file: '},
'gridcfg':{'sticky':'e', 'row':9, 'column':0}
})
ifd.append({'name':'energyDensityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.energyDensityFile,
'gridcfg':{'sticky':'wens', 'row':9, 'column':1}
})
ifd.append({'name':'ionNumberFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Ion number file: '},
'gridcfg':{'sticky':'e', 'row':10, 'column':0}
})
ifd.append({'name':'ionNumberFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.ionNumberFile,
'gridcfg':{'sticky':'wens', 'row':10, 'column':1}
})
ifd.append({'name':'ionChargeDensityFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Ion charge density file: '},
'gridcfg':{'sticky':'e', 'row':11, 'column':0}
})
ifd.append({'name':'ionChargeDensityFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.ionChargeDensityFile,
'gridcfg':{'sticky':'wens', 'row':11, 'column':1}
})
ifd.append({'name':'xShiftedDielectricFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'X-shifted dielectric file: '},
'gridcfg':{'sticky':'e', 'row':12, 'column':0}
})
ifd.append({'name':'xShiftedDielectricFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.xShiftedDielectricFile,
'gridcfg':{'sticky':'wens', 'row':12, 'column':1}
})
ifd.append({'name':'yShiftedDielectricFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Y-shifted dielectric file: '},
'gridcfg':{'sticky':'e', 'row':13, 'column':0}
})
ifd.append({'name':'yShiftedDielectricFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.yShiftedDielectricFile,
'gridcfg':{'sticky':'wens', 'row':13, 'column':1}
})
ifd.append({'name':'zShiftedDielectricFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Z-shifted dielectric file: '},
'gridcfg':{'sticky':'e', 'row':14, 'column':0}
})
ifd.append({'name':'zShiftedDielectricFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.zShiftedDielectricFile,
'gridcfg':{'sticky':'wens', 'row':14, 'column':1}
})
ifd.append({'name':'kappaFunctionFileLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Kappa function file: '},
'gridcfg':{'sticky':'e', 'row':15, 'column':0}
})
ifd.append({'name':'kappaFunctionFile',
'widgetType':Pmw.ComboBox,
'wcfg':{'scrolledlist_items':self.params.FILETYPES,
'listheight':100, 'history':0, 'dropdown':1},
'defaultValue':self.params.kappaFunctionFile,
'gridcfg':{'sticky':'wens', 'row':15, 'column':1}
})
return ifd
elif formName == 'moleculeSelect':
ifd=InputFormDescr(title="Select a molecule")
self.selectedFilename = ''
molNames = self.vf.Mols.name
if molNames is None:
molNames = []
ifd.append({'name':'moleculeListSelect',
'widgetType':Pmw.ScrolledListBox,
'tooltip':'Select a molecule loaded in PMV to run APBS ',
'wcfg':{'label_text':'Select Molecule: ',
'labelpos':'nw',
'items':molNames,
'listbox_selectmode':'single',
'listbox_exportselection':0,
'usehullsize': 1,
'hull_width':100,'hull_height':150,
'listbox_height':5},
'gridcfg':{'sticky':'nsew', 'row':1, 'column':0}})
elif formName == 'default':
ifd = InputFormDescr(title="APBS Profile Setup and Execution")
## NOTEBOOK WIDGET
ifd.append({'widgetType':Pmw.NoteBook,
'name':'hovigNotebook',
'container':{'Calculation':
"w.page('Calculation')",
'Physics':"w.page('Physics')",
'Web Service':"w.page('Web Service')",
'Grid':"w.page('Grid')"},
'wcfg':{'borderwidth':3},
'componentcfg':[{'name':'Calculation',
'cfg':{}},
{'name':'Grid', 'cfg':{}},
{'name':'Physics','cfg':{}},
{'name':'Web Service','cfg':{}} ],
'gridcfg':{'sticky':'we'},
})
## CALCULATION PAGE
## MATH GROUP
ifd.append({'name':"mathGroup",
'widgetType':Pmw.Group,
'parent':'Calculation',
'container':{'mathGroup':'w.interior()'},
'wcfg':{'tag_text':"Mathematics"},
'gridcfg':{'sticky':'wne'}
})
ifd.append({'name':'calculationTypeLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Calculation type:'},
'gridcfg':{'row':0, 'column':0, 'sticky':'e'}
})
ifd.append({'name':'calculationType',
'widgetType':Pmw.ComboBox,
'parent':'mathGroup',
'wcfg':{'scrolledlist_items':self.params.CALCULATIONTYPES,
'history':0, 'dropdown':1,
'selectioncommand':self.calculationParamUpdate,
'listheight':80
},
'gridcfg':{'sticky':'we', 'row':0, 'column':1}
})
ifd.append({'name':'pbeTypeLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Poisson-Boltzmann equation type:'},
'gridcfg':{'row':1, 'column':0, 'sticky':'e'}
})
ifd.append({'name':'pbeType',
'widgetType':Pmw.ComboBox,
'parent':'mathGroup',
'wcfg':{'scrolledlist_items':self.params.PBETYPES,
'history':0,'dropdown':1, 'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we', 'row':1, 'column':1}
})
ifd.append({'name':'boundaryConditionsLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Boundary conditions:'},
'gridcfg':{'row':2, 'column':0, 'sticky':'e'}
})
ifd.append({'name':'boundaryConditions',
'widgetType':Pmw.ComboBox,
'parent':'mathGroup',
'wcfg':{'scrolledlist_items':self.params.BOUNDARYTYPES,
'history':0, 'dropdown':1, 'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we', 'row':2, 'column':1}
})
ifd.append({'name':'chargeDiscretizationLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Charge discretization:'},
'gridcfg':{'sticky':'e', 'row':3, 'column':0}
})
ifd.append({'name':'chargeDiscretization',
'widgetType':Pmw.ComboBox,
'parent':'mathGroup',
'wcfg':{'scrolledlist_items':
self.params.CHARGEDISCRETIZATIONTYPES,'history':0,
'dropdown':1, 'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we', 'row':3, 'column':1}
})
ifd.append({'name':'surfaceCalculationLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Surface smoothing method:'},
'gridcfg':{'sticky':'e', 'row':4, 'column':0}
})
ifd.append({'name':'surfaceCalculation',
'widgetType':Pmw.ComboBox,
'parent':'mathGroup',
'wcfg':{'scrolledlist_items':
self.params.SURFACECALCULATIONTYPES,'history':0,
'dropdown':1, 'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we', 'row':4, 'column':1}
})
ifd.append({'name':'sdensLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Sphere density:'},
'gridcfg':{'row':5, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'sdens',
'parent':'mathGroup',
'wcfg':{'command':self.calculationParamUpdate,
'value':self.params.sdens,
'validate':{'validator':'real', 'min':0.01}},
'gridcfg':{'sticky':'nsew', 'row':5, 'column':1}
})
ifd.append({'name':'splineWindowLabel',
'widgetType':Tkinter.Label,
'parent':'mathGroup',
'wcfg':{'text':'Spline window (Angstroms):'},
'gridcfg':{'row':6, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'splineWindow',
'parent':'mathGroup',
'wcfg':{'command':self.calculationParamUpdate,
'value':self.params.splineWindow,
'validate':{'validator':'real', 'min':0.01}},
'gridcfg':{'sticky':'nsew', 'row':6, 'column':1}
})
# MOLECULES GROUP
ifd.append({'name':"moleculesGroup",
'widgetType':Pmw.Group,
'parent':'Calculation',
'container':{'moleculesGroup':'w.interior()'},
'wcfg':{'tag_text':'Molecules'},
'gridcfg':{'sticky':'nswe'}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'molecule1Select',
'parent':'moleculesGroup',
'wcfg':{'text':'Select Molecule 1 ...',
'command':self.molecule1Select},
'gridcfg':{'sticky':'ew', 'row':0, 'column':0}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'molecule1',
'parent':'moleculesGroup',
'tooltip':"Click on Select Molecule 1 button to set this.",
'wcfg':{'command':self.calculationParamUpdate,
'entry_state':'disabled',
'value':self.params.molecule1Path},
'gridcfg':{'sticky':'ew', 'row':0, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'molecule2Select',
'parent':'moleculesGroup',
'wcfg':{'text':'Select Molecule 2 ...',
'command':self.molecule2Select},
'gridcfg':{'sticky':'ew', 'row':1, 'column':0}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'molecule2',
'parent':'moleculesGroup',
'tooltip':"Click on Select Molecule 2 button to set this.",
'wcfg':{'command':self.calculationParamUpdate,
'entry_state':'disabled',
'value':self.params.molecule2Path},
'gridcfg':{'sticky':'ew', 'row':1, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'complexSelect',
'parent':'moleculesGroup',
'wcfg':{'text':'Select Complex ...',
'command':self.complexSelect},
'gridcfg':{'sticky':'ew', 'row':2, 'column':0}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'complex',
'parent':'moleculesGroup',
'tooltip':"Click on Select Complex button to set this.",
'wcfg':{'command':self.calculationParamUpdate,
'entry_state':'disabled',
'value':self.params.complexPath},
'gridcfg':{'sticky':'ew', 'row':2, 'column':1}
})
## FILE GROUP
ifd.append({'name':"fileGroup",
'widgetType':Pmw.Group,
'parent':'Calculation',
'container':{'fileGroup':'w.interior()'},
'wcfg':{'tag_text':'Output'},
'gridcfg':{'sticky':'nwe'}
})
ifd.append({'name':'energyTypesLabel',
'widgetType':Tkinter.Label,
'parent':'fileGroup',
'wcfg':{'text':'Energy: '},
'gridcfg':{'sticky':'e','row':0, 'column':0}
})
ifd.append({'name':'energyOutput',
'widgetType':Pmw.ComboBox,
'parent':'fileGroup',
'wcfg':{'scrolledlist_items':
self.params.ENERGYOUTPUTTYPES,
'dropdown':1, 'history':0,'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we', 'row':0, 'column':1}
})
ifd.append({'name':'forceTypesLabel',
'widgetType':Tkinter.Label,
'parent':'fileGroup',
'wcfg':{'text':'Force: '},
'gridcfg':{'sticky':'e', 'row':1,'column':0}
})
ifd.append({'name':'forceOutput',
'widgetType':Pmw.ComboBox,
'parent':'fileGroup',
'wcfg':{'scrolledlist_items':
self.params.FORCEOUTPUTTYPES,
'dropdown':1, 'history':0, 'listheight':80,
'selectioncommand':self.calculationParamUpdate},
'gridcfg':{'sticky':'we','row':1,'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'outputFilesSelect',
'parent':'fileGroup',
'wcfg':{'text':'More output options ...',
'command':self.setOutputFiles},
'gridcfg':{'sticky':'ew','row':2,'column':1}
})
## PROFILES GROUP
ifd.append({'name':"ProfilesGroup",
'widgetType':Pmw.Group,
'parent':'Calculation',
'container':{'ProfilesGroup':'w.interior()'},
'wcfg':{'tag_text':'Profiles'},
'gridcfg':{'sticky':'we'}
})
ifd.append({'name':'Profiles',
'widgetType':Pmw.ComboBox,
'parent':'ProfilesGroup',
'wcfg':{'scrolledlist_items':PROFILES, 'listheight':80,
'dropdown':1,'history':1,'autoclear':1,
'selectioncommand':self.select_profile
},
'gridcfg':{'sticky':'we', 'row':0, 'column':0}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'Profiles_Add',
'parent':'ProfilesGroup',
'wcfg':{'text':'Add',
'command':self.add_profile,
'state':state_GUI},
'gridcfg':{'sticky':'ew', 'row':0, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'Profiles_Remove',
'parent':'ProfilesGroup',
'wcfg':{'text':'Remove',
'state':state_GUI,
'command':self.remove_profile},
'gridcfg':{'sticky':'ew', 'row':0, 'column':2}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'Profiles_Run',
'parent':'ProfilesGroup',
'wcfg':{'text':'Run',
'state':state_GUI,
'command':self.apbsOutput},
'gridcfg':{'sticky':'we', 'row':1, 'column':0}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'Profiles_Load',
'parent':'ProfilesGroup',
'wcfg':{'text':'Load',
'command':self.loadProfile},
'gridcfg':{'sticky':'we', 'row':1, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'Profiles_Save',
'parent':'ProfilesGroup',
'wcfg':{'text':'Save',
'state':state_GUI,
'command':self.saveProfile},
'gridcfg':{'sticky':'we', 'row':1, 'column':2}
})
## GRID PAGE
ifd.append({'name':"generalGridGroup",
'widgetType':Pmw.Group,
'parent':'Grid',
'container':{'generalGridGroup':'w.interior()'},
'wcfg':{'tag_text':'General'},
'gridcfg':{'sticky':'wnse'}
})
ifd.append({'name':'generalXLabel',
'widgetType':Tkinter.Label,
'parent':'generalGridGroup',
'wcfg':{'text':'X','fg':'red','font':(ensureFontCase('times'), 15, 'bold')},
'gridcfg':{'row':0, 'column':1}
})
ifd.append({'name':'generalYLabel',
'widgetType':Tkinter.Label,
'parent':'generalGridGroup',
'wcfg':{'text':'Y','fg':'green','font':(ensureFontCase('times'),15,'bold')},
'gridcfg':{'row':0, 'column':2}
})
ifd.append({'name':'generalZLabel',
'widgetType':Tkinter.Label,
'parent':'generalGridGroup',
'wcfg':{'text':'Z','fg':'blue','font':(ensureFontCase('times'),15,' bold')},
'gridcfg':{'row':0, 'column':3}
})
ifd.append({'name':'gridPointsLabel',
'widgetType':Tkinter.Label,
'parent':'generalGridGroup',
'wcfg':{'text':'Grid Points:'},
'gridcfg':{'row':1, 'column':0}
})
ifd.append({'widgetType':SliderWidget,
'name':'gridPointsX',
'parent':'generalGridGroup',
'wcfg':{'label':' ',
'minval':9,'maxval':689,
'left':15,
'command':self.gridParamUpdate,
'init':65,'immediate':1,
'sliderType':'int',
'lookup': self.params.GRID_VALUES},
'gridcfg':{'sticky':'wens', 'row':1, 'column':1}
})
ifd.append({'widgetType':SliderWidget,
'name':'gridPointsY',
'parent':'generalGridGroup',
'wcfg':{'label':' ',
'minval':9,'maxval':689,
'left':15,
'command':self.gridParamUpdate,
'init':65,'immediate':1,
'sliderType':'int',
'lookup': self.params.GRID_VALUES},
'gridcfg':{'sticky':'wens', 'row':1, 'column':2}
})
ifd.append({'widgetType':SliderWidget,
'name':'gridPointsZ',
'parent':'generalGridGroup',
'wcfg':{'label':' ',
'minval':9,'maxval':689,
'left':15,
'command':self.gridParamUpdate,
'init':65,'immediate':1,
'sliderType':'int',
'lookup': self.params.GRID_VALUES},
'gridcfg':{'sticky':'wens', 'row':1, 'column':3}
})
ifd.append({'name':"coarseGridGroup",
'widgetType':Pmw.Group,
'parent':'Grid',
'container':{'coarseGridGroup':'w.interior()'},
'wcfg':{'tag_text':'Coarse Grid'},
'gridcfg':{'sticky':'wnse'}
})
ifd.append({'name':'coarseXLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'X','fg':'red','font':(ensureFontCase('times'), 15, 'bold')},
'gridcfg':{'row':1, 'column':1}
})
ifd.append({'name':'coarseYLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'Y','fg':'green','font':(ensureFontCase('times'),15,'bold')},
'gridcfg':{'row':1, 'column':2}
})
ifd.append({'name':'coarseZLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'Z','fg':'blue','font':(ensureFontCase('times'),15, 'bold')},
'gridcfg':{'row':1, 'column':3}
})
ifd.append({'widgetType':Tkinter.Checkbutton,
'name':'showCoarseGrid',
'parent':'coarseGridGroup',
'defaultValue':0,
'wcfg':{'text':'Show Coarse Grid',
'command':self.gridParamUpdate,
'variable':Tkinter.BooleanVar()},
'gridcfg':{'sticky':'w','row':5, 'column':0}
})
ifd.append({'name':'coarseLengthLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'Length:'},
'gridcfg':{'row':2, 'column':0}
})
ifd.append({'name':'coarseLengthX',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':2, 'column':1, 'sticky':'wnse'},
'wcfg':{'text':None, 'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseLengthX, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'red'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseLengthY',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':2, 'column':2, 'sticky':'wnse'},
'wcfg':{ 'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseLengthY, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'green'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseLengthZ',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':2, 'column':3, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseLengthZ, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'blue'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseCenterLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'Center:'},
'gridcfg':{'row':3, 'column':0}
})
ifd.append({'name':'coarseCenterX',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':3, 'column':1, 'sticky':'wnse'},
'wcfg':{ 'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseCenterX, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'red'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseCenterY',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':3, 'column':2, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseCenterY, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'green'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseCenterZ',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'coarseGridGroup',
'gridcfg':{'row':3, 'column':3, 'sticky':'wnse'},
'wcfg':{'text':None, 'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.coarseCenterZ, 'oneTurn':1000,
'type':'float',
'increment':1,
'canvascfg':{'bg':'blue'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'coarseResolutionLabel',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':'Resolution:'},
'gridcfg':{'row':4, 'column':0}
})
ifd.append({'name':'coarseResolutionX',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':"%5.3f"%self.coarseResolutionX()},
'gridcfg':{'row':4, 'column':1}
})
ifd.append({'name':'coarseResolutionY',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':"%5.3f"%self.coarseResolutionY()},
'gridcfg':{'row':4, 'column':2}
})
ifd.append({'name':'coarseResolutionZ',
'widgetType':Tkinter.Label,
'parent':'coarseGridGroup',
'wcfg':{'text':"%5.3f"%self.coarseResolutionZ()},
'gridcfg':{'row':4, 'column':3}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'autocenterCoarseGrid',
'parent':'coarseGridGroup',
'wcfg':{'text':'Autocenter',
'command':self.autocenterCoarseGrid},
'gridcfg':{'sticky':'ew', 'row':5, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'autosizeCoarseGrid',
'parent':'coarseGridGroup',
'wcfg':{'text':'Autosize',
'command':self.autosizeCoarseGrid},
'gridcfg':{'sticky':'ew', 'row':5, 'column':2}
})
ifd.append({'name':"fineGridGroup",
'widgetType':Pmw.Group,
'parent':'Grid',
'container':{'fineGridGroup':'w.interior()'},
'wcfg':{'tag_text':'Fine Grid'},
'gridcfg':{'sticky':'wnse'}
})
ifd.append({'name':'fineXLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'X','fg':'red','font':(ensureFontCase('times'), 15, 'bold')},
'gridcfg':{'row':1, 'column':1}
})
ifd.append({'name':'fineYLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'Y','fg':'green','font':(ensureFontCase('times'),15,'bold')},
'gridcfg':{'row':1, 'column':2}
})
ifd.append({'name':'fineZLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'Z','fg':'blue','font':(ensureFontCase('times'),15, 'bold')},
'gridcfg':{'row':1, 'column':3}
})
ifd.append({'widgetType':Tkinter.Checkbutton,
'name':'showFineGrid',
'parent':'fineGridGroup',
'defaultValue':0,
'wcfg':{'text':'Show Fine Grid',
'command':self.gridParamUpdate,
'variable':Tkinter.BooleanVar()},
'gridcfg':{'sticky':'w','row':5, 'column':0}
})
ifd.append({'name':'fineLengthLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'Length:'},
'gridcfg':{'row':2, 'column':0}
})
ifd.append({'name':'fineLengthX',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':2, 'column':1, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineLengthX, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'red'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineLengthY',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':2, 'column':2, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineLengthY, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'green'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineLengthZ',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':2, 'column':3, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':2,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineLengthZ, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'blue'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineCenterLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'Center:'},
'gridcfg':{'row':3, 'column':0}
})
ifd.append({'name':'fineCenterX',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':3, 'column':1, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineCenterX, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'red'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineCenterY',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':3, 'column':2, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineCenterY, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'green'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineCenterZ',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'parent':'fineGridGroup',
'gridcfg':{'row':3, 'column':3, 'sticky':'wnse'},
'wcfg':{'showLabel':1,
'min':None,
'lockBMin':1, 'lockBMax':1,
'lockBIncrement':1,
'value':self.params.fineCenterZ, 'oneTurn':1000,
'type':'float',
'increment':.25,
'canvascfg':{'bg':'blue'},
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'callback':self.gridParamUpdate,
'continuous':1,
'wheelPad':1, 'width':100,'height':15}
})
ifd.append({'name':'fineResolutionLabel',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':'Resolution:'},
'gridcfg':{'row':4, 'column':0}
})
ifd.append({'name':'fineResolutionX',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':"%5.3f"%self.fineResolutionX()},
'gridcfg':{'row':4, 'column':1}
})
ifd.append({'name':'fineResolutionY',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':"%5.3f"%self.fineResolutionY()},
'gridcfg':{'row':4, 'column':2}
})
ifd.append({'name':'fineResolutionZ',
'widgetType':Tkinter.Label,
'parent':'fineGridGroup',
'wcfg':{'text':"%5.3f"%self.fineResolutionZ()},
'gridcfg':{'row':4, 'column':3}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'autocenterFineGrid',
'parent':'fineGridGroup',
'wcfg':{'text':'Autocenter',
'command':self.autocenterFineGrid},
'gridcfg':{'sticky':'ew', 'row':5, 'column':1}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'autosizeFineGrid',
'parent':'fineGridGroup',
'wcfg':{'text':'Autosize',
'command':self.autosizeFineGrid},
'gridcfg':{'sticky':'ew', 'row':5, 'column':2}
})
ifd.append({'name':"systemResourcesGroup",
'widgetType':Pmw.Group,
'parent':'Grid',
'container':{'systemResourcesGroup':'w.interior()'},
'wcfg':{'tag_text':'System Resources'},
'gridcfg':{'sticky':'wnse'}
})
ifd.append({'name':'gridPointsLabel',
'widgetType':Tkinter.Label,
'parent':'systemResourcesGroup',
'wcfg':{'text':'Total grid points: '},
'gridcfg':{'row':0, 'column':0, 'sticky':'e'}
})
ifd.append({'name':'gridPointsNumberLabel',
'widgetType':Tkinter.Label,
'parent':'systemResourcesGroup',
'wcfg':{'text':"%d"%self.totalGridPoints()},
'gridcfg':{'row':0, 'column':1, 'sticky':'w'}
})
ifd.append({'name':'mallocLabel',
'widgetType':Tkinter.Label,
'parent':'systemResourcesGroup',
'wcfg':{'text':'Memory to be allocated (MB): '},
'gridcfg':{'row':1, 'column':0, 'sticky':'e'}
})
ifd.append({'name':'mallocSizeLabel',
'widgetType':Tkinter.Label,
'parent':'systemResourcesGroup',
'wcfg':{'text':"%5.3f"%self.memoryToBeAllocated()},
'gridcfg':{'row':1, 'column':1, 'sticky':'w'}
})
## PHYSICS PAGE
ifd.append({'name':'parametersGroup',
'widgetType':Pmw.Group,
'parent':'Physics',
'container':{'parametersGroup':'w.interior()'},
'wcfg':{'tag_text':"Parameters"},
'gridcfg':{'sticky':'snwe'}
})
ifd.append({'name':'proteinDielectricLabel',
'widgetType':Tkinter.Label,
'parent':'parametersGroup',
'wcfg':{'text':'Protein dielectric:'},
'gridcfg':{'row':0, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'proteinDielectric',
'parent':'parametersGroup',
'wcfg':{'command':self.physicsParamUpdate,
'value':self.params.proteinDielectric,
'validate':{'validator':'real', 'min':0}},
'gridcfg':{'sticky':'ew', 'row':0, 'column':1}
})
ifd.append({'name':'solventDielectricLabel',
'widgetType':Tkinter.Label,
'parent':'parametersGroup',
'wcfg':{'text':'Solvent dielectric:'},
'gridcfg':{'row':1, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'solventDielectric',
'parent':'parametersGroup',
'wcfg':{'command':self.physicsParamUpdate,
'value':self.params.solventDielectric,
'validate':{'validator':'real', 'min':0}},
'gridcfg':{'sticky':'nsew', 'row':1, 'column':1}
})
ifd.append({'name':'solventRadiusLabel',
'widgetType':Tkinter.Label,
'parent':'parametersGroup',
'wcfg':{'text':'Solvent radius (Angstroms):'},
'gridcfg':{'row':2, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'solventRadius',
'parent':'parametersGroup',
'wcfg':{'command':self.physicsParamUpdate,
'value':self.params.solventRadius,
'validate':{'validator':'real', 'min':0}},
'gridcfg':{'sticky':'nsew', 'row':2, 'column':1}
})
ifd.append({'name':'systemTemperatureLabel',
'widgetType':Tkinter.Label,
'parent':'parametersGroup',
'wcfg':{'text':'System temperature (Kelvin):'},
'gridcfg':{'row':3, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'systemTemperature',
'parent':'parametersGroup',
'wcfg':{'command':self.physicsParamUpdate,
'value':self.params.systemTemperature,
'validate':{'validator':'real', 'min':0}},
'gridcfg':{'sticky':'nsew', 'row':3, 'column':1}
})
ifd.append({'name':'ionsGroup',
'widgetType':Pmw.Group,
'parent':'Physics',
'container':{'ionsGroup':'w.interior()'},
'wcfg':{'tag_text':"Ions"},
'gridcfg':{'sticky':'wnse'}
})
ifd.append({'widgetType':Pmw.Group,
'name':'SaltGroup',
'container':{'SaltGroup':'w.interior()'},
'parent':'ionsGroup',
'wcfg':{
'tag_pyclass':Tkinter.Checkbutton,
'tag_text':'Salt',
'tag_command':self.SaltUpdate,
'tag_variable': self.salt_var,
},
})
# ifd.append({'name':'ionConcentrationLabel',
# 'widgetType':Tkinter.Label,
# 'wcfg':{'text':'Salt contains ions with radius 2 (Angstrom), and charges +1(e) and -1(e)'},
# 'parent':'SaltGroup',
# 'gridcfg':{'row':0, 'column':0,'columnspan':2, 'sticky':'we'}
# })
ifd.append({'name':'ionConcentrationLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Concentration (M):'},
'parent':'SaltGroup',
'gridcfg':{'row':1, 'column':0, 'sticky':'e'}
})
ifd.append({'widgetType':ThumbWheel,
'name':'saltConcentration',
'parent':'SaltGroup',
'wcfg':{'text':None, 'showLabel':1,
'min':0,
'value':0.01, 'oneTurn':0.1,
'type':'float',
'increment':0.01,
'wheelLabcfg1':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'grey'},
'wheelLabcfg2':{'font':
(ensureFontCase('times'), 15, 'bold'), 'fill':'black'},
'continuous':1,
'wheelPad':1, 'width':150,'height':14},
'gridcfg':{'row':1, 'column':1, 'sticky':'w'}
})
ifd.append({'name':'ionsButtons',
'widgetType':Pmw.ButtonBox,
'parent':'ionsGroup',
'wcfg':{},
'componentcfg':[{'name':'Add More...',
'cfg':{'command':self.addIon}},
{'name':'Remove', 'cfg':{'command':self.removeIon}}]
})
ifd.append({'name':'ionsListLabel',
'widgetType':Tkinter.Label,
'parent':'ionsGroup',
'wcfg':{'text':'Charge, Concentration, Radius'}
})
ifd.append({'widgetType':Pmw.ScrolledListBox,
'name':'ionsList',
'parent':'ionsGroup',
'wcfg':{}
})
## WEB SERVICES PAGE
if APBSservicesFound:
ifd.append({'name':"APBSservicesGroup",
'widgetType':Pmw.Group,
'parent':'Web Service',
'container':{'APBSservicesGroup':'w.interior()'},
'wcfg':{'tag_text':'APBS Web Services'},
'gridcfg':{'sticky':'wen'}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'WS_Run',
'parent':'APBSservicesGroup',
'wcfg':{'text':'Run APBS Remote',
'state':state_GUI,
'command':self.apbsRunRemote},
'gridcfg':{'sticky':'ew', 'row':0, 'column':0}
})
ifd.append({'widgetType':Pmw.ComboBox,
'name':'web service address',
'parent':'APBSservicesGroup',
'wcfg':{'scrolledlist_items':
('http://ws.nbcr.net/opal2/services/ApbsOpalService',),
'selectioncommand':self.toggle_usrpass,
'listheight':100,
'dropdown':1, 'history':1, 'autoclear':1},
'gridcfg':{'sticky':'ew', 'row':0, 'column':1}
})
ifd.append({'widgetType':Tkinter.Label,
'name':'UserName_Label',
'parent':'APBSservicesGroup',
'wcfg':{'text':'User Name'},
'gridcfg':{'sticky':'e', 'row':1, 'column':0}
})
ifd.append({'widgetType':Tkinter.Entry,
'name':'UserName_Entry',
'parent':'APBSservicesGroup',
'wcfg':{},
'gridcfg':{'sticky':'ew', 'row':1, 'column':1}
})
ifd.append({'widgetType':Tkinter.Label,
'name':'Password_Label',
'parent':'APBSservicesGroup',
'wcfg':{'text':'Password'},
'gridcfg':{'sticky':'e', 'row':2, 'column':0}
})
ifd.append({'widgetType':Tkinter.Entry,
'name':'Password_Entry',
'parent':'APBSservicesGroup',
'wcfg':{'show':'*'},
'gridcfg':{'sticky':'ew', 'row':2, 'column':1}
})
ifd.append({'widgetType':Tkinter.Label,
'name':'Remember_Label',
'parent':'APBSservicesGroup',
'wcfg':{'text':'Remember User Name and Password'},
'gridcfg':{'sticky':'e', 'row':3, 'column':0}
})
ifd.append({'widgetType':Tkinter.Checkbutton,
'name':'Remember_Checkbutton',
'parent':'APBSservicesGroup',
'variable':self.RememberLogin_var,
'gridcfg':{'sticky':'w', 'row':3, 'column':1}
})
# self.Parallel_var =Tkinter.BooleanVar()
# self.Parallel_var.set(0)
# ifd.append({'widgetType':Pmw.Group,
# 'name':'ParallelGroup',
# 'container':{'ParallelGroup':'w.interior()'},
# 'parent':'APBSservicesGroup',
# 'wcfg':{
# 'tag_pyclass':Tkinter.Checkbutton,
# 'tag_text':'Parallel',
# 'tag_command':self.ParallelParamUpdate,
# 'tag_variable': self.Parallel_var,
# },
# 'gridcfg':{'sticky':'new','row':4, 'column':0,'columnspan':2
# , 'pady':'10' }
# })
# ifd.append({'widgetType':Pmw.EntryField,
# 'name':'npx',
# 'parent':'ParallelGroup',
# 'state':'disabled',
# 'wcfg':{
# 'validate':{'validator':'integer', 'min':1},
# 'label_text':'The number of processors in the X direction (npx):',
# 'labelpos':'w',
# 'value':2,},
# 'gridcfg':{ 'row':0, 'column':0}
# })
# ifd.append({'widgetType':Pmw.EntryField,
# 'name':'npy',
# 'parent':'ParallelGroup',
# 'wcfg':{
# 'validate':{'validator':'integer', 'min':1},
# 'label_text':'The number of processors in the Y direction (npy):',
# 'labelpos':'w',
# 'value':1,},
# 'gridcfg':{'row':1, 'column':0}
# })
# ifd.append({'widgetType':Pmw.EntryField,
# 'name':'npz',
# 'parent':'ParallelGroup',
#
# 'wcfg':{
# 'validate':{'validator':'integer', 'min':1},
# 'label_text':'The number of processors in the Z direction (npz):',
# 'labelpos':'w',
# 'value':1,
# },
# 'gridcfg':{'row':2, 'column':0}
# })
# ifd.append({'widgetType':Pmw.EntryField,
# 'name':'ofrac',
# 'parent':'ParallelGroup',
# 'wcfg':{
# 'validate':{'validator':'real', 'min':0,'max':1},
# 'label_text':'Overlap factor (ofrac); a value between 0 and 1 :',
# 'labelpos':'w',
# 'value':0.1,
# },
# 'gridcfg':{'row':3, 'column':0}
# })
ifd.append({'name':'APBSservicesLabel1',
'widgetType':Tkinter.Label,
'parent':'APBSservicesGroup',
'wcfg':{'text':''},
'gridcfg':{'sticky':'ensw', 'row':5,'column':0,
'columnspan':2}
})
ifd.append({'name':'APBSservicesLabel2',
'widgetType':Tkinter.Label,
'parent':'APBSservicesGroup',
'wcfg':{'text':''},
'gridcfg':{'sticky':'ensw', 'row':6,'column':0,
'columnspan':2}
})
ifd.append({'name':'APBSservicesLabel3',
'widgetType':Tkinter.Label,
'parent':'APBSservicesGroup',
'wcfg':{'text':''},
'gridcfg':{'sticky':'ensw', 'row':7,'column':0,
'columnspan':2}
})
ifd.append({'name':'APBSservicesLabel4',
'widgetType':Tkinter.Label,
'parent':'APBSservicesGroup',
'wcfg':{'text':''},
'gridcfg':{'sticky':'ensw', 'row':8,'column':0,
'columnspan':2}
})
ifd.append({'name':'WS_ProgressBar',
'widgetType':Tkinter.Frame,
'parent':'APBSservicesGroup',
'wcfg':{'height':30},
'gridcfg':{'sticky':'ew', 'row':9,'column':0,
'columnspan':2}
})
ifd.append({'name':'APBS_WS_DX_Label',
'widgetType':Tkinter.Label,
'parent':'APBSservicesGroup',
'wcfg':{'text':''},
'gridcfg':{'sticky':'ensw', 'row':10,'column':0,
'columnspan':2}
})
else:
ifd.append({'name':'WS_Not_Found',
'parent':'Web Service',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Error importing APBS Web Services.',
'bg':'Red'},
})
ifd.append({'name':'WS_install',
'parent':'Web Service',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Please make sure that ZSI and PyZML packages are properly installed.'},
})
ifd.append({'name':'WS_http',
'parent':'Web Service',
'widgetType':Tkinter.Label,
'wcfg':{'text':'http://nbcr.sdsc.edu/services/apbs/apbs-py.html',
'fg':'Blue','cursor':'hand1'},
})
self.ifd = ifd
return ifd
def SaltUpdate(self):
"Toggles ParallelGroup widget"
self.cmdForms['default'].descr.entryByName['SaltGroup']['widget'].\
toggle()
def changeMenuState(self, state):
"Updates the state of DisplayIsocontours, MapPotential2MSMS and SisplayOrthoSlice manues."
#change_Menu_state(self.vf.APBSDisplayIsocontours, state)
if self.vf.hasGui:
if hasattr(self.vf, 'APBSMapPotential2MSMS'):
change_Menu_state(self.vf.APBSMapPotential2MSMS, state)
#change_Menu_state(self.vf.APBSDisplayOrthoSlice, state)
def ParallelParamUpdate(self):
"Toggles ParallelGroup widget"
self.cmdForms['default'].descr.entryByName['ParallelGroup']['widget'].\
toggle()
def WS_http(self, event):
"Opens webbrowser at http://nbcr.sdsc.edu/services/apbs/apbs-py.html"
import webbrowser
webbrowser.open('http://nbcr.sdsc.edu/services/apbs/apbs-py.html')
def toggle_usrpass(self, event):
"Toggles User Name and Parssword entry and label"
descr = self.cmdForms['default'].descr
address = descr.entryByName['web service address']['widget'].get()
address = address.strip()
if address.find('https://') != 0:
descr.entryByName['UserName_Label']['widget'].grid_forget()
descr.entryByName['UserName_Entry']['widget'].grid_forget()
descr.entryByName['Password_Label']['widget'].grid_forget()
descr.entryByName['Password_Entry']['widget'].grid_forget()
descr.entryByName['Remember_Label']['widget'].grid_forget()
descr.entryByName['Remember_Checkbutton']['widget'].grid_forget()
else:
apply(descr.entryByName['UserName_Label']['widget'].grid, () ,
descr.entryByName['UserName_Label']['gridcfg'])
apply(descr.entryByName['UserName_Entry']['widget'].grid, () ,
descr.entryByName['UserName_Entry']['gridcfg'])
apply(descr.entryByName['Password_Label']['widget'].grid, () ,
descr.entryByName['Password_Label']['gridcfg'])
apply(descr.entryByName['Password_Entry']['widget'].grid, () ,
descr.entryByName['Password_Entry']['gridcfg'])
apply(descr.entryByName['Remember_Label']['widget'].grid, () ,
descr.entryByName['Remember_Label']['gridcfg'])
apply(descr.entryByName['Remember_Checkbutton']['widget'].grid, () ,
descr.entryByName['Remember_Checkbutton']['gridcfg'])
cascadeName = "Electrostatics"
APBSSetupGUI = CommandGUI()
APBSSetupGUI.addMenuCommand('menuRoot','Compute','Setup',
cascadeName=cascadeName, separatorAbove=1)
class APBSRun(MVCommand):
"""APBSRun runs Adaptive Poisson-Boltzmann Solver (APBS)\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSRun
\nCommand name : APBSRun
\nSynopsis:\n
None <--- APBSRun(molName, APBSParamName = "Default", **kw)
\nOptional Arguments:\n
molecule1 - name of the molecule1
molecule2 - name of the molecule2
complex - name of the complex
APBSParamName - Name of the key in mol.APBSParams dictionary
"""
def onAddCmdToViewer(self):
"""Called when APBSRun is loaded"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
def onAddObjectToViewer(self, object):
"""Called when object is added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'normal')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
def guiCallback(self):
"""GUI callback"""
if self.vf.APBSSetup.params.projectFolder == 'apbs-project':
self.doit()
else:
self.doit(self.vf.APBSSetup.params)
def __call__(self, molecule1=None, molecule2=None, _complex=None,
APBSParamName='Default', blocking=False, **kw):
"""None <--- APBSRun(nodes, **kw)\n
\nOptional Arguments :\n
molecule1 - molecule1 as MolKit object or a string
molecule2 - name of the molecule2
complex - name of the complex
APBSParamName = Name of the key in mol.APBSParams dictionary
"""
if not molecule1 and len(self.vf.Mols) == 1:
molecule1 = self.vf.Mols[0].name
if not molecule1:
tkMessageBox.showinfo("No Molecule Selected", "Please use Compute -> Electrostatics -> Setup and select a molecule.")
return 'ERROR'
mol1 = self.vf.expandNodes(molecule1)
assert isinstance(mol1, MoleculeSet)
assert len(mol1) == 1
if not mol1: return 'ERROR'
molecule1 = mol1[0].name
if molecule2:
mol2 = self.vf.expandNodes(molecule2)
assert isinstance(mol2, MoleculeSet)
assert len(mol2) == 1
if not mol2: return 'ERROR'
molecule2 = mol2[0].name
# elif molecule1 == None:
# val = self.vf.APBSSetup.showForm('moleculeSelect', modal=1, blocking=1)
# if not val:
# return
# else:
# if len(val['moleculeListSelect'])==0: return
# molecule1 = val['moleculeListSelect'][0]
# self.vf.APBSSetup.refreshAll()
params = self.vf.APBSSetup.params
if molecule1:
params.projectFolder=os.path.join(os.getcwd(),
"apbs-"+molecule1)
params.molecule1Path = \
self.vf.APBSSetup.moleculeListSelect(molecule1)
self.vf.APBSSetup.mol1Name = molecule1
if not params.molecule1Path:
return
if molecule2:
if not _complex:
import warnings
warnings.warn("Complex is missing!")
return
params.projectFolder += "_"+molecule2+"_"+_complex
params.molecule2Path = \
self.vf.APBSSetup.moleculeListSelect(molecule2)
self.vf.APBSSetup.mol2Name = molecule2
params.complexPath = \
self.vf.APBSSetup.moleculeListSelect(_complex)
self.vf.APBSSetup.complexName = _complex
if not os.path.exists(params.projectFolder):
try:
os.mkdir(params.projectFolder)
except:
from user import home
tmp = os.path.split(params.projectFolder)
params.projectFolder = home + os.sep + tmp[-1]
if not os.path.exists(params.projectFolder):
os.mkdir(params.projectFolder)
try:
open(params.projectFolder+os.sep+'io.mc','w')
except:
from user import home
tmp = os.path.split(params.projectFolder)
params.projectFolder = home + os.sep + tmp[-1]
if not os.path.exists(params.projectFolder):
os.mkdir(params.projectFolder)
if molecule2:
abs_path = os.path.join(params.projectFolder,
molecule2+".pqr")
if not os.path.exists(abs_path) or \
self.vf.APBSPreferences.overwrite_pqr:
mol = self.vf.getMolFromName(molecule2)
self.vf.APBSSetup.mol2Name = molecule2
if hasattr(mol,'flag_copy_pqr') and mol.flag_copy_pqr:
self.copyFix(params.molecule2Path, abs_path)
else:
shutil.move(params.molecule2Path, abs_path)
mol.parser.filename = abs_path
params.molecule2Path = molecule2+".pqr"
params.molecule2Path = \
os.path.split(params.molecule2Path)[-1]
abs_path = os.path.join(params.projectFolder, _complex +".pqr")
mol = self.vf.getMolFromName(_complex)
self.vf.APBSSetup.complexName = _complex
if not os.path.exists(abs_path) or \
self.vf.APBSPreferences.overwrite_pqr:
if hasattr(mol,'flag_copy_pqr') and mol.flag_copy_pqr:
self.copyFix(params.complexPath, abs_path)
else:
shutil.move(params.complexPath, abs_path)
mol.parser.filename = abs_path
params.complexPath = _complex +".pqr"
params.complexPath = os.path.split(params.complexPath)[-1]
abs_path = os.path.join(params.projectFolder, molecule1+".pqr")
if not os.path.exists(abs_path) or \
self.vf.APBSPreferences.overwrite_pqr:
mol = self.vf.getMolFromName(molecule1.replace('-','_'))
self.vf.APBSSetup.mol1Name = mol.name
if hasattr(mol,'flag_copy_pqr') and mol.flag_copy_pqr:
self.copyFix(params.molecule1Path,abs_path)
else:
shutil.move(params.molecule1Path,abs_path)
mol.parser.filename = abs_path
self.vf.APBSPreferences.overwrite_pqr = False
params.molecule1Path = molecule1+".pqr"
params.molecule1Path = os.path.split(params.molecule1Path)[-1]
if self.vf.APBSSetup.cmdForms.has_key('default'):
self.vf.APBSSetup.cmdForms['default'].descr.entryByName\
['molecule1']['widget'].\
setentry(params.molecule1Path)
if APBSParamName != 'Default':
mol = self.vf.getMolFromName(molecule1.replace('-','_'))
self.vf.APBSSetup.mol1Name = mol.name
params = mol.APBSParams[APBSParamName]
dest_path = os.path.join(params.projectFolder,
APBSParamName+'_potential.dx')
pickle_name = os.path.join(params.projectFolder,
APBSParamName+".apbs.pf")
if os.path.exists(pickle_name):
fp = open(pickle_name, 'r')
tmp_params = pickle.load(fp)
fp.close()
flag_run = True # this flags if apbs with the same paramters
# has been already run
for key in tmp_params.__dict__:
if key != 'ions':
if tmp_params.__dict__[key] != \
params.__dict__[key]:
flag_run = False
break
else:
if len(tmp_params.ions) != \
len(params.ions):
flag_run = False
break
for i in range(len(tmp_params.ions)):
if tmp_params.ions[i].charge != \
params.ions[i].charge:
flag_run = False
break
if tmp_params.ions[i].concentration != \
params.ions[i].concentration:
flag_run = False
break
if tmp_params.ions[i].radius != \
params.ions[i].radius:
flag_run = False
break
if flag_run == True:
answer = False
if self.vf.APBSSetup.cmdForms.has_key('default') and \
self.vf.APBSSetup.cmdForms['default'].f.winfo_toplevel().\
wm_state() == 'normal':
answer = tkMessageBox.askyesno("WARNING",\
"APBS with the same parameters has been already run."+
"\n\nWould you like to continue?",
parent=self.vf.APBSSetup.cmdForms['default'].root)
else:
answer = tkMessageBox.askyesno("WARNING",\
"APBS with the same parameters has been already run."+
"\n\nWould you like to continue?")
if answer != True:
#self.vf.APBSSetup.loadProfile(pickle_name)
return
self.vf.APBSSetup.refreshCalculationPage()
if not self.vf.APBSSetup.flag_grid_changed:
self.vf.APBSSetup.autocenterCoarseGrid()
self.vf.APBSSetup.autosizeCoarseGrid()
self.vf.APBSSetup.autocenterFineGrid()
self.vf.APBSSetup.autosizeFineGrid()
self.vf.APBSSetup.refreshGridPage()
if self.doitWrapper(molecule1, molecule2, _complex,
APBSParamName=APBSParamName,
blocking=blocking) == 'error':
self.vf.APBSSetup.showForm('default', \
modal=0, blocking=1,initFunc=self.vf.APBSSetup.refreshAll)
return
def copyFix(self, fileSource, fileDest):
"""Copies a file from fileSource to fileDest and fixes end-of-lines"""
newlines = []
for line in open(fileSource, 'rb').readlines():
if line[-2:] == '\r\n':
line = line[:-2] + '\n'
newlines.append(line)
open(fileDest, 'w').writelines(newlines)
def doit(self, molecule1=None, molecule2=None, _complex=None,
APBSParamName = 'Default', blocking=False):
"""doit function"""
return self.vf.APBSSetup.apbsOutput(molecule1, molecule2, _complex,
blocking=blocking)
APBSRun_GUI = CommandGUI()
APBSRun_GUI.addMenuCommand('menuRoot', 'Compute',
'Compute Potential Using APBS', cascadeName=cascadeName)
class APBSMap_Potential_to_MSMS(MVCommand):
"""APBSMapPotential2MSMS maps APBS Potential into MSMS Surface\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSMap_Potential_to_MSMS
\nCommand name : APBSMapPotential2MSMS
\nSynopsis:\n
None <--- APBSMapPotential2MSMS(mol = mol, potential = potential)
\nRequired Arguments:\n
mol = name of the molecule\n
potential = string representing where potential.dx is located\n"""
def onAddCmdToViewer(self):
"""Called when added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
self.custom_quality = 5.0
def onAddObjectToViewer(self, object):
"""Called when object is added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'normal')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
cmap = self.vf.GUI.VIEWER.FindObjectByName('root|cmap')
if cmap:
cmap.Set(visible=False)
self.vf.GUI.VIEWER.Redraw()
def doit(self, mol = None, potential = None):
"""doit function for APBSMap_Potential_to_MSMS"""
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.VIEWER.master.config(cursor='watch')
self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='watch')
from MolKit.molecule import Molecule
if isinstance(mol, Molecule):
mol = self.vf.getMolFromName(mol.name.replace('-','_'))
elif type(mol) == str:
mol = self.vf.getMolFromName(mol.replace('-','_'))
else:
import warnings
warnings.warn("APBSMap_Potential_to_MSMS doit(): mol should either be a molecule object or molecule name.")
return
self.vf.assignAtomsRadii(mol, overwrite=True,log=False)
mol.allAtoms._radii = {}
for atom in mol.allAtoms:
if hasattr(atom,'pqrRadius'):
atom._radii['pqrRadius'] = atom.pqrRadius
if hasattr(atom,'vdwRadius'):
atom._radii['vdwRadius'] = atom.vdwRadius
if hasattr(atom,'covalentRadius'):
atom._radii['covalentRadius'] = atom.covalentRadius
if self.quality == 'low':
self.vf.computeMSMS(mol, density = 1.0, log = False)
elif self.quality == 'medium':
self.vf.computeMSMS(mol, density = 3.0, log = False)
elif self.quality == 'high':
self.vf.computeMSMS(mol, density = 6.0, log = False)
else:
self.vf.computeMSMS(mol, density = self.custom_quality, log = False)
if not self.vf.commands.has_key('vision'):
self.vf.browseCommands('visionCommands',log=False)
g = mol.geomContainer.geoms['MSMS-MOL']
g.Set(inheritSharpColorBoundaries = False, sharpColorBoundaries =False)
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.VIEWER.master.config(cursor='watch')
self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='watch')
if self.vf.vision.ed is None:
self.vf.vision(log=False)
self.vf.vision(log=False)
self.APBS_MSMS_Net = self.vf.vision.ed.getNetworkByName("APBSPot2MSMS")
if not self.APBS_MSMS_Net:
from mglutil.util.packageFilePath import findFilePath
Network_Path = findFilePath("VisionInterface/APBSPot2MSMS_net.py",
'Pmv')
self.vf.vision.ed.loadNetwork(Network_Path, takefocus=False)
self.APBS_MSMS_Net = self.vf.vision.ed.getNetworkByName\
("APBSPot2MSMS")[0]
else:
self.APBS_MSMS_Net = self.APBS_MSMS_Net[0]
mol_node = self.APBS_MSMS_Net.getNodeByName('Choose Molecule')[0]
mol_node.run(force=1)
mol_node.inputPorts[1].widget.set(mol.name)
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.VIEWER.master.config(cursor='watch')
self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='watch')
file_DX = self.APBS_MSMS_Net.getNodeByName('Pmv Grids')[0]
potentialName = os.path.basename(potential)
if not self.vf.grids3D.has_key(potentialName):
self.vf.Grid3DReadAny(potential, show=False, normalize=False)
self.vf.grids3D[potentialName].geomContainer['Box'].Set(visible=0)
file_DX.inputPorts[0].widget.set(potentialName)
file_DX.run(force=1)
macro = self.APBS_MSMS_Net.getNodeByName('Map Pot On Geom')[0]
offset = macro.macroNetwork.getNodeByName('Offset')[0]
check = offset.getInputPortByName('dial')
check.widget.set(self.distance)
button = macro.macroNetwork.getNodeByName('Checkbutton')[0]
check = button.getInputPortByName('button')
check.widget.set(0)
colormap = macro.macroNetwork.getNodeByName('Color Map')[0]
colormap.run(force=1) # this forces Color node to run
self.APBS_MSMS_Net.run()
colormap.outputPortByName['legend'].data.Set(unitsString='kT/e')
def guiCallback(self):
"""GUI callback for APBSMap_Potential_to_MSMS"""
if not self.vf.commands.has_key('computeMSMS'):
self.vf.browseCommands("msmsCommands",log=False)
file_name,ext = os.path.splitext(self.vf.APBSSetup.params.molecule1Path)
mol_name = os.path.split(file_name)[-1]
mol_list = ()
for name in self.vf.Mols.name:
mol_list += (name,)
ifd = InputFormDescr(title = 'Map Potential to Surface Parameters')
if mol_name in mol_list:
default_mol = mol_name
else:
default_mol = mol_list[0]
from MolKit.molecule import Molecule
if len(self.vf.selection):
selection = self.vf.selection[0]
if isinstance(selection, Molecule):
default_mol = selection.name
self.default_mol = default_mol
ifd.append({'name':'mol_list',
'widgetType':Pmw.ComboBox,
'tooltip':
"""Click on the fliparrow to view
the list of available molecules""" ,
'defaultValue':default_mol,
'wcfg':{'labelpos':'new','label_text':'Please select molecule',
'scrolledlist_items':mol_list, 'history':0,'entry_width':15,
'fliparrow':1, 'dropdown':1, 'listheight':80},
'gridcfg':{'sticky':'we', 'row':1, 'column':0}
})
ifd.append({'name':'quality',
'widgetType':Pmw.RadioSelect,
'tooltip':
""" low, medium and high correspond to molecular
surface density of 1, 3, and 6 points respectively""" ,
'listtext':['low', 'medium', 'high', 'custom'],
'defaultValue':'medium',
'wcfg':{'orient':'vertical','labelpos':'w',
'label_text':'Surface \nquality ',
'command':self.select_custom,
'hull_relief':'ridge', 'hull_borderwidth':2,
'padx':0,
'buttontype':'radiobutton'},
'gridcfg':{'sticky': 'ewns', 'row':2, 'column':0, }})
ifd.append({'name':'distance',
'widgetType':ThumbWheel,
'tooltip':
"""offset along the surface normal at which the potential will be looked up""",
'gridcfg':{'sticky':'we'},
'wcfg':{'value':1.0,'oneTurn':10,
'type':'float',
'increment':0.1,
'precision':1,
'continuous':False,
'wheelPad':3,'width':140,'height':20,
'labCfg':{'text':'Distance from surface',
'side':'top'},
'gridcfg':{'sticky': 'we', 'row':3, 'column':0, }
}
})
val = self.vf.getUserInput(ifd,initFunc = self.initFunc)
if not val: return
self.quality = val['quality']
self.distance = val['distance']
molecule_selected = val['mol_list'][0]
if molecule_selected == mol_name:
potential_dx = os.path.join(self.vf.APBSSetup.params.projectFolder,
mol_name + '.potential.dx')
self.doitWrapper(mol = mol_name, potential = potential_dx)
else:
potential_dx = os.path.join(os.getcwd(), "apbs-"+ molecule_selected)
potential_dx = os.path.join(potential_dx, molecule_selected + \
'.potential.dx')
if not os.path.exists(potential_dx):
self.vf.APBSRun(molecule1 = molecule_selected)
if not hasattr(self.vf.APBSSetup, 'cmd'): return
while self.vf.APBSSetup.cmd.ok.configure()['state'][-1] != \
'normal':
self.vf.GUI.ROOT.update()
self.doitWrapper(mol=molecule_selected, potential=potential_dx)
self.vf.APBSSetup.potential = os.path.basename(potential_dx)
if self.vf.hasGui:
change_Menu_state(self.vf.APBSDisplayIsocontours, 'normal')
change_Menu_state(self.vf.APBSDisplayOrthoSlice, 'normal')
if hasattr(self.vf,'APBSVolumeRender'):
change_Menu_state(self.vf.APBSVolumeRender, 'normal')
def __call__(self, mol=None, potential=None, quality='medium', **kw):
"""Maps potential.dx into MSMS using\n
VisionInterface/APBSPot2MSMS_net.py\n
Required Arguments:\n
mol = name of the molecule\n
potential = location of the potential.dx file\n"""
molNode = self.vf.expandNodes(mol)
assert isinstance(molNode, MoleculeSet)
assert len(molNode) == 1
if not molNode: return 'ERROR'
mol = molNode[0].name
kw['mol'] = mol
if potential is None:
potential_dx = os.path.join(os.getcwd(), "apbs-"+ mol)
potential_dx = os.path.join(potential_dx, mol + '.potential.dx')
kw['potential'] = potential_dx
kw['quality'] = quality
else:
kw['potential'] = potential
if kw.has_key('mol') and kw.has_key('potential'):
if kw.has_key('quality'):
self.quality = kw['quality']
else:
self.quality = 'medium' #default
if kw.has_key('distance'):
self.distance = kw['ditance']
else:
self.distance = 1.0 #default
self.doitWrapper(mol=kw['mol'],potential=kw['potential'])
else:
print >>sys.stderr, "mol and/or potential is missing"
return
def select_custom(self, evt):
if evt == 'custom':
ifd = InputFormDescr(title='Select Surface Density')
ifd.append({'name':'density',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type a value manually""",
'gridcfg':{'sticky':'we'},
'wcfg':{'value':self.custom_quality,'oneTurn':2,
'type':'float',
'increment':0.1,
'precision':1,
'continuous':False,
'wheelPad':2,'width':145,'height':18,
'labCfg':{'text':'Density '},
}
})
val = self.vf.getUserInput(ifd,)
if val:
self.custom_quality = val['density']
def initFunc(self, ifd):
"""This function initializes GUI for APBSMap_Potential_to_MSMS"""
ifd.descr.entryByName['mol_list']['widget']._entryWidget.\
config(state='readonly')
def setupUndoBefore(self, mol = None, potential = None ):
# The undo of this display command depends on which displayMSMS cmd
# was used previously and results in displaying what faces were displayed previously
undoCmd = """self.displayMSMS(self.getMolFromName('%s'), surfName=['MSMS-MOL'], negate=1, redraw =1, topCommand=0)
cmap = self.GUI.VIEWER.FindObjectByName('root|cmap')
if cmap:
cmap.Set(visible=False)"""%(mol)
self.vf.undo.addEntry((undoCmd), ('Map Potential to Molecular Surface'))
APBSMap_Potential_to_MSMS_GUI = CommandGUI()
APBSMap_Potential_to_MSMS_GUI.addMenuCommand('menuRoot','Compute',
'Map Potential to Surface', cascadeName=cascadeName)
class APBSDisplay_Isocontours(MVCommand):
"""APBSDisplayIsocontours displays APBS Potential Isocontours\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBS_Display_Isocontours
\nCommand name : APBSDisplayIsocontours
\nSynopsis:\n
None <--- APBSDisplayIsocontours(potential = potential)
\nRequired Arguments:\n
potential = string representing where potential.dx is located\n"""
def onAddCmdToViewer(self):
"""Called when added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
# def onAddObjectToViewer(self, object):
# """Called when object is added to viewer"""
# change_Menu_state(self, 'normal')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
def dismiss(self, event = None):
"""Withdraws GUI form"""
self.cancel = True
self.ifd.entryByName['-visible']['wcfg']['variable'].set(False)
self.ifd.entryByName['+visible']['wcfg']['variable'].set(False)
self.Left_Visible()
self.Right_Visible()
self.form.withdraw()
def doit(self, potential = None):
"""doit function"""
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.VIEWER.master.config(cursor='watch')
self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='watch')
if not self.vf.commands.has_key('vision'):
self.vf.browseCommands('visionCommands',log=False)
if self.vf.vision.ed is None:
self.vf.vision(log=False)
self.vf.vision(log=False)
self.APBS_Iso_Net = self.vf.vision.ed.getNetworkByName("APBSIsoContour")
if not self.APBS_Iso_Net:
from mglutil.util.packageFilePath import findFilePath
Network_Path = findFilePath("VisionInterface/APBSIsoContour_net.py",
'Pmv')
self.vf.vision.ed.loadNetwork(Network_Path, takefocus=False)
self.APBS_Iso_Net = self.vf.vision.ed.\
getNetworkByName("APBSIsoContour")[0]
else:
self.APBS_Iso_Net = self.APBS_Iso_Net[0]
file_DX = self.APBS_Iso_Net.getNodeByName('Pmv Grids')[0]
potentialName = os.path.basename(potential)
if not self.vf.grids3D.has_key(potentialName):
grid = self.vf.Grid3DReadAny(potential, show=False, normalize=False)
if grid:
self.vf.grids3D[potentialName].geomContainer['Box'].Set(visible=0)
else:
return
file_DX.inputPorts[0].widget.set(potentialName)
self.APBS_Iso_Net.run()
def guiCallback(self):
"""GUI callback"""
file_name,ext = os.path.splitext(self.vf.APBSSetup.params.molecule1Path)
mol_name = os.path.split(file_name)[-1]
self.mol_list = ()
for name in self.vf.Mols.name:
potential_dx = os.path.join(os.getcwd(), "apbs-" + name)
potential_dx = os.path.join(potential_dx, name + '.potential.dx')
if os.path.exists(potential_dx):
self.mol_list += (name,)
potential_dx = os.path.join(self.vf.APBSSetup.params.projectFolder,
mol_name + '.potential.dx')
if os.path.exists(potential_dx):
self.mol_list += (mol_name,)
if len(self.mol_list) == 0:
self.vf.warningMsg("Please run APBS to generate potential.dx", "ERROR potential.dx is missing")
return
if mol_name in self.mol_list:
default_mol = mol_name
else:
default_mol = self.mol_list[0]
from MolKit.molecule import Molecule
if len(self.vf.selection):
selection = self.vf.selection[0]
if isinstance(selection, Molecule):
default_mol = selection.name
self.combo_default = default_mol
potential_dx = os.path.join(os.getcwd(), "apbs-" + default_mol)
potential_dx = os.path.join(potential_dx, default_mol + '.potential.dx')
self.doitWrapper(potential = potential_dx)
self.Isocontour_L = self.APBS_Iso_Net.getNodeByName('Left_Isocontour')[0]
self.Isocontour_R = self.APBS_Iso_Net.getNodeByName('Right_Isocontour')[0]
self.cancel = False
if not hasattr(self, 'ifd'):
self.buildForm()
else:
self.form.deiconify()
self.ifd.entryByName['mol_list']['widget'].setlist(self.mol_list)
self.ifd.entryByName['+Silder']['widget'].canvas.config(bg="Blue")
self.ifd.entryByName['-Silder']['widget'].canvas.config(bg="Red")
self.ifd.entryByName['-visible']['wcfg']['variable'].set(True)
self.ifd.entryByName['+visible']['wcfg']['variable'].set(True)
self.ifd.entryByName['mol_list']['widget'].setentry(self.mol_list[0])
self.ifd.entryByName['mol_list']['widget']._entryWidget.\
config(state='readonly')
self.APBS_Iso_Net.run()
self.Left_Visible()
self.Right_Visible()
self.vf.GUI.ROOT.config(cursor='')
self.vf.GUI.VIEWER.master.config(cursor='')
self.vf.GUI.MESSAGE_BOX.tx.component('text').config(cursor='xterm')
def run(self):
"""Animates isocontours"""
inv_d = 1./(self.maxi - self.mini)
data = Numeric.arange(inv_d,inv_d*500,inv_d*15).tolist()
data += Numeric.arange(inv_d*500,inv_d*5000,inv_d*150).tolist()
for values in data:
if self.cancel:
return
self.ifd.entryByName['+Silder']['widget'].set(values)
#self.Isocontour_L.getInputPortByName('isovalue').widget.set(values)
self.ifd.entryByName['-Silder']['widget'].set(-values)
#self.Isocontour_R.getInputPortByName('isovalue').widget.set(-values)
self.vf.GUI.VIEWER.update()
def __call__(self, **kw):
"""Displays APBS Potential Isocontours using\n
VisionInterface/APBSIsoContour_net.py\n
Required Arguments:\n
potential = location of the potential.dx file\n"""
if kw.has_key('potential'):
self.doitWrapper(potential = kw['potential'])
else:
print >>sys.stderr, "potential is missing"
return
def buildForm(self):
"""Builds 'default' GUI form'"""
VolumeStats = self.APBS_Iso_Net.getNodeByName('VolumeStats')[0]
self.maxi = VolumeStats.getOutputPortByName('maxi').data
self.mini = VolumeStats.getOutputPortByName('mini').data
self.Update(1);self.Update(-1)
self.ifd = ifd = InputFormDescr(title="Isocontours Control Panel")
ifd.append({'name':'mol_list',
'widgetType':Pmw.ComboBox,
'tooltip':
"""Click on the fliparrow to view
the list of available molecules""" ,
'defaultValue': self.combo_default,
'wcfg':{'labelpos':'e','label_text':'Select molecule',
'scrolledlist_items':self.mol_list, 'history':0,
'selectioncommand':self.Combo_Selection,
'entry_width':5,
'fliparrow':1, 'dropdown':1, 'listheight':80},
'gridcfg':{'sticky':'we', 'row':0, 'column':0,'columnspan':2}
})
ifd.append({'name':'+Silder',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type the isovalue manually""",
'wcfg':{'value':1.0,'oneTurn':10,
'type':'float',
'increment':0.1,
'min':0,
'precision':2,
'wheelPad':2,'width':120,'height':19,
'callback':self.Update,
}
})
ifd.append({'name':'-Silder',
'widgetType':ThumbWheel,
'tooltip':
"""Right click on the widget to type the isovalue manually""",
'wcfg':{'value':-1.0,'oneTurn':10,
'type':'float',
'increment':0.1,
'precision':2,
'max':-0.000000001,
'wheelPad':2,'width':120,'height':19,
'callback':self.Update,
},
})
ifd.append({'widgetType':Tkinter.Checkbutton,
'tooltip':"""(De)select this checkbutton to
(un)display blue isocontour""",
'name':'+visible',
'defaultValue':1,
'wcfg':{'text':'Blue isocontour',
'command':self.Left_Visible,
'bg':'Blue','fg':'White',
'variable':Tkinter.BooleanVar()},
'gridcfg':{'sticky':'e','row':1, 'column':1}
})
ifd.append({'widgetType':Tkinter.Checkbutton,
'tooltip':"""(De)select this checkbutton to
(un)display red isocontour""",
'name':'-visible',
'defaultValue':1,
'wcfg':{'text':'Red isocontour',
'command':self.Right_Visible,
'bg':'Red','fg':'White',
'variable':Tkinter.BooleanVar()},
'gridcfg':{'sticky':'e','row':2, 'column':1}
})
ifd.append({'name':'dismiss',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Cancel',
'command':self.dismiss},
'gridcfg':{'sticky':'wens','row':3, 'column':0}
})
ifd.append({'name':'run',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Animate',
'command':self.run},
'gridcfg':{'sticky':'wens','row':3, 'column':1}
})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
return ifd
def Combo_Selection(self, mol_name):
"""
This command is triggered as selectioncommand for ComboBox mol_list
"""
potential_dx = os.path.join(os.getcwd(), "apbs-" + mol_name)
potential_dx = os.path.join(potential_dx, mol_name + '.potential.dx')
self.doitWrapper(potential = potential_dx)
def Left_Visible(self):
"""Sets "+polygons" and "left_label" objects visible state"""
left_object = self.vf.GUI.VIEWER.GUI.objectByName('+polygons')
left_label = self.vf.GUI.VIEWER.GUI.objectByName('LeftLabel')
visible = self.ifd.entryByName['+visible']['wcfg']['variable'].get()
left_object.Set(visible = visible)
left_label.Set(visible = visible)
self.vf.GUI.VIEWER.Redraw()
def Right_Visible(self):
"""Sets "-polygons" and "right_label" objects visible states"""
right_object = self.vf.GUI.VIEWER.GUI.objectByName('-polygons')
right_label = self.vf.GUI.VIEWER.GUI.objectByName('RightLabel')
visible = self.ifd.entryByName['-visible']['wcfg']['variable'].get()
right_object.Set(visible = visible)
right_label.Set(visible = visible)
self.vf.GUI.VIEWER.Redraw()
def Update(self,val):
"""Updates Isocontour_L or Isocontour_R"""
if val > 0:
self.Isocontour_R.getInputPortByName('isovalue').widget.set(val)
else:
self.Isocontour_L.getInputPortByName('isovalue').widget.set(val)
APBSDisplay_Isocontours_GUI = CommandGUI()
APBSDisplay_Isocontours_GUI.addMenuCommand('menuRoot', 'Compute', \
'Isocontour Potential', cascadeName=cascadeName)
from DejaVu.colorTool import RedWhiteBlueARamp
class APBSDisplayOrthoSlice(MVCommand):
"""APBSDisplayOrthoslice displays APBS Potential Orthoslice\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSDisplayOrthoslice
\nCommand name : APBSDisplayOrthoslice
\nSynopsis:\n
None <--- APBSDisplayOrthoslice()
"""
def onAddCmdToViewer(self):
"""Called when added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
# def onAddObjectToViewer(self, object):
# """Called when object is added to viewer"""
# change_Menu_state(self, 'normal')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
potential = object.name +'.potential.dx'
try:
self.vf.Grid3DCommands.select(potential)
self.vf.Grid3DAddRemove.remove()
except:
pass #can't remove from 3D Grid Rendering widget
def doit(self):
"""doit function"""
self.vf.Grid3DCommands.show()
self.vf.Grid3DCommands.select(self.vf.APBSSetup.potential)
self.vf.Grid3DCommands.Checkbuttons['OrthoSlice'].invoke()
grid = self.vf.grids3D[self.vf.APBSSetup.potential]
self.vf.Grid3DOrthoSlice.select()
self.vf.Grid3DOrthoSlice.X_vis.set(True)
self.vf.Grid3DOrthoSlice.Y_vis.set(True)
self.vf.Grid3DOrthoSlice.Z_vis.set(True)
self.vf.Grid3DOrthoSlice.createX()
self.vf.Grid3DOrthoSlice.createY()
self.vf.Grid3DOrthoSlice.createZ()
self.vf.Grid3DOrthoSlice.ifd.entryByName['X_Slice']['widget'].set(grid.dimensions[0]/2)
self.vf.Grid3DOrthoSlice.ifd.entryByName['Y_Slice']['widget'].set(grid.dimensions[1]/2)
self.vf.Grid3DOrthoSlice.ifd.entryByName['Z_Slice']['widget'].set(grid.dimensions[2]/2)
mini = - grid.std/10.
maxi = grid.std/10.
grid.geomContainer['OrthoSlice']['X'].colormap.configure(ramp=RedWhiteBlueARamp(), mini=mini, maxi=maxi)
grid.geomContainer['OrthoSlice']['Y'].colormap.configure(ramp=RedWhiteBlueARamp(), mini=mini, maxi=maxi)
grid.geomContainer['OrthoSlice']['Z'].colormap.configure(ramp=RedWhiteBlueARamp(), mini=mini, maxi=maxi)
def guiCallback(self):
"""GUI callback"""
self.doitWrapper()
def __call__(self, **kw):
"""Displays APBS Potential Isocontours using\n
VisionInterface/APBSIsoContour_net.py\n
Required Arguments:\n
potential = location of the potential.dx file\n"""
self.doitWrapper()
APBSDisplayOrthoSlice_GUI = CommandGUI()
APBSDisplayOrthoSlice_GUI.addMenuCommand('menuRoot', 'Compute', \
'Display OrthoSlice', cascadeName=cascadeName)
class APBSVolumeRender(MVCommand):
"""APBSVolumeRender \n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSVolumeRender
\nCommand name : APBSVolumeRender
\nSynopsis:\n
None <--- APBSAPBSVolumeRender()
"""
def checkDependencies(self, vf):
if not vf.hasGui:
return 'ERROR'
from Volume.Renderers.UTVolumeLibrary import UTVolumeLibrary
test = UTVolumeLibrary.VolumeRenderer()
flagVolume = test.initRenderer()
if not flagVolume:
return 'ERROR'
def onAddCmdToViewer(self):
"""Called when added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
# def onAddObjectToViewer(self, object):
# """Called when object is added to viewer"""
# change_Menu_state(self, 'normal')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
def doit(self):
"""doit function"""
grid = self.vf.grids3D[self.vf.APBSSetup.potential]
mini = - grid.std/10.
maxi = grid.std/10.
tmpMax = grid.maxi
tmpMin = grid.mini
grid.mini = mini
grid.maxi = maxi
self.vf.Grid3DCommands.show()
self.vf.Grid3DCommands.select(self.vf.APBSSetup.potential)
self.vf.Grid3DCommands.Checkbuttons['VolRen'].invoke()
self.vf.Grid3DVolRen.select()
widget = self.vf.Grid3DVolRen.ifd.entryByName['VolRen']['widget']
widget.colorGUI()
ramp = RedWhiteBlueARamp()
ramp[:,3] = Numeric.arange(0,0.25,1./(4*256.),'f')
grid = self.vf.grids3D[self.vf.APBSSetup.potential]
widget.ColorMapGUI.configure(ramp=ramp, mini=mini, maxi=maxi)
widget.ColorMapGUI.apply_cb()
grid.mini = tmpMin
grid.maxi = tmpMax
def guiCallback(self):
"""GUI callback"""
self.doitWrapper()
def __call__(self, **kw):
"""Displays APBS Potential Isocontours using\n
VisionInterface/APBSIsoContour_net.py\n
Required Arguments:\n
potential = location of the potential.dx file\n"""
self.doitWrapper()
APBSVolumeRender_GUI = CommandGUI()
APBSVolumeRender_GUI.addMenuCommand('menuRoot', 'Compute', \
'Volume Renderer', cascadeName=cascadeName)
from tkFileDialog import *
class APBSLoad_Profile(MVCommand):
"""APBSLoadProfile loads APBS parameters\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSLoad_Profile
\nCommand name : APBSLoadProfile
\nSynopsis:\n
None <--- APBSLoadProfile(filename = None)
\nOptional Arguments:\n
filename = name of the file containing APBS parameters\n
"""
def doit(self, filename = None):
"""doit function"""
self.vf.APBSSetup.loadProfile(filename=filename)
def guiCallback(self):
"""GUI callback"""
filename=askopenfilename(filetypes=[('APBS Profile','*.apbs.pf')],\
title="Load APBS Profile")
if filename:
self.doitWrapper(filename=filename)
def __call__(self, **kw):
"""None <--- APBSSave_Profile()\n
Calls APBSSetup.loadProfile\n"""
if kw.has_key('filename'):
self.doitWrapper(filename=kw['filename'])
else:
if self.vf.APBSSetup.cmdForms.has_key('default') and \
self.vf.APBSSetup.cmdForms['default'].f.winfo_toplevel().\
wm_state() == 'normal':
filename=askopenfilename(filetypes=\
[('APBS Profile','*.apbs.pf')],
title="Load APBS Profile",
parent=self.vf.APBSSetup.cmdForms['default'].root)
else:
filename = askopenfilename(filetypes =
[('APBS Profile','*.apbs.pf')], title = "Load APBS Profile")
if filename:
self.doitWrapper(filename=filename)
APBSLoad_Profile_GUI = CommandGUI()
APBSLoad_Profile_GUI.addMenuCommand('menuRoot', 'Compute', 'Load Profile',
cascadeName=cascadeName, separatorAbove=1)
class APBSSave_Profile(MVCommand):
"""APBSSaveProfile saves APBS parameters\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSSave_Profile
\nCommand name : APBSSaveProfile
\nSynopsis:\n
None <--- APBSSaveProfile(filename = None)
\nOptional Arguments:\n
filename = name of the file where APBS parameters are to be saved\n
"""
def onAddCmdToViewer(self):
"""Called when added to viewer"""
if self.vf.hasGui:
change_Menu_state(self, 'disabled')
def onRemoveObjectFromViewer(self, object):
"""Called when object is removed from viewer"""
if self.vf.hasGui:
if len(self.vf.Mols) == 0:
change_Menu_state(self, 'disabled')
def doit(self, Profilename=None):
"""doit function"""
self.vf.APBSSetup.saveProfile(Profilename=Profilename, fileFlag=True, flagCommand=True)
def guiCallback(self):
"""GUI callback"""
filename=asksaveasfilename(filetypes=[('APBS Profile','*.apbs.pf')],
title="Save APBS Profile As")
if filename:
self.doitWrapper(Profilename=filename)
def __call__(self, **kw):
"""None <--- APBSSave_Profile(filename = None)\n
Calls APBSSetup.saveProfile\n"""
if kw.has_key('Profilename'):
self.doitWrapper(Profilename=kw['Profilename'])
else:
if self.vf.APBSSetup.cmdForms.has_key('default') and \
self.vf.APBSSetup.cmdForms['default'].f.winfo_toplevel().\
wm_state() == 'normal':
filename = asksaveasfilename(filetypes=[('APBS Profile',
'*.apbs.pf')],title="Save APBS Profile As",
parent = self.vf.APBSSetup.cmdForms['default'].root)
else:
filename = asksaveasfilename(filetypes =
[('APBS Profile','*.apbs.pf')],title = "Save APBS Profile As")
if filename:
self.doitWrapper(Profilename=filename)
APBSSave_Profile_GUI = CommandGUI()
APBSSave_Profile_GUI.addMenuCommand('menuRoot', 'Compute', 'Save Profile',
cascadeName=cascadeName)
class APBSWrite_APBS_Parameter_File(MVCommand):
"""APBSOutputWrite writes APBS input file\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSWrite_APBS_Parameter_File
\nCommand name : APBSOutputWrite
\nSynopsis:\n
None <--- APBSOutputWrite(filename)
\nRequired Arguments:\n
filename = name of the apbs input file \n
"""
def doit(self, filename = None):
"""doit function for APBSWrite_APBS_Parameter_File"""
if filename:
self.vf.APBSSetup.params.SaveAPBSInput(filename)
def guiCallback(self, **kw):
"""
GUI Callback for APBSWrite_APBS_Parameter_File
Asks for the file name to save current parameters
"""
filename=asksaveasfilename(filetypes=[('APBS Paramter File','*.apbs')],
title="Save APBS Parameters As ")
apply ( self.doitWrapper, (filename,), kw)
APBSWrite_Parameter_File_GUI = CommandGUI()
APBSWrite_Parameter_File_GUI.addMenuCommand('menuRoot', 'Compute', \
'Write APBS Parameter File', cascadeName=cascadeName)
class APBSPreferences(MVCommand):
"""APBSPreferences allows to change APBS Preferences\n
\nPackage : Pmv
\nModule : APBSCommands
\nClass : APBSPreferences
\nCommand name : APBSPreferences
\nSynopsis:\n
None <--- APBSPreferences(APBS_Path = None, pdb2pqr_Path = None, ff = None,
debump = None, hopt = None, hdebump = None, watopt = None)
\nOptional Arguments:\n
APBS_Path -- path to apbs executable
pdb2pqr_Path -- path to pdb2pqr.py script
ff -- Force Field for pdb2pqr ('amber', 'charmm' or 'parse')
nodebump : Do not perform the debumping operation
nohopt : Do not perform hydrogen optimization
nohdebump : Do not perform hydrogen debumping
nowatopt : Do not perform water optimization
"""
def doit(self, APBS_Path = None, pdb2pqr_Path = None, ff = None,
nodebump = False, nohopt = False):
"""
doit function for APBSPreferences class
\nOptional Arguments:\n
APBS_Path -- path to apbs executable
pdb2pqr_Path -- path to pdb2pqr.py script
ff -- Force Field for pdb2pqr ('amber', 'charmm' or 'parse')
nodebump : Do not perform the debumping operation
nohopt : Do not perform hydrogen optimization
nohdebump : Do not perform hydrogen debumping
nowatopt : Do not perform water optimization
"""
self.overwrite_pqr = False
if APBS_Path:
self.vf.APBSSetup.params.APBS_Path = APBS_Path
if pdb2pqr_Path:
self.vf.APBSSetup.params.pdb2pqr_Path = pdb2pqr_Path
if ff:
self.vf.APBSSetup.params.pdb2pqr_ForceField = ff
if nodebump != self.nodebump_past:
self.nodebump_past = nodebump
self.nodebump.set(nodebump)
self.overwrite_pqr = True
if nohopt != self.nohopt_past:
self.nohopt_past = nohopt
self.nohopt.set(nohopt)
self.overwrite_pqr = True
def __init__(self):
MVCommand.__init__(self)
try:
self.nodebump = Tkinter.BooleanVar()
self.nodebump.set(False)
self.nohopt = Tkinter.BooleanVar()
self.nohopt.set(False)
except:
self.nodebump = False
self.nohopt = False
self.nodebump_past = False
self.nohopt_past = False
self.overwrite_pqr = False
def guiCallback(self):
"""GUI Callback for APBSPreferences"""
self.APBS_Path = self.vf.APBSSetup.params.APBS_Path
self.pdb2pqr_Path = self.vf.APBSSetup.params.pdb2pqr_Path
self.ff_arg = Tkinter.StringVar()
self.ff_arg.set(self.vf.APBSSetup.params.pdb2pqr_ForceField)
self.ifd = ifd = InputFormDescr(title="APBS Preferences")
## APBS PATH GROUP
ifd.append({'name':"APBS_Path",
'widgetType':Pmw.Group,
'container':{'APBS_Path':'w.interior()'},
'wcfg':{'tag_text':"Path to APBS executable"},
'gridcfg':{'sticky':'nswe','columnspan':5}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'APBS_Browse',
'parent':'APBS_Path',
'wcfg':{'text':'Browse ...',
'command':self.set_APBS_Path},
'gridcfg':{'sticky':'we', 'row':1, 'column':0}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'APBS_Location',
'parent':'APBS_Path',
'wcfg':{'value':self.APBS_Path},
'gridcfg':{'sticky':'ew', 'row':1, 'column':1}
})
ifd.append({'name':'APBSLabel',
'widgetType':Tkinter.Label,
'parent':'APBS_Path',
'wcfg':{'text':"""\nAdaptive Poisson-Boltzmann Solver \
(APBS) should be installed\n before it can be run locally. \n Source code \
and/or binaries for APBS can be downloaded from
http://agave.wustl.edu/apbs/download \n
Details on how to run APBS using Pmv can be found at
http://mccammon.ucsd.edu/pmv_apbs\n"""},
'gridcfg':{'columnspan':2, 'sticky':'ew', 'row':2, 'column':0} })
##pdb2pqr.py PATH GROUP
ifd.append({'name':"pqd2pqr_Path",
'widgetType':Pmw.Group,
'container':{'pdb2pqr_Path':'w.interior()'},
'wcfg':{'tag_text':"Path to pdb2pqr.py"},
'gridcfg':{'sticky':'nswe','columnspan':5}
})
ifd.append({'widgetType':Tkinter.Button,
'name':'pdb2pqr_Browse',
'parent':'pdb2pqr_Path',
'wcfg':{'text':'Browse ...',
'command':self.set_pdb2pqr_Path},
'gridcfg':{'sticky':'we', 'row':1, 'column':0}
})
ifd.append({'widgetType':Pmw.EntryField,
'name':'pdb2pqr_Location',
'parent':'pdb2pqr_Path',
'wcfg':{'value':self.pdb2pqr_Path},
'gridcfg':{'sticky':'ew', 'row':1, 'column':1}
})
ifd.append({'name':'pdb2pqrLabel',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_Path',
'wcfg':{'text':"""\npdb2pqr.py is needed to create PQR \
files used by APBS. \n One can also use PDB2PQR Server to convert PDB files \
into PQR\n http://agave.wustl.edu/pdb2pqr, \
and read that PQR file instead\n"""},
'gridcfg':{'columnspan':2, 'sticky':'ew', 'row':2, 'column':0}
})
##pdb2pqr.py FORCE FIELD GROUP
ifd.append({'name':"pdb2pqr_ForceField",
'widgetType':Pmw.Group,
'container':{'pdb2pqr_ForceField':'w.interior()'},
'wcfg':{'tag_text':"pdb2pqr ForceField"},
'gridcfg':{'sticky':'nswe','columnspan':5}
})
ifd.append({'name':"Radiobutton_AMBER",
'widgetType':Tkinter.Radiobutton,
'parent':'pdb2pqr_ForceField',
'wcfg':{'value':'amber',
'variable':self.ff_arg},
'gridcfg':{'sticky':'w','row':0, 'column':0}
})
ifd.append({'name':'Label_AMBER',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_ForceField',
'wcfg':{'text':'AMBER '},
'gridcfg':{'sticky':'w', 'row':0, 'column':1} })
ifd.append({'name':"Radiobutton_CHARMM",
'widgetType':Tkinter.Radiobutton,
'parent':'pdb2pqr_ForceField',
'wcfg':{'value':'charmm',
'variable':self.ff_arg},
'gridcfg':{'sticky':'w','row':0, 'column':2}
})
ifd.append({'name':'Label_CHARMM',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_ForceField',
'wcfg':{'text':'CHARMM '},
'gridcfg':{'sticky':'w', 'row':0, 'column':3} })
ifd.append({'name':"Radiobutton_PARSE",
'widgetType':Tkinter.Radiobutton,
'parent':'pdb2pqr_ForceField',
'wcfg':{'value':'parse',
'variable':self.ff_arg},
'gridcfg':{'sticky':'w','row':0, 'column':4}
})
ifd.append({'name':'Label_PARSE',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_ForceField',
'wcfg':{'text':'PARSE '},
'gridcfg':{'sticky':'w', 'row':0, 'column':5} })
##pdb2pqr.py OPTIONS GROUP
ifd.append({'name':"pdb2pqr_Options",
'widgetType':Pmw.Group,
'container':{'pdb2pqr_Options':'w.interior()'},
'wcfg':{'tag_text':"pdb2pqr Options"},
'gridcfg':{'sticky':'nswe','columnspan':5}
})
ifd.append({'name':"pdb2pqr_debump_Checkbutton",
'widgetType':Tkinter.Checkbutton,
'parent':'pdb2pqr_Options',
'wcfg':{
'variable':self.nodebump},
'gridcfg':{'sticky':'w','row':0, 'column':0}
})
ifd.append({'name':'pdb2pqr_debump_Label',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_Options',
'wcfg':{'text':'Do not perform the debumping operation'},
'gridcfg':{'sticky':'w', 'row':0, 'column':1} })
ifd.append({'name':"pdb2pqr_nohopt_Checkbutton",
'widgetType':Tkinter.Checkbutton,
'parent':'pdb2pqr_Options',
'wcfg':{
'variable':self.nohopt},
'gridcfg':{'sticky':'w','row':1, 'column':0}
})
ifd.append({'name':'pdb2pqr_nohopt_Label',
'widgetType':Tkinter.Label,
'parent':'pdb2pqr_Options',
'wcfg':{'text':'Do not perform hydrogen optimization'},
'gridcfg':{'sticky':'w', 'row':1, 'column':1} })
val = self.vf.getUserInput(ifd)
if val:
self.doitWrapper(val['APBS_Location'],
val['pdb2pqr_Location'],self.ff_arg.get(),\
nodebump = self.nodebump.get(), nohopt = self.nohopt.get())
def set_APBS_Path(self):
"""Sets APBS Path"""
filename=askopenfilename(filetypes=[('APBS Executable','apbs*')],\
title="Please select APBS Executable",parent=self.ifd[3]['widget'])
# FIXME: Maybe there is a better way to get the parent
if filename:
self.APBS_Path = filename
self.ifd.entryByName['APBS_Location']['widget'].setentry(filename)
def set_pdb2pqr_Path(self):
"""Sets pdb2pqr Path"""
filename=askopenfilename(filetypes=[('Python script','pdb2pqr.py')],
title="Please select pdb2pqr.py",parent=self.ifd[3]['widget'])
if filename:
self.pdb2pqr_Path = filename
self.ifd.entryByName['pdb2pqr_Location']['widget'].\
setentry(filename)
APBSPreferences_GUI = CommandGUI()
APBSPreferences_GUI.addMenuCommand('menuRoot', 'Compute', 'Preferences',
cascadeName=cascadeName )
commandList = [{'name':'APBSRun','cmd':APBSRun(),'gui':APBSRun_GUI}]
flagMSMS = False
try:
import mslib
flagMSMS = True
except:
pass
if flagMSMS:
commandList.append({'name':'APBSMapPotential2MSMS', 'cmd':
APBSMap_Potential_to_MSMS(),'gui':APBSMap_Potential_to_MSMS_GUI},
)
commandList.extend([
{'name':'APBSDisplayIsocontours', 'cmd':
APBSDisplay_Isocontours(),'gui':APBSDisplay_Isocontours_GUI},
{'name':'APBSDisplayOrthoSlice', 'cmd':
APBSDisplayOrthoSlice(),'gui':APBSDisplayOrthoSlice_GUI},
{'name':'APBSVolumeRender', 'cmd':
APBSVolumeRender(),'gui':APBSVolumeRender_GUI}
])
## flagVolume = False
## try:
## from Volume.Renderers.UTVolumeLibrary import UTVolumeLibrary
## test = UTVolumeLibrary.VolumeRenderer()
## flagVolume = test.initRenderer()
## except:
## pass
## if flagVolume:
## commandList.append({'name':'APBSVolumeRender', 'cmd':
## APBSVolumeRender(),'gui':APBSVolumeRender_GUI})
commandList.extend([
{'name':'APBSLoadProfile','cmd':APBSLoad_Profile(),'gui':
APBSLoad_Profile_GUI},
{'name':'APBSSaveProfile','cmd':APBSSave_Profile(),'gui':
APBSSave_Profile_GUI},
{'name':'APBSOutputWrite','cmd':APBSWrite_APBS_Parameter_File(),
'gui':APBSWrite_Parameter_File_GUI},
{'name':'APBSSetup','cmd':APBSSetup(),'gui':APBSSetupGUI},
{'name':'APBSPreferences','cmd':APBSPreferences(),'gui':
APBSPreferences_GUI}])
def initModule(viewer):
for _dict in commandList:
viewer.addCommand(_dict['cmd'],_dict['name'],_dict['gui'])
def change_Menu_state(self, state):
index = self.GUI.menuButton.menu.children[cascadeName].\
index(self.GUI.menu[4]['label'])
self.GUI.menuButton.menu.children[cascadeName].entryconfig(index, \
state = state)
```
#### File: MGLToolsPckgs/Pmv/colorCommandsGUI.py
```python
from ViewerFramework.VFCommand import CommandGUI, CommandProxy
class ColorCommandProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorCommand
command = ColorCommand()
loaded = self.vf.addCommand(command, 'color', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorGUI = CommandGUI()
ColorGUI.addMenuCommand('menuRoot', 'Color', 'Choose Color')
class ColorByAtomTypeProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByAtomType
command = ColorByAtomType()
loaded = self.vf.addCommand(command, 'colorByAtomType', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByAtomTypeGUI = CommandGUI()
ColorByAtomTypeGUI.addMenuCommand('menuRoot', 'Color', 'by Atom Type')
class ColorByDGProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByDG
command = ColorByDG()
loaded = self.vf.addCommand(command, 'colorAtomsUsingDG', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByDGGUI= CommandGUI()
ColorByDGGUI.addMenuCommand('menuRoot', 'Color', 'by DG colors')
class ColorByResidueTypeProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByResidueType
command = ColorByResidueType()
loaded = self.vf.addCommand(command, 'colorByResidueType', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByResidueTypeGUI = CommandGUI()
ColorByResidueTypeGUI.addMenuCommand('menuRoot', 'Color', 'RasmolAmino',
cascadeName = 'by Residue Type')
class ColorShapelyProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorShapelyColorCommand
command = ColorShapely()
loaded = self.vf.addCommand(command, 'colorResiduesUsingShapely', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorShapelyGUI = CommandGUI()
ColorShapelyGUI.addMenuCommand('menuRoot', 'Color', 'Shapely',
cascadeName = 'by Residue Type')
class ColorByChainProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByChain
command = ColorByChain()
loaded = self.vf.addCommand(command, 'colorByChains', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByChainGUI = CommandGUI()
ColorByChainGUI.addMenuCommand('menuRoot', 'Color', 'by Chain')
class ColorByMoleculeProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByMolecule
command = ColorByMolecule()
loaded= self.vf.addCommand(command, 'colorByMolecules', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByMoleculeGUI = CommandGUI()
ColorByMoleculeGUI.addMenuCommand('menuRoot', 'Color', 'by Molecules')
class ColorByInstanceProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByInstance
command = ColorByInstance()
loaded = self.vf.addCommand(command, 'colorByInstance', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByInstanceGUI = CommandGUI()
ColorByInstanceGUI.addMenuCommand('menuRoot', 'Color', 'by Instance')
class ColorByPropertiesProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByProperties
command = ColorByProperties()
loaded = self.vf.addCommand(command, 'colorByProperty', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByPropertiesGUI = CommandGUI()
ColorByPropertiesGUI.addMenuCommand('menuRoot', 'Color', 'by Properties')
class ColorByExpressionProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.colorCommands import ColorByExpression
command = ColorByExpression()
loaded = self.vf.addCommand(command, 'colorByExpression', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
ColorByExpressionGUI = CommandGUI()
ColorByExpressionGUI.addMenuCommand('menuRoot', 'Color', 'by Expression')
def initGUI(viewer):
viewer.addCommandProxy(ColorCommandProxy(viewer, ColorGUI))
viewer.addCommandProxy(ColorByAtomTypeProxy(viewer, ColorByAtomTypeGUI))
viewer.addCommandProxy(ColorByResidueTypeProxy(viewer, ColorByResidueTypeGUI))
viewer.addCommandProxy(ColorByDGProxy(viewer, ColorByDGGUI))
viewer.addCommandProxy(ColorShapelyProxy(viewer, ColorShapelyGUI))
viewer.addCommandProxy(ColorByChainProxy(viewer, ColorByChainGUI))
viewer.addCommandProxy(ColorByMoleculeProxy(viewer, ColorByMoleculeGUI))
viewer.addCommandProxy(ColorByInstanceProxy(viewer, ColorByInstanceGUI))
viewer.addCommandProxy(ColorByPropertiesProxy(viewer, ColorByPropertiesGUI))
#viewer.addCommandProxy(ColorByExpressionProxy(viewer, ColorByExpressionGUI))
```
#### File: MGLToolsPckgs/Pmv/colorMap.py
```python
from Tkinter import *
from DejaVu.colorTool import RGBRamp, ToRGB, ToHSV
import types, numpy.oldnumeric as Numeric
class ColorMapGUI(Frame):
def button_cb(self, event=None):
"""call back function for the buttons allowing to toggle between
different canvases.
This function hides the currentCanvas and shows the canvas
corresponding to the active radio button.
In addition it sets
self.currentCanvas : used to hide it next time we come in
self.currentLines : list of Canvas Line objects (one per canvas)
self.currentValues : list of numerical values (one per canvas)
self.getColor = function to be called to represent a color as a
Tk string
"""
var = self.currentCanvasVar.get()
newCanvas = self.canvas[var]
self.currentCanvas.forget()
newCanvas.pack(side=TOP)
self.currentCanvas = newCanvas
self.currentLines = self.lines[var]
self.currentValues = self.values[var]
self.getColor = self.getColorFunc[var]
self.current = var
def hueColor(self, val):
"""TkColorString <- hueColor(val)
val is an integer between 25 and 200.
returns color to be use to draw hue lines in hue canvas
"""
return self.hueColor[val-25]
def satColor(self, val):
"""TkColorString <- satColor(val)
val is an integer between 25 and 200
returns color to be use to draw saturation lines in saturation canvas
"""
return self.saturationCol[val-25]
def valColor(self, val):
"""TkColorString <- satColor(val)
val is an integer between 25 and 200
returns color to be use to draw value and opacity lines in canvas
"""
h = hex(val)[2:]
if len(h)==1: h = '0'+h
return '#'+h+h+h
def createWidgets(self):
"""create Tkinter widgets: 4 canvas and buttons in 2 frames
"""
# create 4 canvas
self.canvas = {}
self.canvas['Hue'] = Canvas(self, relief=SUNKEN, borderwidth=3,
width="200", height="256")
self.canvas['Hue'].pack(side=TOP)
self.canvas['Sat'] = Canvas(self, relief=SUNKEN, borderwidth=3,
width="200", height="256")
self.canvas['Val'] = Canvas(self, relief=SUNKEN, borderwidth=3,
width="200", height="256")
self.canvas['Opa'] = Canvas(self, relief=SUNKEN, borderwidth=3,
width="200", height="256")
# create frame for min max
self.minTk = StringVar()
self.minTk.set(str(self.min))
self.maxTk = StringVar()
self.maxTk.set(str(self.max))
minmaxFrame = Frame(self)
Label(minmaxFrame, text='Min: ').grid(row=0, column=0, sticky='e')
self.minEntry = Entry(minmaxFrame, textvariable=self.minTk)
self.minEntry.bind('<Return>', self.min_cb)
self.minEntry.grid(row=0, column=1, sticky='w')
Label(minmaxFrame, text='Max: ').grid(row=1, column=0, sticky='e')
self.maxEntry = Entry(minmaxFrame, textvariable=self.maxTk)
self.maxEntry.bind('<Return>', self.max_cb)
self.maxEntry.grid(sticky='w', row=1, column=1 )
minmaxFrame.pack()
self.dissmiss = Button(self, text='Dissmiss', command=self.quit)
self.dissmiss.pack(side=BOTTOM, fill=X)
# create frame for buttons
self.buttonFrame = Frame(self)
# create radio buttons to switch between canvas
self.buttonFrame1 = f = Frame(self.buttonFrame)
self.currentCanvasVar = StringVar()
self.buttonHue = Radiobutton(f, text='Hue', value = 'Hue',
indicatoron = 0, width=15,
variable = self.currentCanvasVar,
command=self.button_cb)
self.buttonHue.grid(column=0, row=0, sticky='w')
self.buttonSat = Radiobutton(f, text='Saturation', value = 'Sat',
indicatoron = 0, width=15,
variable = self.currentCanvasVar,
command=self.button_cb)
self.buttonSat.grid(column=0, row=1, sticky='w')
self.buttonVal = Radiobutton(f, text='Brightness', value = 'Val',
indicatoron = 0, width=15,
variable = self.currentCanvasVar,
command=self.button_cb)
self.buttonVal.grid(column=0, row=2, sticky='w')
self.buttonOpa = Radiobutton(f, text='Opacity', value = 'Opa',
indicatoron = 0, width=15,
variable = self.currentCanvasVar,
command=self.button_cb)
self.buttonOpa.grid(column=0, row=3, sticky='w')
f.pack(side=LEFT)
self.currentCanvas = self.canvas['Hue']
self.currentCanvasVar.set('Hue')
# create radio buttons to switch between canvas
self.buttonFrame2 = f = Frame(self.buttonFrame)
self.reset = Button(f, text='Reset', width=10, command=self.reset_cb)
self.reset.grid(column=0, row=1, sticky='w')
self.read = Button(f, text='Read', width=10, command=self.read_cb)
self.read.grid(column=0, row=2, sticky='w')
self.write = Button(f, text='Write', width=10, command=self.write_cb)
self.write.grid(column=0, row=3, sticky='w')
f.pack(side=LEFT)
self.buttonFrame.pack(side=BOTTOM)
def min_cb(self, event):
min = float(self.minTk.get())
if min < self.max:
self.min = min
self.callCallbacks()
else:
min = self.max-255.0
self.minTk.set(str(min))
self.min = min
def max_cb(self, event):
max = float(self.maxTk.get())
if max > self.min:
self.max = max
self.callCallbacks()
else:
max = self.min+255.0
self.maxTk.set(str(max))
self.max = max
def quit(self):
self.master.destroy()
def reset_cb(self):
var = self.currentCanvasVar.get()
self.clear(var)
if var == 'Hue':
self.rampHue()
self.drawHue()
elif var == 'Sat':
self.constantSaturation(200)
self.drawSaturation()
elif var == 'Val':
self.constantValue(200)
self.drawValue()
elif var == 'Opa':
self.rampOpacity()
self.drawOpacity()
self.mouseUp(None) # to call callbacks
def read_cb(self):
print 'read'
def write_cb(self):
print 'write'
def clear(self, name):
assert name in ['Hue', 'Sat', 'Val', 'Opa' ]
l = self.lines[name]
c = self.canvas[name]
for i in range(256):
c.delete(l[i])
self.lines[name] = []
self.values[name] = []
if self.current==name:
self.currentLines = self.lines[name]
self.currentValues = self.values[name]
def rampHue(self):
ramp = RGBRamp(176)
self.hueFromRGB = map( lambda x, conv=ToHSV: conv(x)[0], ramp )
ramp = (ramp*255).astype('i')
for i in range(176):
r = hex(int(ramp[i][0]))[2:]
if len(r)==1: r='0'+r
g = hex(ramp[i][1])[2:]
if len(g)==1: g='0'+g
b = hex(ramp[i][2])[2:]
if len(b)==1: b='0'+b
self.hueColor.append( '#'+r+g+b)
v = self.values['Hue']
for i in range(256):
v.append(int(i*(175./255.)+25))
def drawHue(self):
l = self.lines['Hue']
c = self.canvas['Hue']
v = self.values['Hue']
for i in range(256):
val = v[i]
col = self.hueColor[val-25]
l.append( c.create_line( 0, i, val, i, fill=col) )
def constantSaturation(self, value):
for i in range(176, -1, -1):
h = hex(int(i*174/255.))[2:]
if len(h)==1: h='0'+h
self.saturationCol.append( '#ff'+h+h )
v = []
for i in range(256):
v.append(value)
self.values['Sat'] = v
if self.current=='Sat':
self.currentValues = v
def drawSaturation(self):
c = self.canvas['Sat']
l = self.lines['Sat']
v = self.values['Sat']
for i in range(256):
val = v[i]
l.append( c.create_line( 0, i, val, i, fill='red') )
if self.current=='Sat':
self.currentLines = l
def constantValue(self, value):
v = []
for i in range(256):
v.append(value)
self.values['Val'] = v
if self.current=='Val':
self.currentValues = v
def drawValue(self):
c = self.canvas['Val']
l = self.lines['Val']
v = self.values['Val']
for i in range(256):
l.append( c.create_line( 0, i, v[i], i, fill='white') )
if self.current=='Val':
self.currentLines = l
def rampOpacity(self):
v = []
for i in range(256):
v.append(int(i*(175./255.)+25))
self.values['Opa'] = v
if self.current=='Opa':
self.currentValues = v
def drawOpacity(self):
c = self.canvas['Opa']
l = self.lines['Opa']
v = self.values['Opa']
for i in range(256):
val = v[i]
col = self.valColor(val-25)
l.append( c.create_line( 0, i, val, i, fill=col) )
if self.current=='Opa':
self.currentLines = l
def addCallback(self, function):
assert callable(function)
self.callbacks.append( function )
def buildRamp(self):
h = map( lambda x, table=self.hueFromRGB: table[x-25],
self.values['Hue'] )
h = Numeric.array(h)
#h = (Numeric.array(self.values['Hue'])-25)/175.0
s = (Numeric.array(self.values['Sat'])-25)/175.0
v = (Numeric.array(self.values['Val'])-25)/175.0
a = (Numeric.array(self.values['Opa'])-25)/175.0
self.hsva = map( None, h,s,v,a )
self.rgbMap = map( ToRGB, self.hsva)
def callCallbacks(self):
for f in self.callbacks:
f( self.rgbMap, self.min, self.max )
def mouseUp(self, event):
self.buildRamp()
self.callCallbacks()
def mouseDown(self, event):
# canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object
x = min(199, event.x)
y = min(255, event.y)
x = max(25, x)
y = max(0, y)
c = self.currentCanvas
self.starty = y
line = self.currentLines[y]
col = self.getColor(x)
newline = c.create_line( 0, y, x, y, fill=col)
self.currentLines[y] = newline
self.currentValues[y] = x
c.delete(line)
self.startx = x
def mouseMotion(self, event):
# canvas x and y take the screen coords from the event and translate
# them into the coordinate system of the canvas object
# x,y are float
#x = self.canvasHue.canvasx(event.x)
#y = self.canvasHue.canvasy(event.y)
# event.x, event.y are same as x,y but int
x = min(199, event.x)
y = min(255, event.y)
x = max(25, x)
y = max(0, y)
c = self.currentCanvas
if self.starty == y:
line = self.currentLines[y]
col = self.getColor(x)
newline = c.create_line( 0, y, x, y, fill=col)
self.currentLines[y] = newline
c.delete(line)
self.currentValues[y] = x
else: # we need to interpolate for all y's between self.starty and y
dx = x-self.startx
dy = y-self.starty
rat = float(dx)/float(dy)
if y > self.starty:
for yl in range(self.starty, y):
ddx = int(rat*(yl-self.starty)) + self.startx
line = self.currentLines[yl]
col = self.getColor(ddx)
newline = c.create_line( 0,yl, ddx,yl,fill=col)
self.currentLines[yl] = newline
c.delete(line)
self.currentValues[yl] = ddx
else:
for yl in range(self.starty, y, -1):
ddx = int(rat*(yl-self.starty)) + self.startx
line = self.currentLines[yl]
col = self.getColor(ddx)
newline = c.create_line( 0,yl, ddx,yl,fill=col)
self.currentLines[yl] = newline
c.delete(line)
self.currentValues[yl] = ddx
self.starty = y
self.startx = x
# this flushes the output, making sure that
# the rectangle makes it to the screen
# before the next event is handled
self.update_idletasks()
def __init__(self, master=None, min=0.0, max=255.0):
if master == None:
master = Toplevel()
Frame.__init__(self, master)
Pack.config(self)
self.min=min
self.max=max
self.getColorFunc = { 'Hue':self.hueColor,
'Sat':self.satColor,
'Val':self.valColor,
'Opa':self.valColor
}
self.values = { 'Hue': [],
'Sat': [],
'Val': [],
'Opa': []
}
self.lines = { 'Hue':[], 'Sat':[], 'Val':[], 'Opa':[] }
self.current = 'Hue'
self.currentLines = None
self.currentValues = None
self.hueColor = []
self.saturationCol = []
self.callbacks = []
self.hueFromRGB = []
self.createWidgets()
self.rampHue()
self.drawHue()
self.constantSaturation(200)
self.drawSaturation()
self.constantValue(200)
self.drawValue()
self.rampOpacity()
self.drawOpacity()
# just so we have the corresponfing RGBramp
self.buildRamp()
self.getColor = self.getColorFunc['Hue']
self.currentLines = self.lines['Hue']
self.currentValues = self.values['Hue']
Widget.bind(self.canvas['Hue'], "<ButtonPress-1>", self.mouseDown)
Widget.bind(self.canvas['Hue'], "<Button1-Motion>", self.mouseMotion)
Widget.bind(self.canvas['Hue'], "<ButtonRelease-1>", self.mouseUp)
Widget.bind(self.canvas['Sat'], "<ButtonPress-1>", self.mouseDown)
Widget.bind(self.canvas['Sat'], "<Button1-Motion>", self.mouseMotion)
Widget.bind(self.canvas['Sat'], "<ButtonRelease-1>", self.mouseUp)
Widget.bind(self.canvas['Val'], "<ButtonPress-1>", self.mouseDown)
Widget.bind(self.canvas['Val'], "<Button1-Motion>", self.mouseMotion)
Widget.bind(self.canvas['Val'], "<ButtonRelease-1>", self.mouseUp)
Widget.bind(self.canvas['Opa'], "<ButtonPress-1>", self.mouseDown)
Widget.bind(self.canvas['Opa'], "<Button1-Motion>", self.mouseMotion)
Widget.bind(self.canvas['Opa'], "<ButtonRelease-1>", self.mouseUp)
if __name__ == '__main__':
import pdb
test = ColorMapGUI()
def cb(ramp, min, max):
print len(ramp), min, max
test.addCallback(cb)
#test.mainloop()
```
#### File: MGLToolsPckgs/Pmv/computeIsovalue.py
```python
from geomutils.surface import findComponents, meshVolume, triangleArea
try:
from UTpackages.UTisocontour import isocontour
except:
pass
try:
from UTpackages.UTblur import blur
except:
pass
try:
from mslib import MSMS
except:
pass
try:
from QSlimLib import qslimlib
except:
pass
from math import fabs
from MolKit.molecule import Atom
import numpy.oldnumeric as Numeric
from math import sqrt
def computeIsovalue(nodes, blobbyness, densityList=3.0, gridResolution=0.5, criteria="Volume", radiiSet="united", msmsProbeRadius=1.4, computeWeightOption=0, resolutionLevel=None, gridDims=None, padding=0.0):
"""This function is based on shapefit/surfdock.py blurSurface() by <NAME>.
INPUT:
nodes
blobbyness: blobbyness
densityList: A list of vertex densities (or just a single density value) for blur surfaces
e.g. [1.0, 2.0, 3.0] or 1.0 or [1.0]
gridResolution: Resolution of grid used for blurring
0.5 gives surface vertex density > 5 dots/Angstrom^2
0.25 gives surface vertex density > 20 dots/Angstrom^2
0.2 gives surface vertex density > 40 dots/Angstrom^2
radiiSet: Radii set for computing both MSMS and blur surfaces
msmsProbeRadius: Probe radius for computing MSMS
resolutionLevel: Level of surface resolution
= None: using the given blobbyness value
= 1 or 'very low' blobbyness = -0.1
= 2 or 'low' blobbyness = -0.3
= 3 or 'medium' blobbyness = -0.5
= 4 or 'high' blobbyness = -0.9
= 5 or 'very high' blobbyness = -3.0
padding : size of the padding around the molecule
"""
# 0. Initialization
blurSurfList = []
isoGridResolution = 0.5 # grid resolution for finding isovalue
isoDensity = 5.0 # density of blur surface vertices for finding isovalue
msmsDensity = 20.0 # density of MSMS surface vertices for compute MSMS volume
#msmsFilePrefix=molName # prefix of MSMS surface filenames
# ... 1.1. Blur
print "... 1.1. Blur ......"
atoms = nodes.findType(Atom)
coords = atoms.coords
radii = atoms.radius
arrayf, origin, stepsize = blurCoordsRadii(coords, radii, blobbyness,
isoGridResolution, gridDims, padding)
data = isocontour.newDatasetRegFloat3D(arrayf, origin, stepsize)
print "##### data : ", type(data), "#######"
# ... 1.2. Compute area and volume of MSMS surface at msmsDensity
print "... 1.2. Compute MSMS volume ......"
msmsVolume = computeMSMSvolume(coords, radii, msmsProbeRadius, msmsDensity)
#msmsArea, msmsVolume = computeMSMSAreaVolumeViaCommand(molFile, radiiSet, msmsProbeRadius, dens=msmsDensity, outFilePrefix=msmsFilePrefix)
#os.system( "rm -rf %s.vert %s.face %s.xyzr" % ( msmsFilePrefix, msmsFilePrefix, msmsFilePrefix ) ) # remove MSMS surface files
# ... 1.3. Find isovalue based on either MSMS area or volume at blur isoDensity
print "... 1.3. Find isovalue ......"
res = findIsoValueMol(radii, coords, blobbyness, data, isoDensity, msmsVolume, "Volume")
target, targetValue, value, isovalue, v1, t1, n1 = res
#isocontour.clearDataset(data) # free memory of data
isocontour.delDatasetReg(data)
if isovalue == 0.0: # isovalue can not be found
print "blurSurface(): isovalue can not be found"
return None
return isovalue
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5,
weights=None, dims=None, padding = 0.0):
"""blur a set of coordinates with radii
"""
# Setup grid
resX = resY = resZ = res
if not dims:
minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding)
Xdim = int(round( (maxb[0] - minb[0])/resX + 1))
Ydim = int(round( (maxb[1] - minb[1])/resY + 1))
Zdim = int(round( (maxb[2] - minb[2])/resZ + 1))
else:
Xdim, Ydim, Zdim = dims
print "Xdim = %d, Ydim =%d, Zdim = %d"%(Xdim, Ydim, Zdim)
# Generate blur map
volarr, origin, span = blur.generateBlurmap(
coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding)
# Take data from blur map
volarr.shape = [Zdim, Ydim, Xdim]
volarr = Numeric.transpose(volarr).astype('f')
origin = Numeric.array(origin).astype('f')
stepsize = Numeric.array(span).astype('f')
arrayf = Numeric.reshape( Numeric.transpose(volarr),
(1, 1)+tuple(volarr.shape) )
# Return data
return arrayf, origin, stepsize
def computeMSMSvolume(atmCoords, atmRadii, pRadius, dens ):
srf = MSMS(coords=atmCoords, radii=atmRadii)
srf.compute(probe_radius=pRadius, density=dens)
vf, vi, f = srf.getTriangles()
vertices=vf[:,:3]
normals=vf[:,3:6]
triangles=f[:,:3]
return meshVolume(vertices, normals, triangles)
def meshArea(verts, tri):
"""Compute the surface area of a surface as the sum of the area of its
triangles. The surface is specified by vertices, indices of triangular faces
"""
areaSum = 0.0
for t in tri:
s1 = verts[t[0]]
s2 = verts[t[1]]
s3 = verts[t[2]]
area = triangleArea(s1,s2,s3)
areaSum += area
return areaSum
def normalCorrection(norms, faces):
"""Replace any normal, which is equal to zero, with the average
of its triangle neighbors' non-zero normals (triangle neighbors, as
the edge partners, can be derived from the faces)
"""
# Convert one-based faces temporarily to zero-based
newFaces = []
if faces[0][0] == 1:
for v1, v2, v3 in faces: # vertex indices v1, v2, v3
newFaces.append( ( v1-1, v2-1, v3-1 ) )
else:
newFaces = faces
# Build a neighborhood dictionary for easy neighbor search
neighborDict = {}
for v1, v2, v3 in newFaces: # vertex indices v1, v2, v3
# v1
if v1 not in neighborDict:
neighborDict[v1] = []
if v2 not in neighborDict[v1]:
neighborDict[v1].append(v2)
if v3 not in neighborDict[v1]:
neighborDict[v1].append(v3)
# v2
if v2 not in neighborDict:
neighborDict[v2] = []
if v3 not in neighborDict[v2]:
neighborDict[v2].append(v3)
if v1 not in neighborDict[v2]:
neighborDict[v2].append(v1)
# v3
if v3 not in neighborDict:
neighborDict[v3] = []
if v1 not in neighborDict[v3]:
neighborDict[v3].append(v1)
if v2 not in neighborDict[v3]:
neighborDict[v3].append(v2)
# Find any zero-value normal and replace it
newNorms = []
for i, eachnorm in enumerate(norms):
# non-zero normal
if not ( eachnorm[0]==0.0 and eachnorm[1]==0.0 and eachnorm[2]==0.0 ):
newNorms.append( [ eachnorm[0], eachnorm[1], eachnorm[2] ] )
continue
# zero normal
print "normalCorrection(): zero normal at vertex %d", i
neighbors = neighborDict[i]
neighborNorms = [0.0, 0.0, 0.0]
Nneighbors = 0
for eachneighbor in neighbors: # sum up non-zero neighbors
eachneighborNorm = norms[eachneighbor]
if eachneighborNorm[0]==0.0 and eachneighborNorm[1]==0.0 and eachneighborNorm[2]==0.0:
continue # skip zero-normal neighbor
Nneighbors += 1
neighborNorms[0] += eachneighborNorm[0]
neighborNorms[1] += eachneighborNorm[1]
neighborNorms[2] += eachneighborNorm[2]
if Nneighbors == 0: # non-zero neighbors can not be found
print "Can not find non-zero neighbor normals for normal %d " % i
newNorms.append(neighborNorms)
continue
neighborNorms[0] /= Nneighbors # average
neighborNorms[1] /= Nneighbors
neighborNorms[2] /= Nneighbors
newNorms.append(neighborNorms)
# Return
return newNorms
def findIsoValueMol(radii, coords, blobbyness, data, isoDensity, targetValue, target):
"""Find the best isocontour value (isovalue) for a molecule
at one specific blobbyness by reproducing the targetValue
for a target (area or volume)
INPUT:
mol: molecule recognizable by MolKit
blobbyness: blobbyness
data: blurred data
isoDensity: density of surface vertices for finding isovalue only
targetValue: value of the target, to be reproduced
target: Area or Volume
OUTPUT:
target: (as input)
targetValue: (as input)
value: reproduced value of target
isovalue: the best isocontour value
v1d: vertices of generated blur surface
t1d: faces of generated blur surface
n1d: normals of the vertices
"""
# Initialization
isovalue = 1.0 # guess starting value
mini = 0.
maxi = 99.
cutoff = targetValue*0.01 # 99% reproduction of targetValue
accuracy = 0.0001 # accuracy of isovalue
stepsize = 0.5 # step size of increase/decrease of isovalue
value_adjust = 1.0 # adjustment of value
value = 0.0
# Optimize isovalue
while True:
print "------- isovalue = %f -------" % isovalue
# 1. Isocontour
print "... ... 1. Isocontour ......"
v1, t1, n1 = computeIsocontour(isovalue, data)
if len(v1)==0 or len(t1)==0:
value = 0.0
maxi = isovalue
isovalue = maxi - (maxi-mini)*stepsize
print "***** isocontoured surface has no vertices *****", len(v1), ", ", len(t1)
continue
# 2. Remove small components (before decimate)
print "... ... 2. Remove small components ......"
v1, t1, n1 = findComponents(v1, t1, n1, 1)
# 3. Decimate
print "... ... 3. Decimate ......"
v1d, t1d, n1d = decimate(v1, t1, n1, isoDensity)
if len(v1d)==0 or len(t1d)==0:
value = 0.0
maxi = isovalue
isovalue = maxi - (maxi-mini)*stepsize
continue
#################### Analytical normals for decimated vertices #####################
normals = computeBlurCurvature(radii, coords, blobbyness, v1d) # Analytical Blur curvatures
n1d = normals.tolist()
####################################################################################
# 4. Compute value
print "... ... 4. Compute value ......"
if target == "Area":
value = meshArea(v1d, t1d)
else:
n1d = normalCorrection(n1d, t1d) # replace zero normals
print "calling meshVolume after normalCorrection"
value = meshVolume(v1d, n1d, t1d)
# 5. Adjust value
print "... ... 5. Adjust value ......"
value *= value_adjust
# TEST
print "target=%6s, targetValue=%10.3f, value=%10.3f, isovalue=%7.3f, maxi=%7.3f, mini=%7.3f"%(
target, targetValue, value, isovalue, maxi, mini)
# 6. Evaluate isocontour value
print "... ... 6. Evaluate isovalue ......"
if fabs(value - targetValue) < cutoff: # Satisfy condition!
print "Found: target=%6s, targetValue=%10.3f, value=%10.3f, isovalue=%7.3f, maxi=%7.3f, mini=%7.3f"%(
target, targetValue, value, isovalue, maxi, mini)
break
if maxi-mini < accuracy: # can not find good isovalue
print "Not found: target=%6s, targetValue=%10.3f, value=%10.3f, isovalue=%7.3f, maxi=%7.3f, mini=%7.3f"%(
target, targetValue, value, isovalue, maxi, mini)
return target, targetValue, value, 0.0, v1, t1, n1
if value > targetValue: # value too big, increase isovalue
mini = isovalue
isovalue = mini + (maxi-mini)*stepsize
else: # value too small, decrease isovalue
maxi = isovalue
isovalue = maxi - (maxi-mini)*stepsize
# Return
return target, targetValue, value, isovalue, v1, t1, n1
def computeIsocontour(isovalue, data):
isoc = isocontour.getContour3d(data, 0, 0, isovalue,
isocontour.NO_COLOR_VARIABLE)
if isoc.nvert==0 or isoc.ntri==0:
return [], [], []
vert = Numeric.zeros((isoc.nvert,3)).astype('f')
norm = Numeric.zeros((isoc.nvert,3)).astype('f')
col = Numeric.zeros((isoc.nvert)).astype('f')
tri = Numeric.zeros((isoc.ntri,3)).astype('i')
isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)
if len(vert) == 0 or len(tri) == 0:
return [], [], []
return vert, tri, norm
def decimate(vert, tri, normals, density=1.0):
# decimate a mesh to vertex density close to 1.0
if len(vert)==0 or len(tri)==0:
return [], [], []
#print "before decimate: ", len(vert), " vertices, ", len(tri), " faces"
model = qslimlib.QSlimModel(vert, tri, bindtoface=False,
colors=None, norms=normals)
nverts = model.get_vert_count()
nfaces = model.get_face_count()
# allocate array to read decimated surface back
newverts = Numeric.zeros((nverts, 3)).astype('f')
newfaces = Numeric.zeros((nfaces, 3)).astype('i')
newnorms = Numeric.zeros((nverts, 3)).astype('f')
# print len(vert), area, len(tri), int(len(tri)*len(vert)/area)
area = meshArea(vert, tri)
tface = int(min(len(tri), int(len(tri)*area/len(vert)))*density)
model.slim_to_target(tface)
numFaces = model.num_valid_faces()
# print 'decimated to %d triangles from (%d)'%(numFaces, len(tri))
model.outmodel(newverts, newfaces, outnorms=newnorms)
numVertices = max(newfaces.ravel())+1
# build lookup table of vertices used in faces
d = {}
for t in newfaces[:numFaces]:
d[t[0]] = 1
d[t[1]] = 1
d[t[2]] = 1
vl = {}
decimVerts = Numeric.zeros((numVertices, 3)).astype('f')
decimFaces = Numeric.zeros((numFaces, 3)).astype('i')
decimNormals = Numeric.zeros((numVertices, 3)).astype('f')
nvert = 0
nvert = 0
for j, t in enumerate(newfaces[:numFaces]):
for i in (0,1,2):
n = t[i]
if not vl.has_key(n):
vl[n] = nvert
decimVerts[nvert] = newverts[n,:]
decimNormals[nvert] = newnorms[n,:]
nvert += 1
decimFaces[j] = (vl[t[0]], vl[t[1]], vl[t[2]])
## vertices=newverts[:numVertices]
## for t in newfaces[:numFaces]:
## for i in (0,1,2):
## if not vl.has_key(t[i]):
## vl[t[i]] = nvert
## decimVerts.append(vertices[t[i]])
## nvert += 1
## decimFaces.append( (vl[t[0]], vl[t[1]], vl[t[2]] ) )
#print 'density after decimation', len(decimVerts)/meshArea(decimVerts, decimFaces)
## norms1 = glTriangleNormals( decimVerts, decimFaces, 'PER_VERTEX')
#print "after decimate: ", nvert, " vertices, ", numFaces, " faces"
return decimVerts[:nvert], decimFaces, decimNormals[:nvert]
def computeBlurCurvature(radii, coords, blobbiness, points):
# Compute Blur curvatures analytically by UTmolderivatives (since Novemeber 2005)
from UTpackages.UTmolderivatives import molderivatives
import numpy.oldnumeric as Numeric
# Read input
npoints = len(points)
numberOfGaussians = len(coords)
gaussianCenters = Numeric.zeros((numberOfGaussians,4)).astype('d')
for i in range(numberOfGaussians):
gaussianCenters[i,0:3] = coords[i]
gaussianCenters[i,3] = radii[i]
numberOfGridDivisions = 10 # as in Readme.htm of UTmolderivatives
maxFunctionError = 0.001 # as in Readme.htm of UTmolderivatives
# Compute HandK, normals, k1Vector, k2Vector
HandK, normals, k1Vector, k2Vector = molderivatives.getGaussianCurvature(gaussianCenters,
numberOfGridDivisions, maxFunctionError,
blobbiness, points)
k1Vector = Numeric.reshape(k1Vector, (npoints, 3))
k2Vector = Numeric.reshape(k2Vector, (npoints, 3))
HandK = Numeric.reshape(HandK, (npoints, 2))
normals = Numeric.reshape(normals, (npoints, 3)) * (-1) # change normal directions to outwards
return normals
```
#### File: MGLToolsPckgs/Pmv/crystalCommands.py
```python
from symserv.spaceGroups import spaceGroups
import numpy
from mglutil.math.crystal import Crystal
from Pmv.mvCommand import MVCommand
from ViewerFramework.VFCommand import CommandGUI
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
import Pmw, Tkinter
import tkMessageBox
from DejaVu.Box import Box
from mglutil.util.callback import CallBackFunction
def instanceMatricesFromGroup(molecule):
returnMatrices = [numpy.eye(4,4)]
crystal = Crystal(molecule.cellLength, molecule.cellAngles)
matrices = spaceGroups[molecule.spaceGroup]
for matrix in matrices:
tmpMatix = numpy.eye(4,4)
tmpMatix[:3, :3] = matrix[0]
tmpMatix[:3, 3] = crystal.toCartesian(matrix[1])
returnMatrices.append(tmpMatix)
molecule.crystal = crystal
return returnMatrices
class CrystalCommand(MVCommand):
def guiCallback(self):
molNames = []
for mol in self.vf.Mols:
if hasattr(mol, 'spaceGroup'):
molNames.append(mol.name)
if not molNames:
tkMessageBox.showinfo("Crystal Info is Needed", "No Molecule in the Viewer has Crystal Info.")
return
ifd = InputFormDescr(title='Crystal Info')
ifd.append({'name':'moleculeList',
'widgetType':Pmw.ScrolledListBox,
'tooltip':'Select a molecule with Crystal Info.',
'wcfg':{'label_text':'Select Molecule: ',
'labelpos':'nw',
'items':molNames,
'listbox_selectmode':'single',
'listbox_exportselection':0,
'usehullsize': 1,
'hull_width':100,'hull_height':150,
'listbox_height':5},
'gridcfg':{'sticky':'nsew', 'row':1, 'column':0}})
val = self.vf.getUserInput(ifd, modal=1, blocking=1)
if val:
molecule = self.vf.getMolFromName(val['moleculeList'][0])
matrices = instanceMatricesFromGroup(molecule)
geom = molecule.geomContainer.geoms['master']
geom.Set(instanceMatrices=matrices)
if not molecule.geomContainer.geoms.has_key('Unit Cell'):
fractCoords=((1,1,0),(0,1,0),(0,0,0),(1,0,0),(1,1,1),(0,1,1),
(0,0,1),(1,0,1))
coords = []
coords = molecule.crystal.toCartesian(fractCoords)
box=Box('Unit Cell', vertices=coords)
self.vf.GUI.VIEWER.AddObject(box, parent=geom)
molecule.geomContainer.geoms['Unit Cell'] = box
ifd = InputFormDescr(title='Crystal Options')
visible = molecule.geomContainer.geoms['Unit Cell'].visible
if visible:
showState = 'active'
else:
showState = 'normal'
ifd.append({'name': 'Show Cell',
'widgetType':Tkinter.Checkbutton,
'text': 'Hide Unit Cell',
'state':showState,
'gridcfg':{'sticky':Tkinter.W},
'command': CallBackFunction(self.showUnitCell, molecule)})
ifd.append({'name': 'Show Packing',
'widgetType':Tkinter.Checkbutton,
'text': 'Hide Packing',
'state':'active',
'gridcfg':{'sticky':Tkinter.W},
'command': CallBackFunction(self.showPacking, molecule)})
val = self.vf.getUserInput(ifd, modal=0, blocking=1)
if not val:
geom.Set(instanceMatrices=[numpy.eye(4,4)])
molecule.geomContainer.geoms['Unit Cell'].Set(visible=False)
def showUnitCell(self, molecule):
visible = not molecule.geomContainer.geoms['Unit Cell'].visible
molecule.geomContainer.geoms['Unit Cell'].Set(visible=visible)
def showPacking(self, molecule):
geom = molecule.geomContainer.geoms['master']
if len(geom.instanceMatricesFortran) >= 2:
geom.Set(instanceMatrices=[numpy.eye(4,4)])
else:
matrices = instanceMatricesFromGroup(molecule)
geom.Set(instanceMatrices=matrices)
CrystalCommandGUI = CommandGUI()
CrystalCommandGUI.addMenuCommand('menuRoot', 'Display', 'Crystal')
commandList = [{'name':'crystalCommand','cmd':CrystalCommand(),'gui':CrystalCommandGUI}]
def initModule(viewer):
for _dict in commandList:
viewer.addCommand(_dict['cmd'],_dict['name'],_dict['gui'])
```
#### File: MGLToolsPckgs/Pmv/editCommands.py
```python
from PyBabel.addh import AddHydrogens
from PyBabel.aromatic import Aromatic
from PyBabel.atomTypes import AtomHybridization
from PyBabel.cycle import RingFinder
from PyBabel.bo import BondOrder
from PyBabel.gasteiger import Gasteiger
from ViewerFramework.VFCommand import CommandGUI
from Pmv.moleculeViewer import DeleteAtomsEvent, AddAtomsEvent
## from ViewerFramework.gui import InputFormDescr
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.util.callback import CallBackFunction
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
from tkMessageBox import *
from SimpleDialog import SimpleDialog
from Pmv.mvCommand import MVCommand, MVAtomICOM, MVBondICOM
from Pmv.measureCommands import MeasureAtomCommand
from MolKit.tree import TreeNode, TreeNodeSet
from MolKit.molecule import Atom, AtomSet, Bond, Molecule, MoleculeSet
from MolKit.molecule import BondSet
from MolKit.protein import Protein, ProteinSet, Chain, Residue, ResidueSet
from MolKit.pdbParser import PdbParser, PdbqParser, PdbqsParser
from DejaVu.Geom import Geom
from DejaVu.Spheres import Spheres
from DejaVu.Points import CrossSet
from Pmv.stringSelectorGUI import StringSelectorGUI
import types, Tkinter, Pmw, math, os
import numpy.oldnumeric as Numeric
from string import letters, strip, find
def check_edit_geoms(VFGUI):
edit_geoms_list = VFGUI.VIEWER.findGeomsByName('edit_geoms')
if edit_geoms_list==[]:
edit_geoms = Geom("edit_geoms", shape=(0,0), protected=True)
VFGUI.VIEWER.AddObject(edit_geoms, parent=VFGUI.miscGeom)
edit_geoms_list = [edit_geoms]
return edit_geoms_list[0]
from MolKit.protein import Residue, ResidueSet
from MolKit.molecule import Atom, AtomSet
class DeleteWaterCommand(MVCommand):
"""This class provides a command to remove water molecules.
It will delete all atoms belonging to resides with names 'HOH' or 'WAT'
\nPackage:Pmv
\nModule :editCommands
\nClass:DeleteWaterCommand
\nCommand:deleteWater
\nSynopsis:\n
None <--- removeWater(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet for which to remove waters
\nexample:\n
>>> RemoveWaterCommand()\n
>>> RemoveWaterCommand(molecule)\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
self.vf._deletedLevels = []
#if self.vf.hasGui and not self.vf.commands.has_key('deleteMol'):
if not self.vf.commands.has_key('deleteAtomSet'):
self.vf.loadCommand("deleteCommands", "deleteAtomSet", "Pmv",
topCommand=0)
def doit(self, nodes):
nodes = self.vf.expandNodes(nodes)
nodes = nodes.findType( Residue ).uniq()
nodes = ResidueSet([r for r in nodes if r.type=='WAT' or r.type=='HOH'])
atoms = nodes.findType( Atom )
self.vf.deleteAtomSet( atoms )
def __call__(self, nodes, **kw):
"""None<---deleteWater(nodes, **kw)
\nnodes --- TreeNodeSet from which to delete waters"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
try:
nodes = self.vf.expandNodes(nodes)
except:
raise IOError
apply ( self.doitWrapper, (nodes,), kw )
def guiCallback(self):
sel = self.vf.getSelection()
if len(sel):
self.doitWrapper(sel, log=1, redraw=0)
deleteWaterCommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuEntryLabel':'delete water'
}
DeleteWaterCommandGUI = CommandGUI()
DeleteWaterCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Delete Water')
class TypeAtomsCommand(MVCommand):
"""This class uses the AtomHybridization class to assign atom types.
\nPackage:Pmv
\nModule :editCommands
\nClass:TypeAtomsCommand
\nCommand:typeAtoms
\nSynopsis:\n
None <--- typeAtoms(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\nexample:\n
>>> atype = AtomHybridization()\n
>>> atype.assignHybridization(atoms)\n
atoms has to be a list of atom objects\n
Atom:\n
a .element : atom's chemical element symbol (string)\n
a .coords : 3-sequence of floats\n
a .bonds : list of Bond objects\n
Bond:\n
b .atom1 : instance of Atom\n
b .atom2 : instance of Atom\n
After completion each atom has the following additional members:\n
babel_type: string\n
babel_atomic_number: int\n
babel_organic\n
reimplementation of Babel1.6 in Python by <NAME> April 2000
Original code by <NAME> and <NAME>\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def doit(self, nodes):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0:
return 'ERROR'
mols = nodes.top.uniq()
for mol in mols:
#if hasattr(mol.allAtoms[0], 'babel_type'):
#continue
# try:
# mol.allAtoms.babel_type
# except:
babel = AtomHybridization()
babel.assignHybridization(mol.allAtoms)
def __call__(self, nodes, **kw):
"""None<---typeAtoms(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
try:
nodes = self.vf.expandNodes(nodes)
except:
raise IOError
apply ( self.doitWrapper, (nodes,), kw )
def guiCallback(self):
sel = self.vf.getSelection()
if len(sel):
self.doitWrapper(sel, log=1, redraw=0)
typeAtomsCommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuEntryLabel':'Type',
'menuCascadeName': 'Atoms'}
TypeAtomsCommandGUI = CommandGUI()
TypeAtomsCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Type',
cascadeName='Atoms')#, index=1)
class EditAtomTypeGUICommand(MVCommand, MVAtomICOM):
"""This class provides the GUI to EditAtom Type which allows the user
to change assigned atom types.
\nPackage:Pmv
\nModule :editCommands
\nClass:EditAtomTypeGUICommand
\nCommand:editAtomTypeGC
\nSynopsis:\n
None<---editAtomTypeGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
MVAtomICOM.__init__(self)
self.atmTypeDict={}
self.atmTypeDict['B']=['B', 'Bac', 'Box']
self.atmTypeDict['C']=['C', 'C1','C2','C3','Cac', 'Cbl', 'Car', 'C-',\
'C+', 'Cx', 'Cany']
self.atmTypeDict['H']=['H', 'HC', 'H-','HO','H+', 'HN']
self.atmTypeDict['N']=['Ng+', 'Npl','Nam', 'N1','N2','N3', 'N4',\
'Naz', 'Nox', 'Ntr', 'NC', 'N2+', 'Nar', 'Nany', 'N3+']
self.atmTypeDict['O']=['O', 'O-','O2','O3','Oes', 'OCO2', \
'Oco2', 'Oany']
self.atmTypeDict['P']=['P', 'P3', 'P3+', 'Pac', 'Pox']
self.atmTypeDict['S']=['S', 'S2', 'S3', 'S3+', 'Sac', 'So',\
'So2', 'Sox', 'Sany']
def onAddCmdToViewer(self):
self.spheres = Spheres(name='editAtomTypeSphere', shape=(0,3),
radii=0.2, #inheritMaterial=0,
pickable=0, quality=15,
materials=((1.,1.,0.),), protected=True)
if self.vf.hasGui:
edit_geoms = check_edit_geoms(self.vf.GUI)
self.vf.GUI.VIEWER.AddObject(self.spheres, parent=edit_geoms)
if not hasattr(self.vf, 'editAtomType'):
self.vf.loadCommand('editCommands', 'editAtomType','Pmv',
topCommand=0)
def __call__(self, nodes, **kw):
"""None<---editAtomTypeGC(nodes, **kw)
\nnodes --- TreeNodeSet """
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
ats = self.vf.expandNodes(nodes)
if not len(ats): return 'ERROR'
ats = ats.findType(Atom)
apply ( self.doitWrapper, (ats,), kw )
def doit(self, ats):
for atom in ats:
self.spheres.Set(vertices=(atom.coords,))
self.vf.GUI.VIEWER.Redraw()
if not hasattr(atom,'babel_type'):
#msg = 'atom has no babel_type: calling typeAtoms'
#self.warningMsg(msg)
#typeAtoms does whole molecule
self.vf.typeAtoms(atom, topCommand=0)
if atom.element not in self.atmTypeDict.keys():
msg = 'No alternative atom types available for this element'
self.warningMsg(msg)
continue
else:
bVals = self.atmTypeDict[atom.element]
initialValue = (atom.babel_type,None)
entries = []
for item in bVals:
entries.append((item, None))
ifd = self.ifd = InputFormDescr(title='Select New AtomType')
ifd.append({'name': 'typesList',
'title':'Choose New Type',
'widgetType':'ListChooser',
'entries': entries,
'defaultValue':initialValue,
'mode': 'single',
'gridcfg':{'row':0,'column':0},
'lbwcfg':{'height':5}})
vals = self.vf.getUserInput(ifd)
if vals is not None and len(vals)>0 and len(vals['typesList'])>0:
self.vf.editAtomType(atom, vals['typesList'][0],topCommand=0)
else:
return 'ERROR'
self.spheres.Set(vertices=[])
self.vf.GUI.VIEWER.Redraw()
def startICOM(self):
self.vf.setIcomLevel(Atom)
def stopICOM(self):
self.spheres.Set(vertices=[])
self.vf.GUI.VIEWER.Redraw()
self.vf.ICmdCaller.commands.value["Shift_L"] = self.save
self.save = None
#def setupUndoBefore(self, ats, btype=None):
#ustr = ''
#for at in ats:
##typeAtoms types everything so can't undo it
#if hasattr(at, 'babel_type'):
#ustr=ustr + '"at=self.expandNodes('+'\''+at.full_name()+'\''+')[0];at.babel_type=\''+ at.babel_type+'\';"'
#self.undoCmds = "exec("+ustr+")"
def guiCallback(self):
showinfo("Picking level is set to editAtomType",
"Please pick on atom to change the type.")
self.save = self.vf.ICmdCaller.commands.value["Shift_L"]
self.vf.setICOM(self, modifier="Shift_L", topCommand=0)
editAtomTypeGUICommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Atoms',
'menuEntryLabel':'Edit Type'}
EditAtomTypeGUICommandGUI = CommandGUI()
EditAtomTypeGUICommandGUI.addMenuCommand('menuRoot', 'Edit', 'Edit Type',
cascadeName='Atoms')#, index=1)
class EditAtomTypeCommand(MVCommand):
"""This class allows the user to change assigned atom types.
\nPackage:Pmv
\nModule :editCommands
\nClass:EditAtomTypeCommand
\nCommand:editAtomType
\nSynopsis:\n
None <- editAtomType(ats, btype, **kw)\n
\nRequired Arguments:\n
at --- atom\n
btype --- babel_type\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
def __call__(self, ats, btype, **kw):
"""None <- editAtomType(ats, btype, **kw)
\nat --- atom
\nbtype --- babel_type"""
if type(ats) is types.StringType:
self.nodeLogString = "'"+ats+"'"
ats = self.vf.expandNodes(ats)
if not len(ats): return 'ERROR'
at = ats.findType(Atom)[0]
apply ( self.doitWrapper, (at, btype,), kw )
def doit(self, at, btype):
at.babel_type = btype
def setupUndoBefore(self, at, btype):
ustr = ''
#typeAtoms types everything so can't undo it
if hasattr(at, 'babel_type'):
ustr = ustr + '"at=self.expandNodes('+'\''+at.full_name()+'\''+')[0];at.babel_type=\''+ at.babel_type+'\';"'
self.undoCmds = "exec("+ustr+")"
class EditAtomChargeGUICommand(MVCommand, MVAtomICOM):
"""This class provides the GUI to EditAtomCharge which allows the user
to change atom charge.
\nPackage:Pmv
\nModule :editCommands
\nClass:EditAtomTypeGUICommand
\nCommand:editAtomTypeGC
\nSynopsis:\n
None<---editAtomChargeGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
MVAtomICOM.__init__(self)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
self.spheres = Spheres(name='editAtomChargeSphere', shape=(0,3),
radii=0.2, #inheritMaterial=0,
pickable=0, quality=15,
materials=((1.,1.,0.),), protected=True)
if self.vf.hasGui:
edit_geoms = check_edit_geoms(self.vf.GUI)
self.vf.GUI.VIEWER.AddObject(self.spheres, parent=edit_geoms)
self.oldCharge = Tkinter.StringVar()
def __call__(self, nodes, **kw):
"""None<---editAtomChargeGC(nodes, **kw)
\nnodes --- TreeNodeSet """
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
apply ( self.doitWrapper, (nodes,), kw )
def doit(self, nodes,):
ats = nodes.findType(Atom)
res = ats[0].parent
self.setUp(res)
atom = nodes[0]
self.spheres.Set(vertices=(atom.coords,))
self.vf.GUI.VIEWER.Redraw()
if not hasattr(atom,'charge'):
msg = 'atom has no charge: calling XXXXX'
print msg
#self.warningMsg(msg)
self.oldCharge.set(atom.charge)
ifd = self.ifd = InputFormDescr(title='Enter New Charge')
ifd.append({'name':'eCLab',
'widgetType':Tkinter.Label,
'text':'Enter new charge for:\n' + atom.full_name(),
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'eCEnt',
'widgetType':Tkinter.Entry,
'wcfg':{'textvariable':self.oldCharge},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
vals = self.vf.getUserInput(ifd)
if len(vals)>0:
atom._charges[atom.chargeSet] = float(vals['eCEnt'])
self.vf.labelByExpression(AtomSet([atom]),
textcolor=(1.0, 1.0, 1.0),
negate=0,
format=None,
location='Center',
log=0,
font='arial1.glf',
only=0,
lambdaFunc=1,
function='lambda x: str(x.charge)')
#also update something showing the sum on this residue
self.vf.setIcomLevel(Residue, topCommand=0)
res = atom.parent
res.new_sum = round(Numeric.sum(res.atoms.charge),4)
self.vf.labelByProperty(ResidueSet([res]), properties=("new_sum",), \
textcolor="yellow", log=0, font="arial1.glf")
self.vf.setIcomLevel(Atom, topCommand=0)
else:
return 'ERROR'
self.spheres.Set(vertices=[])
self.vf.GUI.VIEWER.Redraw()
def checkStartOk(self):
self.vf.setIcomLevel(Atom)
sel = self.vf.getSelection()
lenSel = len(sel)
if lenSel:
resSet = sel.findType(Residue).uniq()
ats = resSet[0].atoms
self.vf.setIcomLevel(Atom, topCommand=0)
#make sure each atom has a charge
chrgdAts = ats.get(lambda x: hasattr(x, 'charge'))
if chrgdAts is None or len(chrgdAts)!=len(ats):
self.warningMsg('not all atoms have charge')
self.stopICOM()
return 0
else:
return 1
else:
return 0
def setUp(self, res):
#print 'setUp with ', res.full_name()
#label with the smaller error either the floor or ceiling
chsum = Numeric.sum(res.atoms.charge)
fl_sum = math.floor(chsum)
ceil_sum = math.ceil(chsum)
#always add err to end up with either fl_sum or ceil_sum
errF = fl_sum - chsum
#errF = chsum - fl_sum
#errC = chsum - ceil_sum
errC = ceil_sum - chsum
absF = math.fabs(errF)
absC = math.fabs(errC)
#make which ever is the smaller adjustment
if absC<absF:
err = round(errC, 4)
else:
err = round(errF, 4)
#print 'labelling with err = ', err
res.err = err
self.vf.setIcomLevel(Atom, topCommand=0)
self.vf.labelByExpression(res.atoms,textcolor=(1.0, 1.0, 1.0),
negate=0,
format=None,
location='Center',
log=0,
font='arial1.glf',
only=0,
lambdaFunc=1,
function='lambda x: str(x.charge)')
self.vf.setIcomLevel(Residue, topCommand=0)
#res.new_sum = round(Numeric.sum(res.atoms.charge),4)
#self.vf.labelByProperty(ResidueSet([res]), properties=("new_sum",), \
self.vf.labelByProperty(ResidueSet([res]), properties=("err",), \
textcolor="yellow", log=0, font="arial1.glf")
self.vf.setIcomLevel(Atom, topCommand=0)
def startICOM(self):
self.vf.setIcomLevel(Atom)
#ok = self.checkStartOk()
#if ok:
#nodes = self.vf.getSelection()
#res = nodes.findType(Residue).uniq()
#if not len(res):
# return 'ERROR'
#self.setUp(res[0])
def stopICOM(self):
self.spheres.Set(vertices=[])
sel = self.vf.getSelection()
selAts = sel.findType(Atom)
self.vf.setIcomLevel(Residue, topCommand=0)
self.vf.labelByProperty(selAts.parent.uniq(), log=0, negate=1)
self.vf.setIcomLevel(Atom, topCommand=0)
self.vf.labelByExpression(sel, lambdaFunc=1, function='lambda x:2',\
log=0, negate=1)
self.vf.GUI.VIEWER.Redraw()
def setupUndoBefore(self, ats):
ustr = ''
for at in ats:
##typeAtoms types everything so can't undo it
#if hasattr(at, 'babel_type'):
ustr=ustr + '"at=self.expandNodes('+'\''+at.full_name()+'\''+')[0];at._charges[at.chargeSet]=float(\''+ str(at.charge)+'\');res = at.parent; import numpy.oldnumeric as Numeric;from MolKit.protein import ResidueSet; res.new_sum = round(Numeric.sum(res.atoms.charge),4);self.labelByProperty(ResidueSet([res]), properties = (\'new_sum\',),textcolor = \'yellow\',font=\'arial1.glf\',log=0)"'
self.undoCmds = "exec("+ustr+")"
#NEED to redo labels here, too
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
ok = self.checkStartOk()
if ok:
#nodes = self.vf.getSelection()
#res = nodes.findType(Residue).uniq()
#set up list of residues with non-integral charges
#self.setUp(res[0])
#self.setUp(self.vf.getSelection())
self.vf.setICOM(self, modifier="Shift_L", topCommand=0)
editAtomChargeGUICommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Atoms',
'menuEntryLabel':'Edit Charge'}
EditAtomChargeGUICommandGUI = CommandGUI()
EditAtomChargeGUICommandGUI.addMenuCommand('menuRoot', 'Edit', 'Edit Charge',
cascadeName='Charges')#, index=1)
class TypeBondsCommand(MVCommand):
"""This class uses the BondOrder class to compute bond order.
\nPackage:Pmv
\nModule :editCommands
\nClass:TypeBondsCommand
\nCommand:typeBonds
\nSynopsis:\n
None<---typeBonds(nodes, withRings=0, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
withRings: default is 0
Before a BondOrder object can be used, atoms must have been assigned
a type see (AtomHybridization in types.py).\n
Bond order can be calculated using 2 different methods depending on whether
rings have been identified previously or not. Babel decides to use the first
method for molecules with more than 200 atoms and the second one else.\n
example:\n
>>> atype = AtomHybridization()\n
>>> atype.assignHybridization(atoms)\n
>>> bo = BondOrder()\n
>>> bo.assignBondOrder( atoms, bonds )\n
or\n
>>> atype = AtomHybridization()\n
>>> atype.assignHybridization(atoms)\n
>>> rings = RingFinder()\n
>>> rings.findRings(allAtoms, bonds)\n
>>> bo = BondOrder()\n
>>> bo.assignBondOrder( atoms, bonds, rings )\n
atoms has to be a list of atom objects\n
Atom:\n
a .coords : 3-sequence of floats\n
a .bonds : list of Bond objects\n
babel_type: string\n
babel_atomic_number: int\n
Bond:\n
b .atom1 : instance of Atom\n
b .atom2 : instance of Atom\n
after completion each bond has a 'bondOrder' attribute (integer)\n
reimplementation of Babel1.6 in Python by <NAME> April 2000
Original code by <NAME> and <NAME>\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def doit(self, nodes, withRings=False):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
mols = nodes.top.uniq()
for mol in mols:
allAtoms = mol.allAtoms
if hasattr(mol, 'rings'): continue
try:
allAtoms.babel_type
except:
babel = AtomHybridization()
babel.assignHybridization(allAtoms)
#allAtoms = nodes.findType(Atom)
bonds = allAtoms.bonds[0]
if withRings:
rings = RingFinder()
rings.findRings2(allAtoms, bonds)
else:
rings = None
mol.rings = rings
# create a new attribute to know which rings a bond belongs to maybe should be done in cycle.py
if not mol.rings is None:
mol.rings.bondRings = {}
for ind in xrange(len(mol.rings.rings)):
r = mol.rings.rings[ind]
for b in r['bonds']:
if not mol.rings.bondRings.has_key(b):
mol.rings.bondRings[b] = [ind,]
else:
mol.rings.bondRings[b].append(ind)
bo = BondOrder()
bo.assignBondOrder(allAtoms, bonds, rings)
allAtoms._bndtyped = 1
if withRings:
# do aromatic here
arom = Aromatic(rings)
arom.find_aromatic_atoms(allAtoms)
def __call__(self, nodes, withRings=False, **kw):
"""None<---typeBonds(nodes, withRings=0, **kw)
\nnodes --- TreeNodeSet holding the current selection
\nwithRings --- default is 0"""
kw['withRings'] = withRings
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
apply ( self.doitWrapper, (nodes,), kw )
def guiCallback(self):
#put in checkbutton here for w/ or w/out rings
ifd = InputFormDescr(title="Type bonds:")
ifd.append({'name': 'rings',
'text': 'With Rings',
'widgetType': Tkinter.Checkbutton,
'variable': Tkinter.IntVar(),
'gridcfg': {'sticky':'w'}})
val = self.vf.getUserInput(ifd)
sel = self.vf.getSelection()
if val and len(sel):
self.doitWrapper(sel, val['rings'],log=1,redraw=0)
typeBondsCommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Bonds',
'menuEntryLabel':'Type'}
TypeBondsCommandGUI = CommandGUI()
TypeBondsCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Type' ,
cascadeName='Bonds')
class AddHydrogensGUICommand(MVCommand):
"""This GUICOMMAND class calls the AddHydrogenCommand class.
\nPackage:Pmv
\nModule :editCommands
\nClass:AddHydrogensGUICommand
\nCommand:add_hGC
\nSynopsis:\n
None<---add_hGC(nodes, polarOnly=0, method='noBondOrder', renumber=1,**kw)\n
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
polarOnly --- default is 0\n
method --- Hydrogen atoms can be added using 2 different methods, ex: method='withBondOrder', default is 'noBondOrder'\n
renumber --- default is 1\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'add_h'):
self.vf.loadCommand('editCommands', 'add_h','Pmv',
topCommand=0)
def __call__(self, nodes, polarOnly=False, method='noBondOrder',
renumber=True, **kw):
"""None<---add_hGC(nodes, polarOnly=False, method='noBondOrder',
renumber=1,**kw)
\nnodes --- TreeNodeSet holding the current selection
\npolarOnly --- default is False
\nmethod --- Hydrogen atoms can be added using 2 different methods,
ex: method='withBondOrder', default is 'noBondOrder'
\nrenumber --- Boolean flag when set to True the atoms are renumbered. (default is True)
"""
#kw['topCommand'] = 0
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
apply(self.doitWrapper,(nodes,polarOnly,method,renumber,), kw)
def doit(self, nodes, polarOnly, method, renumber):
""" None <- add_h(nodes, polarOnly=0, method='noBondOrder',
renumber=1)"""
newHs = self.vf.add_h(nodes, polarOnly, method, renumber,topCommand=0)
#it could be that there are no new hydrogens: then don't log + return
if not len(newHs): return 'ERROR'
molecules, ats = self.vf.getNodesByMolecule(newHs)
## for mol, hSet in map(None, molecules, ats):
## #to update display
## done = 0
## for name, g in mol.geomContainer.geoms.items():
## #if name in ['lines', 'cpk', 'balls', 'sticks']:
## if name=='lines':
## if g.visible:
## kw = self.vf.displayLines.getLastUsedValues()
## kw['topCommand']=0
## kw['redraw']=1
## apply(self.vf.displayLines, (hSet,), kw)
## if name=='cpk':
## if g.visible:
## kw = self.vf.displayCPK.getLastUsedValues()
## kw['topCommand']=0
## kw['redraw']=1
## apply(self.vf.displayCPK, (hSet,), kw)
## if not done and (name=='balls' or name=='sticks'):
## if g.visible:
## kw = self.vf.displaySticksAndBalls.getLastUsedValues()
## kw['topCommand']=0
## kw['redraw']=1
## apply(self.vf.displaySticksAndBalls, (hSet,), kw)
## done = 1
def guiCallback(self):
sel = self.vf.getSelection()
if not len(sel):
self.warningMsg("No Molecules in Viewer!")
return
# check for non-bonded atoms
mols = sel.findType(Protein, uniq=1)
nonbnded = AtomSet()
for m in mols:
if m == mols[0]:
mnames = m.name
else:
mnames = ',' + m.name
nbs = m.get_nonbonded_atoms()
if len(nbs): nonbnded += nbs
if len(nonbnded):
msg = ' Try adding hydrogens anyway?\n Found non-bonded atoms in ' + mnames +":\n"
d = Pmw.TextDialog(self.vf.GUI.ROOT, scrolledtext_labelpos = 'n',
title = 'Add hydrogens',
buttons =['No', 'Yes'] , defaultbutton = 0,
label_text = msg , text_width=30, text_height=20)
d.withdraw()
msg = ""
for b in nonbnded:
msg = msg + " " + b.full_name() + "\n"
## d = SimpleDialog(self.vf.GUI.ROOT, text=msg,
## buttons=['No','Yes'], default=0,
## title='Try adding hydrogens anyway?')
## tryAnyway = d.go()
d.insert('end', msg)
tryAnyway = d.activate()
if tryAnyway == "No":
return "ERROR"
ifd = InputFormDescr(title = "Add Hydrogens:")
hydrogenChoice = Tkinter.IntVar()
hydrogenChoice.set(0)
methodChoice = Tkinter.StringVar()
if os.path.splitext(sel.top[0].parser.filename)[1]=='.pdb':
methodChoice.set('noBondOrder')
else:
methodChoice.set('withBondOrder')
#if len(sel.findType(Atom))>200:
#methodChoice.set('noBondOrder')
#else:
#methodChoice.set('withBondOrder')
#methodChoice.set('noBondOrder')
renumberChoice = Tkinter.IntVar()
renumberChoice.set(1)
ifd.append({'name': 'allHs',
'text': 'All Hydrogens',
'widgetType': Tkinter.Radiobutton,
'value':0,
'variable': hydrogenChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name': 'polarOnly',
'text': 'Polar Only',
'widgetType': Tkinter.Radiobutton,
'value':1,
'variable': hydrogenChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name':'methodLab',
'widgetType':Tkinter.Label,
'text':'Method',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name': 'noBondOrder',
'text': 'noBondOrder (for pdb files...)',
'widgetType': Tkinter.Radiobutton,
'value':'noBondOrder',
'variable': methodChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name': 'withBondOrder',
'text': 'withBondOrder (if you trust the bond order info)',
'widgetType': Tkinter.Radiobutton,
'value':'withBondOrder',
'variable': methodChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name':'renumberLab',
'widgetType':Tkinter.Label,
'text':'Renumber atoms to include new hydrogens',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name': 'yesRenumber',
'text': 'yes',
'widgetType': Tkinter.Radiobutton,
'value':1,
'variable': renumberChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name': 'noRenumber',
'text': 'no',
'widgetType': Tkinter.Radiobutton,
'value':0,
'variable': renumberChoice,
'gridcfg': {'sticky':'w'}})
val = self.vf.getUserInput(ifd)
if val:
self.doitWrapper(sel, polarOnly=hydrogenChoice.get(),
method=methodChoice.get(), renumber=renumberChoice.get(),
redraw=1)
addHydrogensGUICommandGuiDescr = {'widgetType':'Menu','menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Hydrogens',
'menuEntryLabel':'Add'}
AddHydrogensGUICommandGUI = CommandGUI()
AddHydrogensGUICommandGUI.addMenuCommand('menuRoot', 'Edit', 'Add',
cascadeName='Hydrogens')
class AddHydrogensCommand(MVCommand):
"""This command adds hydrogen atoms to all atoms in all molecules that have at least one member (i.e atom, residue, chain, base-pair etc..) specified in the first argument.
\nPackage:Pmv
\nModule :editCommands
\nClass:AddHydrogensCommand
\nCommand:add_h
\nSynopsis:\n
AtomSet<---add_h(nodes, polarOnly=0, method='noBondOrder,
renumber=1,**kw)\n
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
polarOnly --- default is 0\n
method --- Hydrogen atoms can be added using 2 different methods, ex: method='withBondOrder', default is 'noBondOrder'\n
renumber --- default is 1\n
Returns an atomSet containing the created H atoms\n
NOTE: This command adds hydrogens to all atoms in the molecule specified using the nodes argument.\n
The hydrogen atoms added to each molecule are also saved as a set called mol.name + '_addedH'\n
This class uses the AddHydrogens class from the PyBabel package.\n
Before this AddHydrogens object can be used, atoms must have been assigned
a type see (AtomHybridization in types.py).\n
Hydrogen atoms can be added using 2 different methods. The first one requires
bondOrders to have been calculated previousely.\n
example:\n
>>> atype = AtomHybridization()\n
>>> atype.assignHybridization(atoms)\n
>>> addh = AddHydrogens()\n
>>> hat = addh.addHydrogens(atoms)\n
atoms has to be a list of atom objects\n
Atom:\n
a .coords : 3-sequence of floats\n
a .bonds : list of Bond objects\n
babel_type: string\n
babel_atomic_number: int\n
Bond:\n
b .atom1 : instance of Atom\n
b .atom2 : instance of Atom\n
or\n
>>> addh = AddHydrogens()\n
>>> hat = addh.addHydrogens(atoms, method='withBondOrder')\n
atoms has to be a list of atom objects as above and\n
Bond:\n
b .atom1 : instance of Atom\n
b .atom2 : instance of Atom\n
b .bondOrder : integer\n
these calls return a list 'hat' containing a tuple for each Hydrogen
atom to be added. This tuple provides:\n
coordsH : 3-float coordinates of the H atom\n
atom : the atom to which the H atom is to be connected\n
atomic_number : the babel_atomic_number of the H atom\n
type : tyhe b:wabel_type of the H atom\n
reimplementation of Babel1.6 in Python by <NAME> April 2000
Original code by <NAME> and <NAME>\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('typeBonds'):
self.vf.loadCommand('editCommands', 'typeBonds','Pmv',
topCommand=0)
if not self.vf.commands.has_key("saveSet"):
self.vf.loadCommand("selectionCommands", "saveSet", "Pmv",
topCommand=0)
if not self.vf.commands.has_key("selectSet"):
self.vf.loadCommand("selectionCommands", "selectSet", "Pmv",
topCommand=0)
if not self.vf.commands.has_key("fixHNames"):
self.vf.loadCommand("editCommands", "fixHNames", "Pmv",
topCommand=0)
def __call__(self, nodes, polarOnly=False, method='noBondOrder',
renumber=True, **kw):
"""
AtomSet <- add_h(nodes, polarOnly=0, method='noBondOrder,
renumber=1,**kw)
\nnodes --- TreeNodeSet holding the current selection
\npolarOnly --- default is False
\nmethod --- Hydrogen atoms can be added using 2 different methods,
\nex --- method='withBondOrder', default is 'noBondOrder'
\nrenumber --- default is True
\nReturns an atomSet containing the created H atoms
\nNOTE: This command adds hydrogens to all atoms in the molecule
specified using the nodes argument.
\nThe hydrogen atoms added to each molecule are also saved as a set
called mol.name + '_addedH'
"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
return apply(self.doitWrapper,(nodes,polarOnly,method,renumber,), kw)
def doit(self, nodes, polarOnly=False, method='noBondOrder',
renumber=True):
""" None <- add_h(nodes, polarOnly=False, method='noBondOrder', renumber=True)"""
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
mols = nodes.top.uniq()
newHs = AtomSet([]) # list of created H atoms (will be returned)
resList = {} # used to get a list of residues with added H atoms
for mol in mols:
# check if we need to assign babel atom types
try:
t = mol.allAtoms.babel_type
except:
babel = AtomHybridization()
babel.assignHybridization(mol.allAtoms)
# check if we need to assign bond orders
if method=='withBondOrder':
allBonds, noBonds = mol.allAtoms.bonds
haveBO = 1
for b in allBonds:
if b.bondOrder is None:
haveBO = 0
break
if haveBO==0:
self.vf.typeBonds(mol, withRings=1, topCommand=0)
# add hydrogen atoms to this molecule
addh = AddHydrogens()
hat = addh.addHydrogens(mol.allAtoms, method=method)
# build lists of all H atoms bonded to the same heavy atom
bondedAtomDict = {} # key is heavy atom
for a in hat:
if bondedAtomDict.has_key(a[1]):
bondedAtomDict[a[1]].append(a)
else:
bondedAtomDict[a[1]] = [a]
# now create Atom object for hydrogens
# and add the to the residues's atom list
molNewHs = AtomSet([]) # list of created H atoms for this molecule
heavyAtoms = AtomSet([]) # list of atoms that need new radii
for heavyAtom, HatmsDscr in bondedAtomDict.items():
# do not add H to Carbon atoms if polarOnly is specified
if polarOnly:
if heavyAtom.element=='C': continue
res = heavyAtom.parent
resList[res] = 1
# find where to insert H atom
childIndex = res.children.index(heavyAtom)+1
# loop over H atoms description to be added
# start art the end because (go ask RUTH)
l = len(HatmsDscr)
for i in range(l-1,-1,-1):
a = HatmsDscr[i]
# build H atom's name
if len(heavyAtom.name)==1:
name = 'H' + heavyAtom.name
else:
name = 'H' + heavyAtom.name[1:]
# if more than 1 H atom, add H atom index
# for instance HD11, HD12, Hd13 (index is 1,2,3)
if l > 1:
name = name + str(i+1)
#this is needed to avoid bug #752 alternate position atoms
if '@' in name and '@' in a[1].name:
at_position = name.find('@')
name = name[:at_position] + name[at_position+2:] + \
name[at_position:at_position+2]
# create the H atom object
atom = Atom(name, res, top=heavyAtom.top,
chemicalElement='H',
childIndex=childIndex, assignUniqIndex=0)
# set atoms attributes
atom._coords = [ a[0] ]
if hasattr(a[1], 'segID'): atom.segID = a[1].segID
atom.hetatm = heavyAtom.hetatm
atom.alternate = []
#atom.element = 'H'
atom.occupancy = 1.0
atom.conformation = 0
atom.temperatureFactor = 0.0
atom.babel_atomic_number = a[2]
atom.babel_type = a[3]
atom.babel_organic = 1
atom.radius = 1.2
# create the Bond object bonding Hatom to heavyAtom
bond = Bond( a[1], atom, bondOrder=1)
# add the created atom the the list
newHs.append(atom)
molNewHs.append(atom)
# create the color entries for all geoemtries
# available for the heavyAtom
for key, value in heavyAtom.colors.items():
atom.colors[key]=(1.0, 1.0, 1.0)
atom.opacities[key]=1.0
# DO NOT set charges to 0.0
##for key in heavyAtom._charges.keys():
##atom._charges[key] = 0.0
heavyAtoms.append(heavyAtom)
if not len(newHs):
# if there are no newHs, return empty AtomSet here
return newHs
# assign non united radii to heavy atoms
mol.defaultRadii(atomSet=heavyAtoms, united=0 )
# update the allAtoms set in the molecule
mol.allAtoms = mol.findType(Atom)
if renumber:
fst = mol.allAtoms[0].number
mol.allAtoms.number = range(fst, len(mol.allAtoms)+fst)
# save the added atoms as a set
if len(molNewHs) > 0:
setName = mol.name + '_addedH'
self.vf.saveSet( molNewHs, setName,
'added by addh command', topCommand=0)
for r in resList.keys():
r.assignUniqIndex()
# update self.vf.Mols.allAtoms
self.vf.allAtoms = self.vf.Mols.allAtoms
event = AddAtomsEvent(objects=newHs)
self.vf.dispatchEvent(event)
return newHs
class FixHydrogenAtomNamesGUICommand(MVCommand):
"""This class provides Graphical User Interface to FixHydrogenAtomsNameCommand
which is invoked by it with the current selection, if there is one.
\nPackage:Pmv
\nModule :editCommands
\nClass:FixHydrogenAtomNamesGUICommand
\nCommand:fixHNamesGC
\nSynopsis:\n
None<---fixHNamesGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'fixHNames'):
self.vf.loadCommand('editCommands', 'fixHNames','Pmv',
topCommand=0)
def doit(self, nodes):
self.vf.fixHNames(nodes)
def __call__(self, nodes, **kw):
"""None <- fixHNamesGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
apply( self.doitWrapper, (nodes,), kw )
def guiCallback(self):
sel=self.vf.getSelection()
if len(sel):
self.doitWrapper(sel, topCommand=0)
fixHydrogenAtomNamesGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Hydrogens',
'menuEntryLabel':'Fix Pdb Names'}
FixHydrogenAtomNamesGUICommandGUI = CommandGUI()
FixHydrogenAtomNamesGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
'Fix Pdb Names', cascadeName='Hydrogens')
class FixHydrogenAtomNamesCommand(MVCommand):
"""\nThis class checks hydrogen atom names and modifies them to conform to 'IUPAC-IUB' conventions
\nPackage:Pmv
\nModule :editCommands
\nClass:FixHydrogenAtomNamesCommand
\nCommand:fixHNames
\nSynopsis:\n
None <- fixHNames(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
Hydrogen names have 4 spaces:'H _ _ _', (here referred to as 1-4).\n
'H' is always in space 1.\n
Space 2 references the name of the atom to which H is bonded
using the following scheme: \n
IF the name has 1 letter, space 2 is that letter. \n
IF the name has more than 1 letter, space 2 is the second letter
in that name and space 3 the third letter if it exists. \n
(Please note that the second space in the bonded atom name is a 'remoteness'
indicator and the third used to number items equally remote.)\n
In all cases, the LAST space (which could be space 3 or space 4
depending on the bonded-atom's name) is used to number hydrogen atoms
when more than one are bound to the same atom.\n
EXAMPLES:\n
HN <- hydrogen bonded to atom named 'N'\n
HA <- hydrogen bonded to atom named 'CA'\n
HE <- hydrogen bonded to atom named 'NE'\n
HH11 <- first hydrogen bonded to atom named 'NH1'\n
HH12 <- second hydrogen bonded to atom named 'NH1'\n
HD21 <- first hydrogen bonded to atom named 'CD2'\n
________________________________________________________________________\n
A final complexity results when these names are written in pdb files:\n
The name of the atom appears RIGHT-JUSTIFIED in the first two columns of
the 4 columns involved (13-16). Thus 'H' appears in column 14 for all hydrogen
atoms. This creates a problem for 4 character hydrogen names. They are
accommodated by wrapping so that space 4 appears in column 13.\n
EXAMPLE:\n
1HD2 <- first hydrogen bonded to atom named 'CD2' as represented
in a pdb file.\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def doit(self, nodes):
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
allAtoms = nodes.findType(Atom)
allHs = allAtoms.get('H*')
if allHs is None or len(allHs)==0: return 'ERROR'
ct = 0
for a in allHs:
if not len(a.bonds): continue
b=a.bonds[0]
a2=b.atom1
if a2==a: a2=b.atom2
if a2.name=='N':
hlist = a2.findHydrogens()
if len(hlist) == 1:
if a.name!='HN':
#print 'fixing atom ', a.full_name()
a.name = 'HN'
ct = ct + 1
else:
for i in range(len(hlist)):
if hlist[i].name[:2]!='HN' or len(hlist[i].name)<3:
#print 'fixing atom ', hlist[i].full_name()
ct = ct + 1
hlist[i].name = 'HN'+str(i+1)
if len(a2.name)>1:
remote=a2.name[1]
if remote in letters:
if len(a.name)<2 or remote!=a.name[1]:
#print 'fixing remote atom', a.full_name()
ct = ct + 1
a.name = a.name[0]+a2.name[1]
if len(a.name)>2:
a.name=a.name+a.name[2:]
else:
newname = a.name + remote
if len(a.name)>1:
newname=newname+a.name[1:]
def __call__(self, nodes, **kw):
"""None <--- fixHNames(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
apply ( self.doitWrapper, (nodes,), kw )
## class FixHydrogenAtomNamesGUICommand(MVCommand):
## """
## This class provides Graphical User Interface to FixHydrogenAtomsNameCommand
## which is invoked by it with the current selection, if there is one.
## """
## def __init__(self, func=None):
## MVCommand.__init__(self, func)
## self.flag = self.flag | self.objArgOnly
## def onAddCmdToViewer(self):
## if not hasattr(self.vf, 'fixHNames'):
## self.vf.loadCommand('editCommands', 'fixHNames','Pmv',
## topCommand=0)
## def doit(self, nodes):
## self.vf.fixHNames(nodes)
## def __call__(self, nodes, **kw):
## """None<---fixHNamesGC(nodes, **kw)
## \nnodes --- TreeNodeSet holding the current selection"""
## if type(nodes) is types.StringType:
## self.nodeLogString = "'"+nodes+"'"
## apply( self.doitWrapper, (nodes,), kw )
## def guiCallback(self):
## sel=self.vf.getSelection()
## if len(sel):
## ## if self.vf.userpref['expandNodeLogString']['value'] == 0:
## ## # The GUI command doesn't log itself but the associated command
## ## # does so we need to set the nodeLogString of the Command
## ## self.vf.fixHNames.nodeLogString = "self.getSelection()"
## self.doitWrapper(sel, topCommand=0)
## fixHydrogenAtomNamesGUICommandGuiDescr = {'widgetType':'Menu',
## 'menuBarName':'menuRoot',
## 'menuButtonName':'Edit',
## 'menuCascadeName':'Hydrogens',
## 'menuEntryLabel':'Fix Pdb Names'}
## FixHydrogenAtomNamesGUICommandGUI = CommandGUI()
## FixHydrogenAtomNamesGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
## 'Fix Pdb Names', cascadeName='Hydrogens')
#class FixHydrogenAtomNamesCommand(MVCommand):
# """
#This class checks hydrogen atom names and modifies them to conform to
#IUPAC-IUB conventions:
#Hydrogen names have 4 spaces:'H _ _ _', (here referred to as 1-4).
# 'H' is always in space 1.
# Space 2 references the name of the atom to which H is bonded
# using the following scheme:
# IF the name has 1 letter, space 2 is that letter.
# IF the name has more than 1 letter, space 2 is the second letter
# in that name and space 3 the third letter if it exists.
#(Please note that the second space in the bonded atom name is a 'remoteness'
#indicator and the third used to number items equally remote.)
# In all cases, the LAST space (which could be space 3 or space 4
#depending on the bonded-atom's name) is used to number hydrogen atoms
#when more than one are bound to the same atom.
#EXAMPLES:
# HN <- hydrogen bonded to atom named 'N'
# HA <- hydrogen bonded to atom named 'CA'
# HE <- hydrogen bonded to atom named 'NE'
# HH11 <- first hydrogen bonded to atom named 'NH1'
# HH12 <- second hydrogen bonded to atom named 'NH1'
# HD21 <- first hydrogen bonded to atom named 'CD2'
#________________________________________________________________________
#A final complexity results when these names are written in pdb files:
#The name of the atom appears RIGHT-JUSTIFIED in the first two columns of
#the 4 columns involved (13-16). Thus 'H' appears in column 14 for all hydrogen
#atoms. This creates a problem for 4 character hydrogen names. They are
#accommodated by wrapping so that space 4 appears in column 13.
#EXAMPLE:
# 1HD2 <- first hydrogen bonded to atom named 'CD2' as represented
#in a pdb file.
# """
# def __init__(self, func=None):
# MVCommand.__init__(self, func)
# self.flag = self.flag | self.objArgOnly
# def doit(self, nodes):
# nodes = self.vf.expandNodes(nodes)
# if not len(nodes): return 'ERROR'
#
# allAtoms = nodes.findType(Atom)
# allHs = allAtoms.get('H.*')
## if allHs is None or len(allHs)==0: return 'ERROR'
# ct = 0
# for a in allHs:
# if not len(a.bonds): continue
# b=a.bonds[0]
# a2=b.atom1
# if a2==a: a2=b.atom2
# if a2.name=='N':
# hlist = a2.findHydrogens()
# if len(hlist) == 1:
# if a.name!='HN':
# #print 'fixing atom ', a.full_name()
# a.name = 'HN'
# ct = ct + 1
# else:
# for i in range(len(hlist)):
## if hlist[i].name[:2]!='HN' or len(hlist[i].name)<3:
# #print 'fixing atom ', hlist[i].full_name()
# ct = ct + 1
# hlist[i].name = 'HN'+str(i+1)
## if len(a2.name)>1:
# remote=a2.name[1]
## if remote in letters:
# if remote!=a.name[1]:
# #print 'fixing remote atom', a.full_name()
# ct = ct + 1
# a.name = a.name[0]+a2.name[1]
# if len(a.name)>2:
# a.name=a.name+a.name[2:]
# else:
# newname = a.name + remote
# if len(a.name)>1:
# newname=newname+a.name[1:]
##
#
# def __call__(self, nodes, **kw):
# """None <- fixHNames(nodes, **kw)
# nodes: TreeNodeSet holding the current selection"""
# if type(nodes) is types.StringType:
# self.nodeLogString = "'"+nodes+"'"
# apply ( self.doitWrapper, (nodes,), kw )
class SplitNodesGUICommand(MVCommand):
""" This class presents GUI for SplitNodesCommand
\nPackage:Pmv
\nModule :editCommands
\nClass:SplitNodesGUICommand
\nCommand:splitNodesGC
\nSynopsis:\n
None<---splitNodesGC(nodes, levelToSplit, top, renumber=1, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
levelToSplit --- splitting level\n
top --- \n
renumber --- default is 1\n
"""
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'splitNodes'):
self.vf.loadCommand('editCommands', 'splitNodes','Pmv',
topCommand=0)
def onAddCmdToViewer(self):
import MolKit
self.levelDict={}
self.levelDict['Molecule']=MolKit.molecule.Molecule
self.levelDict['Protein']=MolKit.protein.Protein
self.levelDict['Chain']=MolKit.protein.Chain
self.levelDict['Residue']=MolKit.protein.Residue
self.levelStrings={}
self.levelStrings[MolKit.molecule.Molecule]='Molecule'
self.levelStrings[MolKit.protein.Protein]='Protein'
self.levelStrings[MolKit.protein.Chain]='Chain'
self.levelStrings[MolKit.protein.Residue]='Residue'
def __call__(self, nodes, levelToSplit, top, renumber=1, **kw):
"""None<---splitNodesGC(nodes, levelToSplit, top, renumber=1, **kw)
\nnodes --- TreeNodeSet holding the current selection
\nlevelToSplit --- splitting level
\ntop ---
\nrenumber --- default is 1"""
if type(levelToSplit)==types.StringType:
levelToSplit = self.levelDict[levelToSplit]
kw['renumber'] = renumber
apply(self.doitWrapper, (nodes, levelToSplit, top,), kw)
def fixIDS(self, chains):
idList = chains.id
ifd = self.ifd = InputFormDescr(title="Set unique chain ids")
ent_varDict = self.ent_varDict = {}
self.nStrs = []
self.entStrs = []
self.chains = chains
ifd.append({'name':'Lab1',
'widgetType':Tkinter.Label,
'text':'Current',
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'Lab2',
'widgetType':Tkinter.Label,
'text':'New',
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
for ch in chains:
#fix the chain numbers here, also
ch.number = self.vf.Mols.chains.index(ch)
idList = chains.id
ct = idList.count(ch.id)
if ct!=1:
for i in range(ct-1):
ind = idList.index(ch.id)
idList[ind] = ch.id+str(i)
for i in range(len(chains)):
chid = idList[i]
ch = chains[i]
nStr = chid+'_lab'
self.nStrs.append(nStr)
entStr = chid+'_ent'
self.entStrs.append(entStr)
newEntVar = ent_varDict[ch] = Tkinter.StringVar()
newEntVar.set(ch.id)
ifd.append({'name':nStr,
'widgetType':Tkinter.Label,
'text':ch.full_name(),
'gridcfg':{'sticky':'we'}})
ifd.append({'name':entStr,
'widgetType':Tkinter.Entry,
'wcfg':{ 'textvariable': newEntVar, },
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
vals = self.vf.getUserInput(self.ifd, modal=0, blocking=1)
if vals :
for i in range(len(chains)):
#CHECK for changes in id/name
ch = chains[i]
ll = ch.id
ln = (len(ch.name)+len(ch.id))/2.0
wl = strip(vals[self.entStrs[i]])
if len(wl) and ln!=1:
print 'changed chain ', ch.full_name(), ' to ',
ch.id = wl[0]
ch.name = wl[0]
print ch.full_name()
def doit(self, nodes, levelToSplit, top, **kw):
mol = apply(self.vf.splitNodes, (nodes, levelToSplit, top,),kw)
# if levelToSplit is Molecule/Protein then mol is new mol
# otherwise it is nodes.top with new levelToSplit items: chains or
# residues....
self.vf.select.updateSelectionIcons()
#also need to fix name
#if at chain level, assign a number to the chain
if levelToSplit==self.levelDict['Protein']:
self.fixIDS(mol.chains)
nobnds = mol.geomContainer.atoms['nobnds']
mol.geomContainer.atoms['bonds'] = mol.allAtoms - nobnds
self.vf.displayLines(nodes, negate=1)
self.vf.displayLines(nodes, negate=0)
def guiCallback(self):
nodes=self.vf.getSelection()
if len(nodes)==0: return 'ERROR'
if nodes.__class__==nodes.top.__class__:
msg= "unable to split selection at " + nodes.__class__+ " level"
self.warningMsg(msg)
return
#figure out what levels are available for splitting:
top = nodes.top.uniq()
assert len(top)==1, 'nodes to be split must be in same molecule'
top = top[0]
levelChoices=[]
try:
n = top.levels.index(nodes.elementType)
except:
msg='invalid selection'
self.warningMsg(msg)
return
levels = top.levels[:n]
for item in levels:
levelChoices.append(self.levelStrings[item])
assert len(levelChoices)>0, 'molecule has no levels !?!'
if len(levelChoices)==1:
self.doitWrapper(nodes,self.levelDict[levelChoices[0]],top)
else:
renumberChoice = Tkinter.IntVar()
renumberChoice.set(1)
ifd = InputFormDescr(title='Choose Split Level')
ifd.append({'name':'level',
'widgetType': Tkinter.Radiobutton,
'listtext':levelChoices,
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name':'renumberLab',
'widgetType':Tkinter.Label,
'text':'Renumber atoms after split',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name': 'yesRenumber',
'text': 'yes',
'widgetType': Tkinter.Radiobutton,
'value':1,
'variable': renumberChoice,
'gridcfg': {'sticky':'w'}})
ifd.append({'name': 'noRenumber',
'text': 'no',
'widgetType': Tkinter.Radiobutton,
'value':0,
'variable': renumberChoice,
'gridcfg': {'sticky':'w'}})
val = self.vf.getUserInput(ifd)
if val is not None and len(val):
## if self.vf.userpref['expandNodeLogString']['value'] == 0:
## # The GUI command doesn't log itself but the associated
## # command does so we need to set the nodeLogString of the
## # Command
## self.vf.splitNodes.nodeLogString = "self.getSelection()"
self.doitWrapper(nodes, self.levelDict[val['level']], top,\
renumber=renumberChoice.get(), log=1, redraw=1)
splitNodesGUICommandGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Misc',
'menuEntryLabel':'Split Selection'}
SplitNodesGUICommandGUI = CommandGUI()
SplitNodesGUICommandGUI.addMenuCommand('menuRoot', 'Edit', 'Split Selection',
cascadeName='Misc')
class SplitNodesCommand(MVCommand):
"""This class allows the user to split current selection from unselected nodes.
\nPackage:Pmv
\nModule :editCommands
\nClass:SplitNodesCommand
\nCommand:splitNodes
\nSynopsis:\n
mol<---splitNodes(nodes, levelToSplit, top, renumber=1, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
levelToSplit --- the splitting level\n
top ---\n
renumber --- default is 1\n
if levelToSplit is Molecule/Protein, the new molecule is returned
OTHERWISE the modified molecule is returned\n
The split is done at a level above nodes. If more than one level above nodes exists,
the user chooses the level at which to split. Result of split depends on the designated
splitting level: \n
splits at the Protein/Molecule level result in a new Protein/Molecule\n
splits at other levels result in adding new nodes to the Protein/Molecule: \n
eg. splitting at the chain level adds a new chain to the Protein, etc. etc.\n
"""
def onAddCmdToViewer(self):
import MolKit
self.levelDict={}
self.levelDict['Molecule']=MolKit.molecule.Molecule
self.levelDict['Protein']=MolKit.protein.Protein
self.levelDict['Chain']=MolKit.protein.Chain
self.levelDict['Residue']=MolKit.protein.Residue
self.levelStrings={}
self.levelStrings[MolKit.molecule.Molecule]='Molecule'
self.levelStrings[MolKit.protein.Protein]='Protein'
self.levelStrings[MolKit.protein.Chain]='Chain'
self.levelStrings[MolKit.protein.Residue]='Residue'
def __call__(self, nodes, levelToSplit, top, renumber=True, **kw):
"""mol <- splitNodes(nodes, levelToSplit, top, renumber=1, **kw)
\nnodes --- TreeNodeSet holding the current selection
\nlevelToSplit --- the splitting level
\ntop ---
\nrenumber --- default is 1
\nif levelToSplit is Molecule/Protein, the new molecule is returned
OTHERWISE the modified molecule is returned"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
if type(levelToSplit)==types.StringType:
levelToSplit = self.levelDict[levelToSplit]
kw['renumber'] = renumber
return apply(self.doitWrapper, (nodes, levelToSplit, top,), kw)
def doit(self, nodes, levelToSplit, top, **kw):
renumber = kw['renumber']
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
#FIX THIS: could be in >1 molecule
assert len(nodes.top.uniq())==1, 'nodes to be split must be in same molecule'
if nodes.__class__==nodes.top.__class__:
msg= "unable to split selection at " + nodes.__class__+ " level"
self.warningMsg(msg)
return 'ERROR'
if levelToSplit==top.__class__:
changeAtoms = nodes.findType(Atom)
event = DeleteAtomsEvent(objects=changeAtoms)
self.vf.dispatchEvent(event)
parents=nodes.parent.uniq()
#while parents.elementType!=levelToSplit and parents[0].parent!=None:
while parents[0].__class__!=levelToSplit and \
not parents[0].parent is None:
parents=parents.parent.uniq()
#returnVal = []
#then need to split each parent with its children in nodes
for parent in parents:
children = nodes.__class__(filter(lambda x, parent=parent, nodes=nodes:\
x in parent.findType(nodes.elementType), nodes))
#newnode of class levelToSplit is returned with proper children:
#if top, add to viewer else adopt it by correct parent
#split returns a copy of parent so thisResult is really parentCOPY
thisResult = parent.split(children)
movedAtoms = thisResult.findType(Atom)
#parentAtoms = parent.findType(Atom)
##NB: bogusAtoms are atoms moving to new molecule, newtop
#have to correct bonds here for both sets:
#atSetList = [bogusAtoms, parentAtoms]
#only have to correct bonds in one set
for at in movedAtoms:
for b in at.bonds:
at2 = b.atom1
if at2==at: at2 = b.atom2
if at2 not in movedAtoms:
#print 'removing bond:', b
b.atom1.bonds.remove(b)
b.atom2.bonds.remove(b)
del b
if levelToSplit==top.__class__:
# FIX THIS: should not get >2 as result
# assert len(thisResult)==2, 'faulty split'
# add new molecule to viewer
# add new molecule to viewer
newtop = self.vf.addMolecule(thisResult)
newtop.allAtoms = newtop.chains.residues.atoms
top.allAtoms = top.chains.residues.atoms
#top.allAtoms = top.allAtoms - movedAtoms
#NB: this fixes 'number' but not '_uniqIndex'
if renumber:
for m in [top, newtop]:
fst = m.allAtoms[0].number
m.allAtoms.number = range(fst, len(m.allAtoms)+fst)
#have to rebuilt allAtoms
#newAllAtoms = AtomSet([])
#for item in self.vf.Mols:
#newAllAtoms = newAllAtoms + item.allAtoms
#self.vf.allAtoms = newAllAtoms
self.vf.allAtoms = self.vf.Mols.chains.residues.atoms
#thisResult is top, newtop
#FIX THIS: need to duplicate/split the parser, also
return thisResult
else:
#return top.setClass([top])
return top
class MergeFieldsCommand(MVCommand):
"""This class allows the user to change the fields of one set by the values
of another set.
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeFieldsCommand
\nCommand:mergeFields
\nSynopsis:\n
None <- mergeFields(set1, set2, fieldList=[], negate=0, **kw)
\nRequired Arguments:\n
set1 --- field value of set1\n
set2 --- field value of set1\n
\nOptional Arguments:\n
fieldList --- fields of type Int or Float in a list, default is []\n
negate --- flag when set to 1 undisplay the current selection, default is 0\n
Fields that are of type Int or Float can be added or subtracted.
Specified fields of the items in the first set are incremented or decremented
by those of the second set.\n
"""
def __call__(self, set1, set2, fieldList=[], negate=False, **kw):
"""None <- mergeFields(set1, set2, fieldList=[], negate=0, **kw)
\nset1 --- field value of set1
\nset2 --- field value of set1
\nfieldList --- fields of type Int or Float in a list, default is []
\nnegate --- flag when set to 1 undisplay the current selection, default is 0"""
kw['negate'] = negate
apply(self.doitWrapper, (set1, set2, fieldList,), kw)
def doit(self,set1, set2, fieldList, **kw):
if not len(set1): return 'ERROR'
if not len(set2): return 'ERROR'
negate = kw['negate']
assert len(set1)<=len(set2),'second set must be equal or larger than first'
#possibly truncate second set
set2=set2[:len(set1)]
topSets=[MoleculeSet,ProteinSet]
if not (set1.__class__ in topSets and set2.__class__ in topSets):
assert set1.__class__==set2.__class__, 'sets not of same class'
for f in fieldList:
exec('set1.'+f+'=Numeric.array(set1.'+f+')')
exec('set2.'+f+'=Numeric.array(set2.'+f+')')
if not negate:
exec('set1.'+f+'=Numeric.add(set1.'+f+',set2.'+f+')')
else:
exec('set1.'+f+'=Numeric.subtract(set1.'+f+',set2.'+f+')')
def guiCallback(self):
import Pmv.selectionCommands
set_entries=self.vf.sets.keys()
if not len(set_entries):
msg='No current sets'
self.warningMsg(msg)
return
ifd=InputFormDescr(title='Select two sets')
ifd.append({'name':'labelSet1',
'widgetType':Tkinter.Label,
'text':'Change Set1 values',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name': 'set1List',
'widgetType': Tkinter.Radiobutton,
'listtext':set_entries,
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name':'labelSet2',
'widgetType':Tkinter.Label,
'text':'by values in Set2',
'gridcfg':{'sticky':Tkinter.W, 'row':0, 'column':1}})
ifd.append({'name': 'set2List',
'widgetType': Tkinter.Radiobutton,
'listtext':set_entries,
'gridcfg':{'sticky':Tkinter.W, 'row':1, 'column':1}})
vals = self.vf.getUserInput(ifd)
if vals is not None and len(vals)>0:
set1=self.vf.sets[vals['set1List']]
set2=self.vf.sets[vals['set2List']]
else:
return
entries1 = filter(lambda x: isinstance(x[1], types.IntType)\
or isinstance(x[1], types.FloatType),
set1[0].__dict__.items())
entries1=map(lambda x: x[0], entries1)
entries2 = filter(lambda x: isinstance(x[1], types.IntType)\
or isinstance(x[1], types.FloatType),
set2[0].__dict__.items())
entries2=map(lambda x: x[0], entries2)
entries = filter(lambda x,entries2=entries2:x in entries2, entries1)
ifd=InputFormDescr(title='Select Property')
ifd.append({'name': 'propList',
'widgetType':Tkinter.Radiobutton,
'listtext': entries,
'title':'Select Property(s) to Merge',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name':'negateB',
'widgetType':Tkinter.Checkbutton,
'defaultValue':0,
'wcfg':{'text':'Subtract (when on)'},
'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
vals = self.vf.getUserInput(ifd)
if vals is not None and len(vals)>0:
fieldList = vals['propList']
kw = {}
kw['negate'] = int(vals['negateB'])
kw['log'] =1
kw['redraw'] =1
apply(self.doitWrapper, (set1, set2, [vals['propList']],), kw)
mergeFieldsCommandGuiDescr = {'widgetType':'Menu','menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuEntryLabel':'Fields',
'menuCascadeName':'Misc'}
MergeFieldsCommandGUI = CommandGUI()
MergeFieldsCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Fields',
cascadeName='Misc')
class MergeSetsCommand(MVCommand):
"""This class allows the user to merge two sets into one.
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeSetsCommand
\nCommand:mergeSets
\nSynopsis:\n
None <- mergeSets(set1, set2, **kw)
\nRequired Arguments:\n
set1 --- first set
\nset2 --- second set
One by one items in the first set adopt children of items of the second set\n
"""
def updateAllAtoms(self,mols,negate):
if len(self.vf.Mols)>len(mols):
restmols=self.vf.Mols-mols
allAtoms=restmols.allAtoms
else:
allAtoms=AtomSet([])
classList=[Chain,Residue,Atom]
for m in mols:
if not(len(m.children)):
continue
lnodes=m.setClass([m])
for l in classList:
if l in m.levels:
lnodes=lnodes.findType(l)
m.allAtoms=lnodes
allAtoms=allAtoms+m.allAtoms
self.vf.allAtoms=allAtoms
#print 'at end: self.vf.allAtoms= ', len(self.vf.allAtoms)
def __call__(self, set1, set2, **kw):
"""removedItems <- mergeSets(set1, set2, **kw)
\nset1 --- first set
\nset2 --- second set
"""
return apply(self.doitWrapper, (set1, set2,), kw)
def doit(self,set1, set2, **kw):
if not len(set1): return
if not len(set2): return
assert len(set1)>=len(set2),'len(set1) not >= len(set2)'
negate = kw['negate']
topSets=[MoleculeSet,ProteinSet]
if not (set1.__class__ in topSets and set2.__class__ in topSets):
assert set1.__class__==set2.__class__, 'sets not of same class'
removedItems = set1.__class__([])
top1=set1.top.uniq()[0]
top2=set2.top.uniq()[0]
if top1==top2:
tops=MoleculeSet([top1])
else:
tops=MoleculeSet([top1,top2])
if not negate:
if set2.__class__ != AtomSet and not len(set2.children):
msg='unable to merge currently merged set2'
self.warningMsg(msg)
return 'ERROR'
self.vf.displayLines(set2,negate=1, log=0,redraw=1)
else:
if len(set2.children):
msg='trying to unmerge currently unmerged set2'
self.warningMsg(msg)
return 'ERROR'
for i in range(len(set2)):
item1=set1[i]
item2=set2[i]
#next part deals with trying to update the tree structure correctly
if not negate:
#if there are any children: deal with them:
item2.childrenByName=item2.children.name
if not item2.childrenByName is None:
for c in item2.children:
item1.adopt(c)
for cname in item2.children.name:
ind=item2.children.name.index(cname)
item2.remove(item2.children[ind])
if item2==item2.top:
self.vf.deleteMol(item2)
else:
item2.parent.remove(item2)
removedItems.append(item2)
else:
#if there are any children: deal with them:
if not item2.childrenByName is None:
for c in item2.childrenByName:
child=None
for ch in item1.children:
if ch.name==c:
child=ch
if child is not None:
item2.adopt(child)
for c in item2.childrenByName:
child=None
for ch in item1.children:
if ch.name==c:
child=ch
if child is not None:
item1.remove(child)
item2.parent.adopt(item2)
self.updateAllAtoms(tops,negate)
#lines should deal with this:
#needs to update geomContainer.geoms correctly
#FIX ME: THIS IS A HACK..because only would hide other molecules, etc
#oldats=tops[0].geomContainer.atoms['lines']
oldats=tops[0].geomContainer.atoms['bonded']
newats=tops[0].allAtoms-oldats
if not negate:
self.vf.displayLines(newats,log=0,redraw=1)
##self.vf.select.updateSelectionIcons()
else:
self.vf.displayLines(tops[0].allAtoms, only=1,log=0,redraw=1)
self.vf.displayLines(set2,log=0,redraw=1)
#self.vf.select.updateSelectionIcons()
return removedItems
def guiCallback(self):
import Pmv.selectionCommands
set_entries=self.vf.sets.keys()
if not len(set_entries):
msg='No current sets'
self.warningMsg(msg)
return
if len(set_entries)<2:
msg='Not enough current sets'
self.warningMsg(msg)
return
ifd=InputFormDescr(title='Select two sets')
ifd.append({'name':'labelSet1',
'widgetType':Tkinter.Label,
'text':'Add to Set1',
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name': 'set1List',
'widgetType': Tkinter.Radiobutton,
'listtext':set_entries,
'gridcfg':{'sticky':Tkinter.W}})
ifd.append({'name':'labelSet2',
'widgetType':Tkinter.Label,
'text':'children of nodes in Set2',
'gridcfg':{'sticky':Tkinter.W, 'row':0, 'column':1}})
ifd.append({'name': 'set2List',
'widgetType': Tkinter.Radiobutton,
'listtext':set_entries,
'gridcfg':{'sticky':Tkinter.W, 'row':1, 'column':1}})
ifd.append({'name':'negateB',
'widgetType':Tkinter.Checkbutton,
'defaultValue':0,
'wcfg':{'text':'Negate'},
'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
vals = self.vf.getUserInput(ifd)
if vals is not None and len(vals)>0:
set1=self.vf.sets[vals['set1List']]
set2=self.vf.sets[vals['set2List']]
dict = {}
dict['log'] = 1
dict['redraw'] = 1
dict['negate'] = int(vals['negateB'])
apply(self.doitWrapper,(set1, set2,),dict)
mergeSetsCommandGuiDescr = {'widgetType':'Menu','menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuEntryLabel':'Sets',
'menuCascadeName':'Misc'}
MergeSetsCommandGUI = CommandGUI()
MergeSetsCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Sets',
cascadeName='Misc')
class MergeNPHsGUICommand(MVCommand):
"""This class implements GUICommand for MergeNPHsCommand below
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeNPHsGUICommand
\nCommand:mergeNPHSGC
\nSynopsis:\n
None<---mergeNPHSGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'mergeNPHS'):
self.vf.loadCommand('editCommands', 'mergeNPHS','Pmv',
topCommand=0)
def __call__(self, nodes, **kw):
"""None <- mergeNPHSGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
apply(self.doitWrapper, (nodes,), kw)
def doit(self, nodes, **kw):
ats = nodes.findType(Atom)
hs = ats.get(lambda x: x.element=='H')
hs_with_bonds = hs.get(lambda x: len(x.bonds)>0)
hs_with_no_bonds = hs.get(lambda x: len(x.bonds)==0)
if hs_with_no_bonds:
mols = hs_with_no_bonds.top.uniq()
msg = ""
for m in mols:
msg += m.name + ','
msg = msg[:-1] + ' has ' + str(len(hs_with_no_bonds)) + ' hydrogen(s) with no bonds:'
for at in hs_with_no_bonds:
print 'adding ', at.full_name()
msg += at.parent.parent.name + ':'+ at.parent.name +':'+ at.name + ','
print 'EC:', msg
self.warningMsg(msg[:-1])
#npHs = ats.get(lambda x: x.element=='H' and
#(x.bonds[0].atom1.element=='C' or
#x.bonds[0].atom2.element=='C'))
npHs = hs_with_bonds.get(lambda x: x.bonds[0].atom1.element=='C' or x.bonds[0].atom2.element=='C')
if npHs is not None and len(npHs)!=0:
if kw.has_key('logBaseCmd'):
kw['topCommand'] = kw['logBaseCmd']
apply(self.vf.mergeNPHS,(npHs,),kw)
self.vf.select.updateSelectionIcons()
else:
return 'ERROR'
def guiCallback(self):
sel=self.vf.getSelection()
if len(sel):
if self.vf.undoCmdStack == []:
self.doitWrapper(sel, topCommand=0)
else:
text = """WARNING: This command cannot be undone.
if you choose to continue the undo list will be reset.
Do you want to continue?"""
idf = self.idf = InputFormDescr(title="WARNING")
idf.append({'name': 'testLab',
'widgetType':Tkinter.Label,
'wcfg':{'text':text},
'gridcfg':{'columnspan':3,'sticky':'w'}})
idf.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'CONTINUE',
'command':CallBackFunction(self.cont_cb, sel)},
'gridcfg':{'sticky':'we'}})
idf.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'CANCEL', 'command':self.cancel_cb},
'gridcfg':{'row':-1,'sticky':'we'}})
self.form = self.vf.getUserInput(idf, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.cancel_cb)
def cont_cb(self, sel):
self.vf.resetUndo()
self.form.destroy()
self.doitWrapper(sel, topCommand=0)
def cancel_cb(self, event=None):
self.form.destroy()
mergeNPHsGUICommandGuiDescr = {'widgetType':'Menu','menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Hydrogens',
'menuEntryLabel':'Merge Non-Polar Hs'}
MergeNPHsGUICommandGUI = CommandGUI()
MergeNPHsGUICommandGUI.addMenuCommand('menuRoot', 'Edit', 'Merge Non-Polar',
cascadeName='Hydrogens')
class MergeNPHsCommand(MVCommand):
"""This class merges non-polar hydrogens and the carbons to which they are attached. There are three parts to the process:the charge(s) of non-polar hydrogens are added to those their carbons the bond between the npH and its carbon is removed from the carbon's bonds the hydrogen atoms are removed.
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeNPHsCommand
\nCommand:mergeNPHS
\nSynopsis:\n
None<---mergeNPHS(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def __call__(self, nodes, **kw):
"""None <- mergeNPHS(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
return apply(self.doitWrapper, (nodes,), kw)
def doit(self, nodes, **kw):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
if nodes[0].__class__!=Atom:
nodes = nodes.findType(Atom)
allAtoms = nodes
returnVal = []
#process nodes by molecule
molecules, atomSets = self.vf.getNodesByMolecule(allAtoms)
for mol, atoms in zip(molecules, atomSets):
# we do not delete the atom in mol.mergeNPH but call
# self.vf.deleteAtomSet() instead so that Pmv updates properly
npHSet = mol.mergeNPH(atoms, deleteAtoms=False)
self.vf.deleteAtomSet(npHSet)
return returnVal
class MergeLonePairsGUICommand(MVCommand):
""" This class presents GUI for MergeLonePairsCommand
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeLonePairsGUICommand
\nCommand:mergeLPSGC
\nSynopsis:\n
None<---mergeLPSGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'mergeLPS'):
self.vf.loadCommand('editCommands', 'mergeLPS','Pmv',
topCommand=0)
def __call__(self, nodes, **kw):
"""None <- mergeLPSGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
apply(self.doitWrapper, (nodes,), kw)
def doit(self, nodes, **kw):
ats = nodes.findType(Atom)
lps = ats.get(lambda x:x.element=='Xx'\
and (x.name[0]=='L' or \
x.name[1]=='L'))
if lps is not None and len(lps)!=0:
if kw.has_key('logBaseCmd'):
kw['topCommand'] = kw['logBaseCmd']
apply(self.vf.mergeLPS, (lps,), kw)
self.vf.select.updateSelectionIcons()
else:
return 'ERROR'
def guiCallback(self):
sel=self.vf.getSelection()
if len(sel):
if self.vf.undoCmdStack == []:
self.doitWrapper(sel, topCommand=0)
else:
text = """WARNING: This command cannot be undone.
if you choose to continue the undo list will be reset.
Do you want to continue?"""
idf = self.idf = InputFormDescr(title="WARNING")
idf.append({'name': 'testLab',
'widgetType':Tkinter.Label,
'wcfg':{'text':text},
'gridcfg':{'columnspan':3,'sticky':'w'}})
idf.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'CONTINUE',
'command':CallBackFunction(self.cont_cb, sel)},
'gridcfg':{'sticky':'we'}})
idf.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'CANCEL', 'command':self.cancel_cb},
'gridcfg':{'row':-1,'sticky':'we'}})
self.form = self.vf.getUserInput(idf, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.cancel_cb)
def cont_cb(self, sel):
self.vf.resetUndo()
self.form.destroy()
## if self.vf.userpref['expandNodeLogString']['value'] == 0:
## self.mergeLPS.nodeLogString = "self.getSelection()"
self.doitWrapper(sel, topCommand=0)
def cancel_cb(self, event=None):
self.form.destroy()
mergeLonePairsCommandGuiDescr = {'widgetType':'Menu','menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Misc',
'menuEntryLabel':'Merge Lone Pairs'}
MergeLonePairsGUICommandGUI = CommandGUI()
MergeLonePairsGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
'Merge Lone Pairs',
cascadeName='Misc')
class MergeLonePairsCommand(MVCommand):
"""This class merges lone-pairs and the sulfur atoms to which they are attached.There are three parts to the process:the charges of lone-pairs, if any, are added to those of the sulfurs the bond between the lone-pair and its sulfur is removed from the sulfur's bonds the lone-pair 'atoms' are deleted
\nPackage:Pmv
\nModule :editCommands
\nClass:MergeLonePairsCommand
\nCommand:mergeLPS
\nSynopsis:\n
None<---mergeLPS(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection\n
NB: the lone pairs are identified by these criteria:
\nthe element field of the lone pair 'atom' is 'Xx' and its name has a 'L'
in the first or second position.
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def __call__(self, nodes, **kw):
"""None<---mergeLPS(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
return apply(self.doitWrapper, (nodes,), kw)
def doit(self, nodes, **kw):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
if nodes[0].__class__!=Atom:
nodes = nodes.findType(Atom)
allAtoms = nodes
returnVal = []
#process nodes by molecule
molecules, atomSets= self.vf.getNodesByMolecule(allAtoms)
allAtoms = AtomSet([])
for i in range(len(molecules)):
mol=molecules[i]
ats=atomSets[i]
lps=ats.get(lambda x:x.element=='Xx'\
and (x.name[0]=='L' or \
x.name[1]=='L'))
if lps is not None and len(lps)!=0:
Sset = AtomSet([])
for LPatom in lps:
b = LPatom.bonds[0]
if b.atom1==LPatom:
Sset.append(b.atom2)
if b in b.atom2.bonds:
b.atom2.bonds.remove(b)
else:
Sset.append(b.atom1)
if b in b.atom1.bonds:
b.atom1.bonds.remove(b)
else:
#there is nothing to do, so just do next molecule
continue
#process each field in lps._charges.keys()
#to get only the ones every lps has:
chList = lps[0]._charges.keys()
for at in lps:
chs = at._charges.keys()
for c in chList:
if c not in chs: chList.remove(c)
if not len(chList):
print 'no consistent chargeSet across sulfurs\ncharge on sulfurs unchanged'
#self.warningMsg('no consistent chargeSet across sulfurs\ncharge on sulfurs unchanged')
for chargeSet in chList:
for lp in lps:
Satom = lp.bonds[0].atom1
if Satom==lp: Satom = lp.bonds[0].atom2
Satom._charges[chargeSet] = Satom.charge + lp.charge
mol.allAtoms = mol.allAtoms - lps
self.vf.allAtoms = self.vf.allAtoms - lps
event = DeleteAtomsEvent(objects=lps)
self.vf.dispatchEvent(event)
for at in lps:
at.parent.remove(at)
del at
returnVal.append(mol)
#return a list of molecules which changed
return returnVal
class ComputeGasteigerGUICommand(MVCommand):
"""Calls computeGasteiger which does work of computing gasteiger partial charges
for each atom and entering each atom's charge in its _charges dictionary.
\nPackage:Pmv
\nModule :editCommands
\nClass:ComputeGasteigerGUICommand
\nCommand:computeGasteigerGC
\nSynopsis:\n
None<---computeGasteigerGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'computeGasteiger'):
self.vf.loadCommand('editCommands', 'computeGasteiger','Pmv',
topCommand=0)
def doit(self, nodes):
self.vf.computeGasteiger(nodes)
ats = nodes.findType(Atom)
sum = round(Numeric.add.reduce(ats.charge),4)
msg = 'Total gasteiger charge added = ' + str(sum)
self.warningMsg(msg)
self.msg = msg
return sum
def __call__(self, nodes, **kw):
"""None<---computeGasteigerGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
if not len(nodes): return
return apply(self.doitWrapper, (nodes,), kw )
def guiCallback(self):
sel=self.vf.getSelection()
if len(sel):
return self.doitWrapper(sel, topCommand=0)
computeGasteigerGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Charges',
'menuEntryLabel':'Compute Gasteiger'}
ComputeGasteigerGUICommandGUI = CommandGUI()
ComputeGasteigerGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
'Compute Gasteiger', cascadeName='Charges')
class ComputeGasteigerCommand(MVCommand):
"""Does work of computing gasteiger partial charges for each atom and entering each atom's charge in its '_charges' dictionary as value for key 'gasteiger' (rounded to 4 decimal places). Calls babel.assignHybridization(mol.allAtoms) for each molecule with atoms in nodes.Sets the current charge (its chargeSet field) of each atom to gasteiger.
\nPackage:Pmv
\nModule :editCommands
\nClass:ComputeGasteigerCommand
\nCommand:computeGasteiger
\nSynopsis:\n
None<---computeGasteiger(nodes, **kw)
\nRequiured Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def setupUndoBefore(self, nodes):
nodes = self.vf.expandNodes(nodes)
allAtoms = nodes.findType(Atom)
chargeAts = AtomSet([])
charges = []
nochargeAts = AtomSet([])
for at in allAtoms:
#if hasattr(at, 'gast_charge'):
if at._charges.has_key('gasteiger'):
chargeAts.append(at)
charges.append(at._charges['gasteiger'])
else:
nochargeAts.append(at)
self.undoMenuString = self.name
if len(chargeAts) and len(nochargeAts):
ustr='"nodes=self.expandNodes('+'\''+chargeAts.full_name()+'\''+');nodes.addCharges(\'gasteiger\','+str(charges)+');nodes=self.expandNodes('+nochargeAts.full_name()+');nodes.delCharges(\'gasteiger\')"'
self.undoCmds = "exec("+ustr+")"
elif len(chargeAts):
ustr = '"nodes=self.expandNodes('+'\''+chargeAts.full_name()+'\''+');nodes.addCharges(\'gasteiger,'+str(charges)+')"'
self.undoCmds = "exec("+ustr+")"
else:
ustr='"nodes=self.expandNodes('+'\''+nochargeAts.full_name()+'\''+');nodes.delCharges(\'gasteiger\')"'
self.undoCmds = "exec("+ustr+")"
def __call__(self, nodes, **kw):
"""None <- computeGasteiger(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return
apply ( self.doitWrapper, (nodes,), kw )
def doit(self, nodes ):
#nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
mols = nodes.top.uniq()
for mol in mols:
babel_typed = filter(lambda x: hasattr(x,'babel_type'), mol.allAtoms)
if len(babel_typed)==len(mol.allAtoms):
continue
babel = AtomHybridization()
babel.assignHybridization(mol.allAtoms)
allAtoms = nodes.findType(Atom)
bonds = allAtoms.bonds[0]
if not len(bonds):
msg='must buildBonds before gasteiger charges can be computed'
self.warningMsg(msg)
return
Gast = Gasteiger()
Gast.compute(allAtoms)
#at this point, allAtoms has field 'gast_charge' with 12 decimal places
gastCharges = []
for c in allAtoms.gast_charge:
gastCharges.append(round(c,4))
allAtoms.addCharges('gasteiger', gastCharges)
del allAtoms.gast_charge
#make gasteiger the current charge
allAtoms.chargeSet = 'gasteiger'
class AddKollmanChargesGUICommand(MVCommand):
"""Kollman united atom charges are added to atoms in peptides by looking up each atom's parent and name in table in Pmv.qkollua. Missing entries are assigned charge 0.0
\nPackage:Pmv
\nModule :editCommands
\nClass:AddKollmanChargesGUICommand
\nCommand:addKollmanChargesGC
\nSynopsis:\n
totalCharge<---addKollmanChargesGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'addKollmanCharges'):
self.vf.loadCommand('editCommands', 'addKollmanCharges','Pmv',
topCommand=0)
def __call__(self, nodes, **kw):
"""totalCharge <- addKollmanChargesGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
kw['topCommand'] = 0
return apply(self.doitWrapper, (nodes,), kw)
def doit(self, nodes,):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
self.vf.addKollmanCharges(nodes)
ats = nodes.findType(Atom)
sum = round(Numeric.add.reduce(ats.charge),4)
msg = 'Total Kollman charge added = ' + str(sum)
self.warningMsg(msg)
self.msg = msg
return sum
def guiCallback(self):
sel = self.vf.getSelection()
if not len(sel):
self.warningMsg("No Molecules Present")
return
## if self.vf.userpref['expandNodeLogString']['value'] == 0:
## self.vf.addKollmanCharges.nodeLogString = "self.getSelection()"
return self.doitWrapper(sel, topCommand=0)
addKollmanChargesGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Charges',
'menuEntryLabel':'Add Kollman Charges'}
AddKollmanChargesGUICommandGUI = CommandGUI()
AddKollmanChargesGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
'Add Kollman Charges ', cascadeName='Charges')
class AddKollmanChargesCommand(MVCommand):
"""Kollman united atom partial charges are added to atoms by looking up each atom's parent's type to get a dictionary of charges for specific atom names (from Pmv.qkollua). Missing entries are assigned charge 0.0. These partial charges are entered in each atom's '_charges' dictionary as value for key 'Kollman'. Sets the current charge (its chargeSet field) of each atom to 'Kollman'.
\nPackage:Pmv
\nModule :editCommands
\nClass:AddKollmanChargesCommand
\nCommand:addKollmanCharges
\nSynopsis:\n
totalCharge<---addKollmanCharges(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\ntotalCharge --- sum of partial charges on nodes.
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
import Pmv.qkollua
self.q = Pmv.qkollua.q
def __call__(self, nodes, **kw):
"""totalCharge<---addKollmanCharges(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
return apply(self.doitWrapper, (nodes,), kw)
def setupUndoBefore(self, nodes):
nodes = self.vf.expandNodes(nodes)
allAtoms = nodes.findType(Atom)
chargeAts = AtomSet([])
charges = []
nochargeAts = AtomSet([])
for at in allAtoms:
#if hasattr(at, 'gast_charge'):
if at._charges.has_key('Kollman'):
chargeAts.append(at)
charges.append(at._charges['Kollman'])
else:
nochargeAts.append(at)
self.undoMenuString = self.name
if len(chargeAts) and len(nochargeAts):
ustr='"nodes=self.expandNodes('+'\''+chargeAts.full_name()+'\''+');nodes.addCharges(\'Kollman\','+str(charges)+');nodes=self.expandNodes('+nochargeAts.full_name()+');nodes.delCharges(\'Kollman\')"'
self.undoCmds = "exec("+ustr+")"
elif len(chargeAts):
ustr = '"nodes=self.expandNodes('+'\''+chargeAts.full_name()+'\''+');nodes.addCharges(\'Kollman\','+str(charges)+')"'
self.undoCmds = "exec("+ustr+")"
else:
ustr='"nodes=self.expandNodes('+'\''+nochargeAts.full_name()+'\''+');nodes.delCharges(\'Kollman\')"'
self.undoCmds = "exec("+ustr+")"
def doit(self, nodes):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
self.vf.fixHNames(nodes, topCommand=0)
allRes = nodes.findType(Residue).uniq()
allAtoms = allRes.atoms
allChains = allRes.parent.uniq()
total = 0.0
for a in allAtoms:
if not self.q.has_key(a.parent.type):
a._charges['Kollman'] = 0.0
else:
dict = self.q[a.parent.type]
if dict.has_key(a.name):
a._charges['Kollman'] = dict[a.name]
total = total + a._charges['Kollman']
else:
a._charges['Kollman'] = 0.0
#fix histidines
hisRes = allRes.get(lambda x:x.name[:3]=='HIS')
if hisRes is not None and len(hisRes)!=0:
for hres in hisRes:
total = self.fixHisRes(hres, total)
#fix cys's
cysRes = allRes.get(lambda x:x.name[:3]=='CYS')
if cysRes is not None and len(cysRes)!=0:
for cres in cysRes:
total = self.fixCysRes(cres, total)
#check for termini:
for ch in allChains:
if ch.residues[0] in allRes:
##fix the charge on Hs
total = self.fixNterminus(ch.residues[0],total)
if ch.residues[-1] in allRes:
self.fixCterminus(ch.residues[-1], total)
#make Kollman the current charge
allAtoms.chargeSet = 'Kollman'
return total
def fixNterminus(self, nres, total):
"""newTotal<-fixNterminu(nres, total)
\nnres is the N-terminal residue
\ntotal is previous charge total on residueSet
\nnewTotal is adjusted total after changes to nres.charges
"""
nresSet = nres.atoms.get('N')
if nresSet is None or len(nresSet)==0:
if self.q.has_key(nres.type):
for at in nres.atoms:
try:
at._charges['Kollman'] = self.q[at.parent.type][at.name]
except:
at._charges['Kollman'] = 0.0
else:
print nres.name, ' not in qkollua; charges set to 0.0'
for at in nres.atoms:
at._charges['Kollman'] = 0.0
return total
Natom = nres.atoms.get('N')[0]
caresSet = nres.atoms.get('CA')
if caresSet is None or len(caresSet)==0:
if self.q.has_key(nres.type):
for at in nres.atoms:
at._charges['Kollman'] = self.q[at.parent.type][at.name]
else:
print nres.name, ' not in qkollua; charges set to 0.0'
for at in nres.atoms:
at._charges['Kollman'] = 0.0
return total
CAatom = nres.atoms.get('CA')
if CAatom is not None and len(CAatom)!=0:
CAatom = nres.atoms.get('CA')[0]
hlist = Natom.findHydrogens()
#5/5:assert len(hlist), 'polar hydrogens missing from n-terminus'
if not len(hlist):
print 'polar hydrogens missing from n-terminus of chain ' + nres.parent.name
#self.warningMsg('polar hydrogens missing from n-terminus')
if nres.type == 'PRO':
#divide .059 additional charge between CA + CD
#FIX THIS what if no CD?
#CDatom = nres.atoms.get('CD')[0]
CDatom = nres.atoms.get('CD')
if CDatom is not None and len(CDatom)!=0:
CDatom = CDatom[0]
CDatom._charges['Kollman'] = CDatom._charges['Kollman'] + .029
else:
print 'WARNING: no CD atom in ', nres.name
Natom._charges['Kollman'] = Natom._charges['Kollman'] + .274
CAatom._charges['Kollman'] = CAatom._charges['Kollman'] + .030
for ha in hlist:
ha._charges['Kollman'] = .333
else:
Natom._charges['Kollman'] = Natom._charges['Kollman'] + .257
CAatom._charges['Kollman'] = CAatom._charges['Kollman'] + .055
for ha in hlist:
ha._charges['Kollman'] = .312
return total + 1
else:
print 'WARNING: no CA atom in ', nres.name
return total
def fixCterminus(self, cres, total):
"""newTotal<-fixCterminu(cres, total)
\ncres is the C-terminal residue
\ntotal is previous charge total on residueSet
\nnewTotal is adjusted total after changes to cres.charges
"""
OXYatomSet = cres.atoms.get('OXT')
if OXYatomSet is not None and len(OXYatomSet)!=0:
OXYatom = OXYatomSet[0]
OXYatom._charges['Kollman'] = -.706
#CAUTION!
CAatom = cres.atoms.get('CA')
if CAatom is not None and len(CAatom)!=0:
CAatom = cres.atoms.get('CA')[0]
CAatom._charges['Kollman'] = CAatom._charges['Kollman'] - .006
#CAUTION!
Catom = cres.atoms.get('C')
if Catom is not None and len(Catom)!=0:
Catom = cres.atoms.get('C')[0]
Catom._charges['Kollman'] = Catom._charges['Kollman'] - .082
Oatom = cres.atoms.get('O')
if Oatom is not None and len(Oatom)!=0:
#CAUTION!
Oatom = cres.atoms.get('O')[0]
Oatom._charges['Kollman'] = Oatom._charges['Kollman'] - .206
return total - 1
else:
#if there is no OXT don't change charges
return total
def fixHisRes(self, his, total):
"""newTotal<-fixHisRes(his, total)
\nhis is a HISTIDINE residue
\ntotal is previous charge total on residueSet
\nnewTotal is adjusted total after changes to his.charges
"""
hisAtomNames = his.atoms.name
#oldcharge = Numeric.sum(his.atoms._charges['Kollman'])
oldcharge = 0
for at in his.atoms:
oldcharge = oldcharge + at._charges['Kollman']
assertStr = his.name + ' is lacking polar hydrogens'
assert 'HD1' or 'HE2' in hisAtomNames, assertStr
#get the appropriate dictionary
if 'HD1' in hisAtomNames and 'HE2' in hisAtomNames:
d = self.q['HIS+']
elif 'HD1' in hisAtomNames:
d = self.q['HISD']
elif 'HE2' in hisAtomNames:
d = self.q['HIS']
else:
msgStr = his.full_name() + ' missing both hydrogens!'
print msgStr
#self.warningMsg(msgStr)
return total
#assign charges
for a in his.atoms:
if d.has_key(a.name):
a._charges['Kollman'] = d[a.name]
else:
a._charges['Kollman'] = 0.0
#correct total
#newcharge = Numeric.sum(his.atoms._charges['Kollman'])
newcharge = 0
for at in his.atoms:
newcharge = newcharge + at._charges['Kollman']
total = total - oldcharge + newcharge
return total
def fixCysRes(self, cys, total):
cysAtomNames = cys.atoms.name
#oldcharge = Numeric.sum(cys.atoms._charges['Kollman'])
oldcharge = 0
for at in cys.atoms:
oldcharge = oldcharge + at._charges['Kollman']
#get the appropriate dictionary
if 'HG' in cysAtomNames:
d = self.q['CYSH']
else:
#cystine
d = self.q['CYS']
#assign charges
for a in cys.atoms:
if d.has_key(a.name):
a._charges['Kollman'] = d[a.name]
else:
a._charges['Kollman'] = 0.0
#correct total
#newcharge = Numeric.sum(cys.atoms._charges['Kollman'])
newcharge = 0
for at in cys.atoms:
newcharge = newcharge + at._charges['Kollman']
total = total - oldcharge + newcharge
return total
class AverageChargeErrorCommand(MVCommand):
"""Adjusts the charge on each atom in residue with non-integral overall charge so that the sum of the charge on all the atoms in the residue is an integer. Determines if initial sum is closer to the ceiling or the floor and then adds or subtracts the difference from this nearer value divided by the number of atoms to each atom. The new chargeSet is called 'adjustedCharges'.
\nPackage:Pmv
\nModule :editCommands
\nClass:AverageChargeErrorCommand
\nCommand:averageChargeError
\nSynopsis:\n
None<---averageChargeError(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def guiCallback(self):
sel = self.vf.getSelection()
if len(sel):
self.doitWrapper(sel, topCommand=0)
else:
self.warningMsg('No Molecules present!')
def __call__(self, nodes, **kw):
"""None<---averageChargeError(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
kw['topCommand'] = 0
nodes = self.vf.expandNodes(nodes)
if len(nodes):
apply(self.doitWrapper,(nodes,), kw)
else:
return 'ERROR'
def doit(self, nodes):
totalCharge, resSet = self.vf.checkResCharges(nodes)
if not len(resSet):
self.warningMsg('no residues with non-integral charges found')
return 'ERROR'
if totalCharge==9999.9999:
self.warningMsg('ERROR in checkResCharges')
return 'ERROR'
for res in resSet:
self.averageCharge(res)
tops = resSet.top.uniq()
for t in tops:
okAts = t.allAtoms.get(lambda x: not x._charges.has_key('adjustedCharge'))
if okAts is not None and len(okAts)!=0:
okAts.addCharges('adjustedCharges', okAts.charge)
t.allAtoms.setCharges('adjustedCharges')
def averageCharge(self, res):
rats = res.atoms
sum = Numeric.sum(Numeric.array(rats.charge))
numRats = len(rats)
fl_sum = math.floor(sum)
ceil_sum = math.ceil(sum)
errF = sum - fl_sum
errC = ceil_sum - sum
absF =math.fabs(errF)
absC =math.fabs(errC)
newCharges = []
#make which ever is the smaller adjustment
if absC<absF:
delta = round(errC/numRats, 4)
newCharges = []
for a in rats:
newCharges.append(a.charge + delta)
else:
delta = round(errF/numRats, 4)
newCharges = []
for a in rats:
newCharges.append(a.charge - delta)
#add these newCharges as a chargeSet
#FIX THIS@@!!
#NB THIS ONLY ADDS charge to ones with problems
rats.addCharges('adjustedCharges', newCharges)
rats.setCharges('adjustedCharges')
chs = Numeric.sum(Numeric.array(rats.charge))
#print 'chs=', chs,
err = round(chs, 0) - chs
res.err = round(err, 4)
#class SetTerminusChargeGUICommand(MVCommand):
# """Allows user to set total charge on N terminus
# \nPackage:Pmv
# \nModule :editCommands
# \nClass:SetTerminusChargeGUICommand
# \nCommand:setTerminusChargeGC
# \nSynopsis:\n
# None<---setTerminusChargeGC(nodes, **kw)
# \nRequired Arguments:\n
# nodes --- TreeNodeSet holding the current selection
# """
#
# def __init__(self, func=None):
# MVCommand.__init__(self, func)
# self.flag = self.flag | self.objArgOnly
# def onAddCmdToViewer(self):
# if not self.vf.commands.has_key('labelByProperty'):
# self.vf.loadCommand('labelCommands', 'labelByProperty','Pmv',
# topCommand=0)
# if not self.vf.commands.has_key('labelByExpression'):
# self.vf.loadCommand('labelCommands', 'labelByExpression','Pmv',
# topCommand=0)
# if not hasattr(self.vf, 'checkResCharges'):
# self.vf.loadCommand('editCommands', 'checkResCharges','Pmv',
# topCommand=0)
#
# def guiCallback(self):
# sel = self.vf.getSelection()
# if len(sel):
# self.doitWrapper(sel, topCommand=0)
# else:
# self.warningMsg('No Molecules present!')
# def __call__(self, nodes, netcharge=1.0, **kw):
# """None<---setTerminusChargeGC(nodes, **kw)
# \nnodes --- TreeNodeSet holding the current selection"""
# if type(nodes) is types.StringType:
# self.nodeLogString = "'"+nodes+"'"
# kw['topCommand'] = 0
# nodes = self.vf.expandNodes(nodes)
# if len(nodes):
# apply(self.doitWrapper,(nodes, netcharge), kw)
# else:
# return 'ERROR'
# def doit(self, nodes, netcharge):
# if totalCharge==9999.9999:
# self.warningMsg('ERROR in checkResCharges')
# return 'ERROR'
# resNames = []
# if len(resSet):
# resSet.sort()
# else:
# self.warningMsg('no residues with non-integral charges found')
# return 'ERROR'
# for item in resSet:
# resNames.append((item.full_name(), None))
# #FIX THIS: have to change contents of listbox + labels
# #if the molecule has changed....
# ifd = self.ifd=InputFormDescr(title='Check Residue Charge Results:')
# ifd.append({'name': 'numResErrsLabel',
# 'widgetType': Tkinter.Label,
# 'wcfg':{'text': str(len(resSet)) + ' Residues with non-integral charge:\n(double click to edit charges on a residue\nyellow number is amt to add\nfor closest integral charge)'},
# 'gridcfg':{'sticky': Tkinter.W+Tkinter.E}})
# ifd.append({'name': 'resLC',
# 'widgetType':ListChooser,
# 'wcfg':{
# 'mode': 'single',
# 'entries': resNames,
# 'title': '',
# 'command': CallBackFunction(self.showErrResidue, resSet),
# 'lbwcfg':{'height':5,
# 'selectforeground': 'red',
# 'exportselection': 0,
# 'width': 30}},
# 'gridcfg':{'sticky':'news','row':2,'column':0} })
# ifd.append({'name': 'chargeLabel',
# 'widgetType':Tkinter.Label,
# 'wcfg':{'text':'Net Charge on ResidueSet: ' + str(totalCharge)},
# 'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
# ifd.append({'name':'averBut',
# 'widgetType':Tkinter.Button,
# 'wcfg': { 'text':'Spread Charge Deficit\nover all atoms in residue',
# 'command': CallBackFunction(self.averageCharge, resSet)},
# 'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
# #ifd.append({'name':'showBut',
# #'widgetType':Tkinter.Button,
# #'wcfg': { 'text':'Save Non-Integral Charge Residues As Set',
# #'command': CallBackFunction(self.saveErrResidues, resSet)},
# #'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
# ifd.append({'widgetType':Tkinter.Button,
# 'wcfg':{'bd':6, 'text':'Dismiss',
# 'command': CallBackFunction(self.Dismiss_cb, resSet)},
# 'gridcfg':{'sticky':'ew', 'columnspan':4}})
# self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
# self.form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
# eD = self.ifd.entryByName
# eD['resLC']['widget'].lb.bind('<Double-Button-1>', \
# CallBackFunction(self.editResCharges, resSet), add='+')
# self.totalChLab = eD['chargeLabel']['widget']
# #else:
# #self.form.deiconify()
# #self.form.lift()
# ##vals = self.vf.getUserInput(ifd, modal=0, blocking=1,
# ## scrolledFrame=1, width=300, height=220)
# def Dismiss_cb(self, resSet, event=None):
# self.form.destroy()
# if len(resSet):
# self.vf.setIcomLevel(Residue, topCommand=0)
# self.vf.labelByProperty(resSet, log=0, negate=1)
# self.vf.setIcomLevel(Atom, topCommand=0)
# self.vf.labelByExpression(resSet.atoms, lambdaFunc=1, \
# function='lambda x: 2', log=0, negate=1)
# self.vf.GUI.VIEWER.Redraw()
#
# def updateTotalCharge(self, resSet, event=None):
# #make sure form still exists before trying to do update
# if not self.form.f.winfo_exists():
# return
# totalCharge = 0
# tops = resSet.top.uniq()
# for top in tops:
# totalCharge = totalCharge + Numeric.sum(top.allAtoms.charge)
# totalCharge = round(totalCharge, 4)
# self.totalChLab.config({'text':'New Net Charge on ResidueSet: ' + str(totalCharge)})
#
# def averageCharge(self, resSet, event=None):
# self.vf.averageChargeError(resSet)
# #print 'averaged charge error'
# self.vf.setIcomLevel(Residue, topCommand=0)
# self.vf.labelByProperty(resSet, properties=("err",), \
# textcolor="yellow", log=0, font="arial1.glf")
# self.vf.setIcomLevel(Atom, topCommand=0)
# self.vf.labelByExpression(resSet.atoms, lambdaFunc=1, \
# function='lambda x:str(x.charge)',log=0,font="arial1.glf")
# self.updateTotalCharge(resSet)
# ##want charge on the whole molecule
# #totalCharge = 0
# #tops = resSet.top.uniq()
# #for top in tops:
# #totalCharge = totalCharge + Numeric.sum(top.allAtoms.charge)
# #self.totalChLab.config({'text':'New Net Charge on ResidueSet: ' + str(totalCharge)})
#
# def editResCharges(self, resSet, event=None):
# lb = self.ifd.entryByName['resLC']['widget'].lb
# if lb.curselection() == (): return
# resName = lb.get(lb.curselection())
# resNode = self.vf.Mols.NodesFromName(resName)[0]
# #need to open a widget here to facilitate changing charges
# self.vf.editAtomChargeGC.setUp(resNode)
# self.vf.setICOM(self.vf.editAtomChargeGC, topCommand=0)
# self.updateTotalCharge(resSet)
# def showErrResidue(self, resSet, event=None):
# lb = self.ifd.entryByName['resLC']['widget'].lb
# if lb.curselection() == (): return
# resName = lb.get(lb.curselection())
# resNode = self.vf.Mols.NodesFromName(resName)[0]
# oldSel = self.vf.getSelection()
# self.vf.clearSelection(topCommand=0)
# self.vf.setIcomLevel(Residue, topCommand=0)
# self.vf.setICOM(self.vf.select, modifier=None, topCommand=0)
# self.vf.labelByProperty(ResidueSet([resNode]), properties=("err",), textcolor="yellow", log=0, font="arial1.glf")
# self.vf.setIcomLevel(Atom, topCommand=0)
# self.vf.labelByExpression(resNode.atoms, lambdaFunc=1, function='lambda x:str(x.charge)', log=0, font="arial1.glf")
# self.updateTotalCharge(resSet)
# def saveErrResidues(self, resSet, event=None):
# nameStr = resSet.full_name()
# self.vf.saveSet(resSet, nameStr, topCommand=0)
#checkChargesGUICommandGuiDescr = {'widgetType':'Menu',
# 'menuBarName':'menuRoot',
# 'menuButtonName':'Edit',
# 'menuCascadeName':'Charges',
# 'menuEntryLabel':'Check Charges'}
#CheckChargesGUICommandGUI=CommandGUI()
#CheckChargesGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
# 'Check Totals on Residues', cascadeName='Charges')
class CheckChargesGUICommand(MVCommand):
"""Allows user to call checkResCharges on each residue in selection
\nPackage:Pmv
\nModule :editCommands
\nClass:CheckChargesGUICommand
\nCommand:checkChargesGC
\nSynopsis:\n
None<---checkChargesGC(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('labelByProperty'):
self.vf.loadCommand('labelCommands', 'labelByProperty','Pmv',
topCommand=0)
if not self.vf.commands.has_key('labelByExpression'):
self.vf.loadCommand('labelCommands', 'labelByExpression','Pmv',
topCommand=0)
if not hasattr(self.vf, 'checkResCharges'):
self.vf.loadCommand('editCommands', 'checkResCharges','Pmv',
topCommand=0)
def guiCallback(self):
sel = self.vf.getSelection()
if len(sel):
self.doitWrapper(sel, topCommand=0)
else:
self.warningMsg('No Molecules present!')
def __call__(self, nodes, **kw):
"""None<---checkChargesGC(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
kw['topCommand'] = 0
nodes = self.vf.expandNodes(nodes)
if len(nodes):
apply(self.doitWrapper,(nodes,), kw)
else:
return 'ERROR'
def doit(self, nodes):
totalCharge, resSet = self.vf.checkResCharges(nodes)
if totalCharge==9999.9999:
self.warningMsg('ERROR in checkResCharges')
return 'ERROR'
resNames = []
if len(resSet):
resSet.sort()
else:
self.warningMsg('no residues with non-integral charges found')
return 'ERROR'
for item in resSet:
resNames.append((item.full_name(), None))
#FIX THIS: have to change contents of listbox + labels
#if the molecule has changed....
ifd = self.ifd=InputFormDescr(title='Check Residue Charge Results:')
ifd.append({'name': 'numResErrsLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': str(len(resSet)) + ' Residues with non-integral charge:\n(double click to edit charges on a residue\nyellow number is amt to add\nfor closest integral charge)'},
'gridcfg':{'sticky': Tkinter.W+Tkinter.E}})
ifd.append({'name': 'resLC',
'widgetType':ListChooser,
'wcfg':{
'mode': 'single',
'entries': resNames,
'title': '',
'command': CallBackFunction(self.showErrResidue, resSet),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30}},
'gridcfg':{'sticky':'news','row':2,'column':0} })
ifd.append({'name': 'chargeLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Net Charge on ResidueSet: ' + str(totalCharge)},
'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
ifd.append({'name':'averBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Spread Charge Deficit\nover all atoms in residue',
'command': CallBackFunction(self.averageCharge, resSet)},
'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
#ifd.append({'name':'showBut',
#'widgetType':Tkinter.Button,
#'wcfg': { 'text':'Save Non-Integral Charge Residues As Set',
#'command': CallBackFunction(self.saveErrResidues, resSet)},
#'gridcfg':{'sticky':Tkinter.W+Tkinter.E}})
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'bd':6, 'text':'Dismiss',
'command': CallBackFunction(self.Dismiss_cb, resSet)},
'gridcfg':{'sticky':'ew', 'columnspan':4}})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
eD = self.ifd.entryByName
eD['resLC']['widget'].lb.bind('<Double-Button-1>', \
CallBackFunction(self.editResCharges, resSet), add='+')
self.totalChLab = eD['chargeLabel']['widget']
#else:
#self.form.deiconify()
#self.form.lift()
##vals = self.vf.getUserInput(ifd, modal=0, blocking=1,
## scrolledFrame=1, width=300, height=220)
def Dismiss_cb(self, resSet, event=None):
self.form.destroy()
if len(resSet):
self.vf.setIcomLevel(Residue, topCommand=0)
self.vf.labelByProperty(resSet, log=0, negate=1)
self.vf.setIcomLevel(Atom, topCommand=0)
self.vf.labelByExpression(resSet.atoms, lambdaFunc=1, \
function='lambda x: 2', log=0, negate=1)
self.vf.GUI.VIEWER.Redraw()
def updateTotalCharge(self, resSet, event=None):
#make sure form still exists before trying to do update
if not self.form.f.winfo_exists():
return
totalCharge = 0
tops = resSet.top.uniq()
for top in tops:
totalCharge = totalCharge + Numeric.sum(top.allAtoms.charge)
totalCharge = round(totalCharge, 4)
self.totalChLab.config({'text':'New Net Charge on ResidueSet: ' + str(totalCharge)})
def averageCharge(self, resSet, event=None):
self.vf.averageChargeError(resSet)
#print 'averaged charge error'
self.vf.setIcomLevel(Residue, topCommand=0)
self.vf.labelByProperty(resSet, properties=("err",), \
textcolor="yellow", log=0, font="arial1.glf")
self.vf.setIcomLevel(Atom, topCommand=0)
self.vf.labelByExpression(resSet.atoms, lambdaFunc=1, \
function='lambda x:str(x.charge)',log=0,font="arial1.glf")
self.updateTotalCharge(resSet)
##want charge on the whole molecule
#totalCharge = 0
#tops = resSet.top.uniq()
#for top in tops:
#totalCharge = totalCharge + Numeric.sum(top.allAtoms.charge)
#self.totalChLab.config({'text':'New Net Charge on ResidueSet: ' + str(totalCharge)})
def editResCharges(self, resSet, event=None):
lb = self.ifd.entryByName['resLC']['widget'].lb
if lb.curselection() == (): return
resName = lb.get(lb.curselection())
resNode = self.vf.Mols.NodesFromName(resName)[0]
#need to open a widget here to facilitate changing charges
self.vf.editAtomChargeGC.setUp(resNode)
self.vf.setICOM(self.vf.editAtomChargeGC, modifier="Shift_L", topCommand=0)
self.updateTotalCharge(resSet)
def showErrResidue(self, resSet, event=None):
lb = self.ifd.entryByName['resLC']['widget'].lb
if lb.curselection() == (): return
resName = lb.get(lb.curselection())
resNode = self.vf.Mols.NodesFromName(resName)[0]
oldSel = self.vf.getSelection()
self.vf.clearSelection(topCommand=0)
self.vf.setIcomLevel(Residue, topCommand=0)
self.vf.setICOM(self.vf.select, modifier="Shift_L", topCommand=0)
self.vf.labelByProperty(ResidueSet([resNode]), properties=("err",), textcolor="yellow", log=0, font="arial1.glf")
self.vf.setIcomLevel(Atom, topCommand=0)
self.vf.labelByExpression(resNode.atoms, lambdaFunc=1, function='lambda x:str(x.charge)', log=0, font="arial1.glf")
self.updateTotalCharge(resSet)
def saveErrResidues(self, resSet, event=None):
nameStr = resSet.full_name()
self.vf.saveSet(resSet, nameStr, topCommand=0)
checkChargesGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Charges',
'menuEntryLabel':'Check Charges'}
CheckChargesGUICommandGUI=CommandGUI()
CheckChargesGUICommandGUI.addMenuCommand('menuRoot', 'Edit',
'Check Totals on Residues', cascadeName='Charges')
class SetChargeCommand(MVCommand):
"""allows user to set string used to index into _charges dictionary
\nPackage:Pmv
\nModule :editCommands
\nClass:SetChargeCommand
\nCommand:setChargeSet
\nSynopsis:\n
None<---setChargeSet(nodes, key, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\nkey --- what charges (keyword of the _charges dictionary).
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
def onAddCmdToViewer(self):
if self.vf.hasGui:
self.key = Tkinter.StringVar()
def __call__(self, nodes, key, **kw):
"""None <--- setChargeSet(nodes, key, **kw)
\nnodes --- TreeNodeSet holding the current selection
\nkey --- what charges (keyword of the _charges dictionary).
"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
#is this a good idea?
#assert key in nodes._charges.keys()
kw['redraw'] = 0
if len(nodes):
nodes = nodes.findType(Atom)
#check that the key is valid
nodes_with_key = filter(lambda x: key in x._charges.keys(), nodes)
if len(nodes_with_key)!=len(nodes):
raise KeyError
return apply(self.doitWrapper,(nodes, key), kw)
else: return 'ERROR'
def doit(self, nodes, key):
nodes.chargeSet = key
#should be nodes.setCharges(key)
def guiCallback(self):
z = self.vf.getSelection()
if not len(z):
return
nodes = z.findType(Atom)
# only displays the charges keys f
keys = nodes._charges.keys()
if not len(keys):
print 'no charges to choose from'
return
self.key.set(keys[0])
if len(keys)>1:
currentCharge = self.key.get()
ifd = self.ifd = InputFormDescr(title = 'Select charge')
ifd.append({'name': 'chargeList',
'listtext': keys,
'widgetType': Tkinter.Radiobutton,
'groupedBy': 10,
'defaultValue': currentCharge,
'variable': self.key,
'gridcfg': {'sticky': Tkinter.W}})
val = self.vf.getUserInput(ifd)
if val is None or val=={} or not len(val):
return
else:
print 'using only available charge: ', keys[0]
kw = {}
kw['redraw'] = 0
## if self.vf.userpref['expandNodeLogString']['value'] == 0:
## self.nodeLogString = "self.getSelection()"
apply(self.doitWrapper, (nodes, self.key.get()), kw)
setChargeGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Charges',
'menuEntryLabel':'Set Charge Field'}
SetChargeCommandGUI=CommandGUI()
SetChargeCommandGUI.addMenuCommand('menuRoot', 'Edit', 'Set Charge Field',
cascadeName='Charges')
class CheckResidueChargesCommand(MVCommand):
"""Allows user to check charges on each residue + whole molecule
\nPackage:Pmv
\nModule :editCommands
\nClass:CheckResidueChargesCommand
\nCommand:checkResCharges
\nSynopsis:\n
None <--- checkResCharges(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def __call__(self, nodes, **kw):
"""None <- checkResCharges(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if len(nodes):
#if there are nodes, there have to be Residues
resSet = nodes.findType(Residue).uniq()
return apply(self.doitWrapper,(resSet,), kw)
else:
kw['log'] = 0
self.warningMsg('no nodes specified')
return 9999.9999, ResidueSet([])
def doit(self, resSet):
totalCharge = 0.0
errResSet = ResidueSet([])
for item in resSet:
chs = Numeric.sum(item.atoms.charge)
fl_sum = math.floor(chs)
ceil_sum = math.ceil(chs)
errF = chs - fl_sum
errC = ceil_sum - chs
absF = math.fabs(errF)
absC = math.fabs(errC)
#make which ever is the smaller adjustment
if absC<absF:
err = round(errC, 4)
else:
err = round(errF, 4)
#print 'labelling with err = ', err
item.err = err
totalCharge = totalCharge + chs
#err = round(chs, 0) - chs
#item.err = err
if err > .005 or err < -0.005:
errResSet.append(item)
return totalCharge, errResSet
class AssignAtomsRadiiCommand(MVCommand):
"""This commands adds radii to all the atoms loaded so far in the application. Only default radii for now
\nPackage:Pmv
\nModule :editCommands
\nClass:AssignAtomsRadiiCommand
\nCommand:assignAtomsRadii
\nSynopsis:\n
None <- mv.assignAtomsRadii(nodes, united=1, overwrite=1,**kw)\n
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
\nunited --- (default=1) flag to specify whether or not to consider
hydrogen atoms. When hydrogen are there the atom radii
is smaller.
overwrite ---(default=1) flag to specify whether or not to overwrite
existing radii information.\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def doit(self, nodes, united=True, overwrite=False):
#nodes = self.vf.expandNodes(nodes)
if not nodes: return
molecules = nodes.top.uniq()
for mol in molecules:
# Reassign the radii if overwrite is True
if overwrite is True:
mol.unitedRadii = united
mol.defaultRadii(united=united, overwrite=overwrite)
# Reassign the radii if different.
elif mol.unitedRadii != united:
mol.unitedRadii = united
mol.defaultRadii(united=united, overwrite=overwrite)
def onAddObjectToViewer(self, obj):
obj.unitedRadii = None
def __call__(self, nodes, united=True, overwrite=False, **kw):
""" None <- mv.assignAtomsRadii(nodes, united=True, overwrite=False,**kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
united --- (default=True) Boolean flag to specify whether or not
to consider hydrogen atoms. When hydrogen are there the
atom radii is smaller.\n
overwrite --- (default=True) Boolean flag to specify whether or not to overwrite
existing radii information.\n
"""
if type(nodes) is types.StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return
kw['united'] = united
kw['overwrite'] = overwrite
apply(self.doitWrapper, (nodes, ), kw)
def guiCallback(self):
nodes = self.vf.getSelection()
if not nodes: return
idf = InputFormDescr(title="Assign Atoms Radii")
idf.append({'widgetType':Tkinter.Checkbutton,
'name':'united',
'tooltip': "When united is set to 1 it means that the radii should be calculated without hydrogen atoms.",
'defaultValue':1,
'wcfg':{'text':'United Radii',
'variable':Tkinter.IntVar()},
'gridcfg':{'sticky':'w'}})
idf.append({'widgetType':Tkinter.Checkbutton,
'name':'overwrite',
'tooltip': "When overwrite is off the existing radii information won't be overwritten.",
'defaultValue':0,
'wcfg':{'text':'Overwrite Radii','variable':Tkinter.IntVar()},
'gridcfg':{'sticky':'w'}})
val = self.vf.getUserInput(idf)
if val is None or val == {}: return
apply(self.doitWrapper, (self.vf.getSelection(),), val)
assignAtomsRadiiGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Edit',
'menuCascadeName':'Atoms',
'menuEntryLabel':'Assign Radii'}
AssignAtomsRadiiCommandGUI = CommandGUI()
AssignAtomsRadiiCommandGUI.addMenuCommand('menuRoot', 'Edit',
'Assign Radii', cascadeName = 'Atoms')
commandList=[
{'name':'editAtomTypeGC','cmd':EditAtomTypeGUICommand(),
'gui': EditAtomTypeGUICommandGUI},
{'name':'editAtomChargeGC','cmd':EditAtomChargeGUICommand(),
'gui': None},
#{'name':'editAtomChargeGC','cmd':EditAtomChargeGUICommand(),
# 'gui': EditAtomChargeGUICommandGUI},
{'name':'typeAtoms','cmd':TypeAtomsCommand(),
'gui': TypeAtomsCommandGUI},
{'name':'deleteWater','cmd':DeleteWaterCommand(),
'gui': DeleteWaterCommandGUI},
{'name':'editAtomType','cmd':EditAtomTypeCommand(), 'gui':None},
{'name':'assignAtomsRadii', 'cmd':AssignAtomsRadiiCommand(),
'gui': AssignAtomsRadiiCommandGUI},
{'name':'typeBonds','cmd':TypeBondsCommand(),
'gui': TypeBondsCommandGUI},
{'name':'addKollmanChargesGC','cmd':AddKollmanChargesGUICommand(),
'gui': AddKollmanChargesGUICommandGUI},
{'name':'addKollmanCharges','cmd':AddKollmanChargesCommand(),'gui': None},
{'name':'computeGasteigerGC','cmd':ComputeGasteigerGUICommand(),
'gui': ComputeGasteigerGUICommandGUI},
{'name':'computeGasteiger','cmd':ComputeGasteigerCommand(), 'gui': None},
{'name':'checkChargesGC','cmd':CheckChargesGUICommand(),
'gui': CheckChargesGUICommandGUI},
{'name':'checkResCharges','cmd':CheckResidueChargesCommand(),'gui': None},
{'name':'averageChargeError','cmd':AverageChargeErrorCommand(),'gui': None},
{'name':'setChargeSet','cmd':SetChargeCommand(),
'gui': SetChargeCommandGUI},
{'name':'add_hGC','cmd':AddHydrogensGUICommand(),
'gui': AddHydrogensGUICommandGUI},
{'name':'add_h','cmd':AddHydrogensCommand(), 'gui': None},
{'name':'mergeNPHSGC','cmd':MergeNPHsGUICommand(),
'gui': MergeNPHsGUICommandGUI},
{'name':'mergeNPHS','cmd':MergeNPHsCommand(), 'gui': None},
{'name':'fixHNamesGC','cmd':FixHydrogenAtomNamesGUICommand(),
'gui': FixHydrogenAtomNamesGUICommandGUI},
{'name':'fixHNames','cmd':FixHydrogenAtomNamesCommand(), 'gui': None},
#{'name':'mergeFields','cmd':MergeFieldsCommand(),
#'gui': MergeFieldsCommandGUI},
#{'name':'mergeSets','cmd':MergeSetsCommand(),
#'gui': MergeSetsCommandGUI},
{'name':'mergeLPSGC','cmd':MergeLonePairsGUICommand(),
'gui': MergeLonePairsGUICommandGUI},
{'name':'mergeLPS','cmd':MergeLonePairsCommand(), 'gui': None},
{'name':'splitNodesGC','cmd':SplitNodesGUICommand(),
'gui': SplitNodesGUICommandGUI},
{'name':'splitNodes','cmd':SplitNodesCommand(), 'gui': None},
]
def initModule(viewer):
for dict in commandList:
viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])
```
#### File: MGLToolsPckgs/Pmv/fileCommandsGUI.py
```python
from ViewerFramework.VFCommand import CommandGUI, CommandProxy
class PDBWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import PDBWriter
command = PDBWriter()
loaded = self.vf.addCommand(command, 'writePDB', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
PDBWriterGUI = CommandGUI()
PDBWriterGUI.addMenuCommand('menuRoot', 'File', 'Write PDB',
cascadeName='Save', index=3, separatorAbove=1)
class PDBQWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import PDBQWriter
command = PDBQWriter()
loaded = self.vf.addCommand(command, 'writePDBQ', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
PDBQWriterGUI = CommandGUI()
PDBQWriterGUI.addMenuCommand('menuRoot', 'File', 'Write PDBQ',
cascadeName='Save', index=4)
class PDBQSWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import PDBQSWriter
command = PDBQSWriter()
loaded = self.vf.addCommand(command, 'writePDBQ', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
PDBQSWriterGUI = CommandGUI()
PDBQSWriterGUI.addMenuCommand('menuRoot', 'File', 'Write PDBQS',
cascadeName='Save', index=5)
class PDBQTWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import PDBQTWriter
command = PDBQTWriter()
loaded = self.vf.addCommand(command, 'writePDBQT', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
PDBQTWriterGUI = CommandGUI()
PDBQTWriterGUI.addMenuCommand('menuRoot', 'File', 'Write PDBQT',
cascadeName='Save', index=6)
class SaveMMCIFProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import SaveMMCIF
command = SaveMMCIF()
loaded = self.vf.addCommand(command, 'SaveMMCIF', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
SaveMMCIFGUI = CommandGUI()
SaveMMCIFGUI.addMenuCommand('menuRoot', 'File', 'Write MMCIF',
cascadeName='Save', index=7)
class PQRWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import PQRWriter
command = PQRWriter()
loaded = self.vf.addCommand(command, 'writePQR', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
PQRWriterGUI = CommandGUI()
PQRWriterGUI.addMenuCommand('menuRoot', 'File', 'Write PQR',
cascadeName='Save', index=8)
class MoleculeReaderProxy(CommandProxy):
def __init__(self, vf, gui):
from Pmv.fileCommands import MoleculeReader
command = MoleculeReader()
vf.addCommand(command, 'readMolecule', gui)
CommandProxy.__init__(self, vf, gui)
MoleculeReaderGUI = CommandGUI()
MoleculeReaderGUI.addMenuCommand('menuRoot', 'File', 'Read Molecule', index = 0)
class fetchCommandProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import fetch
command = fetch()
loaded = self.vf.addCommand(command, 'fetch', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
fetchGUI = CommandGUI()
fetchGUI.addMenuCommand('menuRoot', 'File', 'Fetch From Web', index=0,
cascadeName='Import')
class VRML2WriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import VRML2Writer
command = VRML2Writer()
loaded = self.vf.addCommand(command, 'writeVRML2', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
VRML2WriterGUI = CommandGUI()
VRML2WriterGUI.addMenuCommand('menuRoot', 'File', 'Write VRML 2.0',
cascadeName='Save', cascadeAfter='Read Molecule',
separatorAboveCascade=1)
class STLWriterProxy(CommandProxy):
def guiCallback(self, **kw):
if self.command:
self.command.guiCallback(**kw)
else:
from Pmv.fileCommands import STLWriter
command = STLWriter()
loaded = self.vf.addCommand(command, 'writeSTL', self.gui)
if loaded:
command = loaded
self.command = command
self.command.guiCallback(**kw)
STLWriterGUI = CommandGUI()
STLWriterGUI.addMenuCommand('menuRoot', 'File', 'Write STL',
cascadeName='Save', index=11,separatorBelow=1)
class ReadSourceMoleculeProxy(CommandProxy):
def __init__(self, vf, gui):
from Pmv.fileCommands import ReadSourceMolecule
command =ReadSourceMolecule()
vf.addCommand(command, 'readSourceMolecule', gui)
CommandProxy.__init__(self, vf, gui)
ReadSourceMoleculeGUI = CommandGUI()
ReadSourceMoleculeGUI.addToolBar('Read Molecule or Python Script', icon1='fileopen.gif',
type='ToolBarButton', balloonhelp='Read Molecule or Python Script', index=0)
def initGUI(viewer):
viewer.addCommandProxy(fetchCommandProxy(viewer, fetchGUI))
viewer.addCommandProxy(PDBWriterProxy(viewer, PDBWriterGUI))
viewer.addCommandProxy(PDBQWriterProxy(viewer, PDBQWriterGUI))
viewer.addCommandProxy(PDBQTWriterProxy(viewer, PDBQTWriterGUI))
viewer.addCommandProxy(PDBQSWriterProxy(viewer, PDBQSWriterGUI))
viewer.addCommandProxy(SaveMMCIFProxy(viewer, SaveMMCIFGUI))
viewer.addCommandProxy(PQRWriterProxy(viewer, PQRWriterGUI))
viewer.addCommandProxy(MoleculeReaderProxy(viewer, MoleculeReaderGUI))
viewer.addCommandProxy(VRML2WriterProxy(viewer, VRML2WriterGUI))
viewer.addCommandProxy(STLWriterProxy(viewer, STLWriterGUI))
viewer.addCommandProxy(ReadSourceMoleculeProxy(viewer, ReadSourceMoleculeGUI))
```
#### File: MGLToolsPckgs/Pmv/fileCommands.py
```python
from ViewerFramework.VFCommand import CommandGUI
from Pmv.mvCommand import MVCommand
from MolKit.protein import Protein
from MolKit.pdbParser import PdbParser, PdbqParser, PdbqsParser, PdbqtParser, PQRParser, F2DParser
from MolKit.pdbWriter import PdbWriter, PdbqWriter, PdbqsWriter, PdbqtWriter
from MolKit.pqrWriter import PqrWriter
from MolKit.groParser import groParser
from MolKit.molecule import Atom, AtomSet, MoleculeSet
from MolKit.mol2Parser import Mol2Parser
from MolKit.mmcifParser import MMCIFParser
from MolKit.mmcifWriter import MMCIFWriter
import types, os, sys, string, glob
import numpy
import numpy.oldnumeric as Numeric
import Tkinter, Pmw
## from ViewerFramework.gui import InputFormDescr
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import SaveButton
from MolKit.tree import TreeNode, TreeNodeSet
from MolKit.molecule import Atom
from tkMessageBox import *
from Pmv.moleculeViewer import EditAtomsEvent
pdbDescr = """
By default the PDB writer will create the following records:
- ATOM and TER records
- CONECT records when bond information is available (bonds have been built by distance,
the user defined bond information or the original file contained connectivity information.
- HELIX, SHEET, TURN when secondary structure information is available (either from the original
file or computed).
Other records can be created from the molecular data structure such as :
- HYDBND when hydrogne bonds information is available.
The information below can be found at http://www.rcsb.org/pdb/docs/format/pdbguide2.2/guide2.2_frame.html
The PDBQ format is similar to the PDB format but has charges information in the field adjacent to the
temperature factor.
The PDBQS format is the PDBQS format with some solvation information at the end of the ATOM/HETATM records.
The PDBQT format is the PDBQ format with autodock element information at the end of the ATOM/HETATM records.
1- TITLE SECTION
HEADER
----------------------------------
The HEADER record uniquely identifies a PDB entry through the idCode field.
This record also provides a classification for the entry. Finally, it contains
the date the coordinates were deposited at the PDB.
OBSLTE
----------------------------------
OBSLTE appears in entries which have been withdrawn from distribution.
This record acts as a flag in an entry which has been withdrawn from the PDB's
full release. It indicates which, if any, new entries have replaced the withdrawn entry.
The format allows for the case of multiple new entries replacing one existing entry.
TITLE
----------------------------------
The TITLE record contains a title for the experiment or analysis that is represented
in the entry. It should identify an entry in the PDB in the same way that a title
identifies a paper.
CAVEAT
----------------------------------
CAVEAT warns of severe errors in an entry. Use caution when using an entry containing
this record.
COMPND
----------------------------------
The COMPND record describes the macromolecular contents of an entry. Each macromolecule
found in the entry is described by a set of token: value pairs, and is referred to as a
COMPND record component. Since the concept of a molecule is difficult to specify exactly,
PDB staff may exercise editorial judgment in consultation with depositors in assigning
these names.
For each macromolecular component, the molecule name, synonyms, number assigned
by the Enzyme Commission (EC), and other relevant details are specified.
SOURCE
----------------------------------
The SOURCE record specifies the biological and/or chemical source of each biological
molecule in the entry. Sources are described by both the common name and the scientific
name, e.g., genus and species. Strain and/or cell-line for immortalized cells are given
when they help to uniquely identify the biological entity studied.
KEYWDS
----------------------------------
The KEYWDS record contains a set of terms relevant to the entry. Terms in the KEYWDS
record provide a simple means of categorizing entries and may be used to generate
index files. This record addresses some of the limitations found in the classification
field of the HEADER record. It provides the opportunity to add further annotation to
the entry in a concise and computer-searchable fashion.
EXPDTA
----------------------------------
The EXPDTA record presents information about the experiment.
The EXPDTA record identifies the experimental technique used. This may refer to the
type of radiation and sample, or include the spectroscopic or modeling technique.
Permitted values include:
ELECTRON DIFFRACTION
FIBER DIFFRACTION
FLUORESCENCE TRANSFER
NEUTRON DIFFRACTION
NMR
THEORETICAL MODEL
X-RAY DIFFRACTION
AUTHOR
----------------------------------
The AUTHOR record contains the names of the people responsible for the contents of
the entry.
REVDAT
----------------------------------
REVDAT records contain a history of the modifications made to an entry since its release.
SPRSDE
----------------------------------
The SPRSDE records contain a list of the ID codes of entries that were made obsolete
by the given coordinate entry and withdrawn from the PDB release set. One entry may
replace many. It is PDB policy that only the principal investigator of a structure has
the authority to withdraw it.
JRNL
----------------------------------
The JRNL record contains the primary literature citation that describes the experiment
which resulted in the deposited coordinate set. There is at most one JRNL reference per
entry. If there is no primary reference, then there is no JRNL reference. Other references
are given in REMARK 1.
PDB is in the process of linking and/or adding all references to CitDB, the literature
database used by the Genome Data Base (available at URL
http://gdbwww.gdb.org/gdb-bin/genera/genera/citation/Citation).
REMARK
----------------------------------
REMARK records present experimental details, annotations, comments, and information not
included in other records. In a number of cases, REMARKs are used to expand the contents
of other record types. A new level of structure is being used for some REMARK records.
This is expected to facilitate searching and will assist in the conversion to a relational
database.
REMARK 1
----------------------------------
REMARK 1 lists important publications related to the structure presented in the entry.
These citations are chosen by the depositor. They are listed in reverse-chronological
order. Citations are not repeated from the JRNL records. After the first blank record
and the REFERENCE sub-record, the sub-record types for REMARK 1 are the same as in the
JRNL sub-record types. For details, see the JRNL section.
PDB is in the process of linking and/or adding references to CitDB, the literature
database of the Genome Data Base (available at URL
http://gdbwww.gdb.org/gdb-bin/genera/genera/citation/Citation).
REMARK 2
----------------------------------
REMARK 2 states the highest resolution, in Angstroms, that was used in building the model.
As with all the remarks, the first REMARK 2 record is empty and is used as a spacer.
REMARK 3
----------------------------------
REMARK 3 presents information on refinement program(s) used and the related statistics.
For non-diffraction studies, REMARK 3 is used to describe any refinement done, but its
format in those cases is mostly free text.
If more than one refinement package was used, they may be named in
'OTHER REFINEMENT REMARKS'. However, Remark 3 statistics are given for the final
refinement run.
Refinement packages are being enhanced to output PDB REMARK 3. A token: value
template style facilitates parsing. Spacer REMARK 3 lines are interspersed for
visually organizing the information.
The templates below have been adopted in consultation with program authors. PDB is
continuing this dialogue with program authors, and expects the library of PDB records
output by the programs to greatly increase in the near future.
Instead of providing aRecord Formattable, each template is given as it appears in
PDB entries.
REMARK N
----------------------------------
REMARKs following the refinement remark consist of free text annotation, predefined
boilerplate remarks, and token: value pair styled templates. PDB is beginning to organize
the most often used remarks, and assign numbers and topics to them.
Presented here is the scheme being followed in the remark section of PDB files.
The PDB expects to continue to adopt standard text or tables for certain remarks,
as details are worked out.
2- PRIMARY STRUCTURE SECTION:
DBREF
----------------------------------
The DBREF record provides cross-reference links between PDB sequences and the
corresponding database entry or entries. A cross reference to the sequence database
is mandatory for each peptide chain with a length greater than ten (10) residues.
For nucleic acid entries a DBREF record pointing to the Nucleic Acid Database (NDB)
is mandatory when the corresponding entry exists in NDB.
SEQADV
----------------------------------
The SEQADV record identifies conflicts between sequence information in the ATOM records
of the PDB entry and the sequence database entry given on DBREF. Please note that these
records were designed to identify differences and not errors. No assumption is made as
to which database contains the correct data. PDB may include REMARK records in the entry
that reflect the depositor's view of which database has the correct sequence.
SEQRES
----------------------------------
SEQRES records contain the amino acid or nucleic acid sequence of residues in each
chain of the macromolecule that was studied.
MODRES
----------------------------------
The MODRES record provides descriptions of modifications (e.g., chemical or
post-translational) to protein and nucleic acid residues. Included are a mapping
between residue names given in a PDB entry and standard residues.
3- HETEROGEN SECTION
HET
----------------------------------
HET records are used to describe non-standard residues, such as prosthetic groups,
inhibitors, solvent molecules, and ions for which coordinates are supplied. Groups
are considered HET if they are:
- not one of the standard amino acids, and
- not one of the nucleic acids (C, G, A, T, U, and I), and
- not one of the modified versions of nucleic acids (+C, +G, +A, +T, +U, and +I), and
- not an unknown amino acid or nucleic acid where UNK is used to indicate the
unknown residue name.
Het records also describe heterogens for which the chemical identity is unknown,
in which case the group is assigned the hetID UNK.
HETNAM
----------------------------------
This record gives the chemical name of the compound with the given hetID.
HETSYN
----------------------------------
This record provides synonyms, if any, for the compound in the corresponding
(i.e., same hetID) HETNAM record. This is to allow greater flexibility in searching
for HET groups.
FORMUL
----------------------------------
The FORMUL record presents the chemical formula and charge of a non-standard group.
(The formulas for the standard residues are given in Appendix 5.)
4- SECONDARY STRUCTURE SECTION
HELIX
----------------------------------
HELIX records are used to identify the position of helices in the molecule.
Helices are both named and numbered. The residues where the helix begins and ends are
noted, as well as the total length.
SHEET
----------------------------------
SHEET records are used to identify the position of sheets in the molecule.
Sheets are both named and numbered. The residues where the sheet begins and ends are
noted.
TURN
----------------------------------
The TURN records identify turns and other short loop turns which normally connect other
secondary structure segments.
5- CONNECTIVITY ANNOTATION SECTION:
SSBOND
----------------------------------
The SSBOND record identifies each disulfide bond in protein and polypeptide structures
by identifying the two residues involved in the bond.
LINK :
----------------------------------
The LINK records specify connectivity between residues that is not implied by the
primary structure. Connectivity is expressed in terms of the atom names.
This record supplements information given in CONECT records and is provided here
for convenience in searching.
HYDBND
----------------------------------
The HYDBND records specify hydrogen bonds in the entry.
SLTBRG
----------------------------------
The SLTBRG records specify salt bridges in the entry.
CISPEP
----------------------------------
CISPEP records specify the prolines and other peptides found to be in the cis
conformation. This record replaces the use of footnote records to list cis peptides.
6- MISCELLANEOUS FEATURES SECTION:
SITE
----------------------------------
The SITE records supply the identification of groups comprising important sites
in the macromolecule.
7- CRYSTALLOGRAPHIC COORDINATE TRANSFORMATION SECTION
CRYST1
----------------------------------
The CRYST1 record presents the unit cell parameters, space group, and Z value.
If the structure was not determined by crystallographic means, CRYST1 simply defines
a unit cube.
ORIGX 1,2,3
----------------------------------
The ORIGXn (n = 1, 2, or 3) records present the transformation from the orthogonal
coordinates contained in the entry to the submitted coordinates.
SCALE 1,2,3
----------------------------------
The SCALEn (n = 1, 2, or 3) records present the transformation from the orthogonal
coordinates as contained in the entry to fractional crystallographic coordinates.
Non-standard coordinate systems should be explained in the remarks.
MTRIX 1,2,3
----------------------------------
The MTRIXn (n = 1, 2, or 3) records present transformations expressing
non-crystallographic symmetry.
TVECT
----------------------------------
The TVECT records present the translation vector for infinite covalently
connected structures.
8- COORDINATE SECTION
======================================================
MODEL
----------------------------------
The MODEL record specifies the model serial number when multiple structures are
presented in a single coordinate entry, as is often the case with structures determined
by NMR.
ATOM
----------------------------------
The ATOM records present the atomic coordinates for standard residues.
They also present the occupancy and temperature factor for each atom. Heterogen
coordinates use the HETATM record type. The element symbol is always present on each
ATOM record; segment identifier and charge are optional.
SIGATM
----------------------------------
The SIGATM records present the standard deviation of atomic parameters as they appear
in ATOM and HETATM records.
ANISOU
----------------------------------
The ANISOU records present the anisotropic temperature factors.
SIGUIJ
----------------------------------
The SIGUIJ records present the standard deviations of anisotropic temperature factors
scaled by a factor of 10**4 (Angstroms**2).
TER
----------------------------------
The TER record indicates the end of a list of ATOM/HETATM records for a chain.
HETATM
----------------------------------
The HETATM records present the atomic coordinate records for atoms within
'non-standard' groups. These records are used for water molecules and atoms presented
in HET groups.
ENDMDL
----------------------------------
The ENDMDL records are paired with MODEL records to group individual structures
found in a coordinate entry.
9- CONNECTIVITY SECTION
CONECT
----------------------------------
The CONECT records specify connectivity between atoms for which coordinates are
supplied. The connectivity is described using the atom serial number as found in
the entry. CONECT records are mandatory for HET groups (excluding water) and for
other bonds not specified in the standard residue connectivity table which involve
atoms in standard residues (see Appendix 4 for the list of standard residues).
These records are generated by the PDB.
10- BOOKKEEPING SECTION:
MASTER
----------------------------------
The MASTER record is a control record for bookkeeping. It lists the number of lines
in the coordinate entry or file for selected record types.
END
----------------------------------
The END record marks the end of the PDB file
"""
class MoleculeLoader(MVCommand):
"""Base class for all the classes in this module
\nPackage : Pmv
\nModule : bondsCommands
\nClass : MoleculeLoader
"""
def __init__(self):
MVCommand.__init__(self)
self.fileTypes = [('all', '*')]
self.fileBrowserTitle = "Read File"
self.lastDir = "."
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
try:
atms = obj.findType(Atom)
for a in atms:
if hasattr(a, 'alternate'):
delattr(a, 'alternate')
except:
print "exception in MolecularLoader.onRemoveObjectFromViewer", obj.name
#del atms
def guiCallback(self, event=None, *args, **kw):
cmdmenuEntry = self.GUI.menu[4]['label']
files = self.vf.askFileOpen(types=self.fileTypes,
idir=self.lastDir,
title=self.fileBrowserTitle,
multiple=True)
mols = MoleculeSet([])
for file in files:
mol = None
self.lastDir = os.path.split(file)[0]
self.vf.GUI.configMenuEntry(self.GUI.menuButton, cmdmenuEntry,
state='disabled')
mol = self.vf.tryto(self.doitWrapper, file)
self.vf.GUI.configMenuEntry(self.GUI.menuButton,
cmdmenuEntry,state='normal')
mols.extend(mol.data)
self.vf.recentFiles.add(file, self.name)
if len(mols): return mols
else: return None
class MoleculeReader(MoleculeLoader):
"""Command to read molecule
\nPackage : Pmv
\nModule : fileCommands
\nClass : MoleculeReader
\nCommand :readMolecule
\nSynopsis:\n
mols <- readMolecule(filename,parser=None, **kw)
\nRequired Arguments:\n
filename --- path to a file describing a molecule\n
parser --- you can specify the parser to use to parse the file has to be one of 'PDB', 'PDBQ', 'PDBQS','PDBQT', 'PQR', 'MOL2'.This is useful when your file doesn't have the correct extension.
"""
lastDir = None
def __init__(self):
MoleculeLoader.__init__(self)
self.fileTypes =[(
'All supported files',
'*.cif *.mol2 *.pdb *.pqr *.pdbq *.pdbqs *.pdbqt *.f2d *.gro')]
self.fileTypes += [('PDB files', '*.pdb'),
('MEAD files', '*.pqr'),('MOL2 files', '*.mol2'),
('AutoDock files (pdbq)', '*.pdbq'),
('AutoDock files (pdbqs)', '*.pdbqs'),
('AutoDock files (pdbqt)', '*.pdbqt'),
('Gromacs files (gro)', '*.gro'),
('F2Dock input molecule files (f2d)', '*.fd2'),
]
self.parserToExt = {'PDB':'.pdb', 'PDBQ':'.pdbq',
'PDBQS':'.pdbqs', 'PDBQT':'.pdbqt',
'MOL2':'.mol2',
'PQR':'.pqr',
'GRO':'.gro',
'F2D':'.f2d',
}
self.fileTypes += [('MMCIF files', '*.cif'),]
self.parserToExt['CIF'] = '.cif'
self.fileTypes += [('All files', '*')]
self.fileBrowserTitle ="Read Molecule:"
def onAddCmdToViewer(self):
# Do that better
self.vf.loadCommand("fileCommands", ["readPDBQ",
"readPDBQS",
"readPDBQT",
"readPQR",
"readF2D",
"readMOL2",
"readPDB",
"readGRO",
], "Pmv",
topCommand=0)
self.vf.loadCommand("fileCommands", ["readMMCIF"], "Pmv",
topCommand=0)
if self.vf.hasGui:
self.modelsAsMols = Tkinter.IntVar()
self.modelsAsMols.set(1)
self.doModelUpdates = Tkinter.IntVar()
self.doModelUpdates.set(0)
self.setModelUpdates = None
def processArrowEvent(self, event):
#detect molecules with conformations and vina_results
mols = self.vf.Mols.get(lambda x: len(x.allAtoms[0]._coords)>1)
if not len(mols):
return
if hasattr(event, 'keysym') and event.keysym=='Right':
#print "Right"
for m in mols:
geom = m.geomContainer.geoms['ProteinLabels']
ind = m.allAtoms[0].conformation
nconf = len(m.allAtoms[0]._coords)
if ind+1 < nconf:
m.allAtoms.setConformation(ind+1)
event = EditAtomsEvent('coords', m.allAtoms)
self.vf.dispatchEvent(event)
else:
print 'last conformation of ', m.name
if hasattr(event, 'keysym') and event.keysym=='Left':
#print "Left"
for m in mols:
geom = m.geomContainer.geoms['ProteinLabels']
ind = m.allAtoms[0].conformation
if ind > 0:
ind = ind - 1
m.allAtoms.setConformation(ind)
event = EditAtomsEvent('coords', m.allAtoms)
self.vf.dispatchEvent(event)
else:
print 'first conformation of ', m.name
def buildFormDescr(self, formName):
if formName == 'parser':
idf = InputFormDescr(title=self.name)
label = self.fileExt + " has not been recognized\n please choose a parser:"
l = ['PDB','PDBQ', 'PDBQS', 'PDBQT','MOL2','PQR', 'F2D']
l.append('MMCIF')
idf.append({'name':'parser',
'widgetType':Pmw.RadioSelect,
'listtext':l,
'defaultValue':'PDB',
'wcfg':{'labelpos':'nw', 'label_text':label,
'orient':'horizontal',
'buttontype':'radiobutton'},
'gridcfg':{'sticky': 'we'}})
return idf
def guiCallback(self, event=None, *args, **kw):
cmdmenuEntry = self.GUI.menu[4]['label']
files = self.vf.askFileOpen(types=self.fileTypes,
idir=self.lastDir,
title=self.fileBrowserTitle,
multiple=True)
if files is None:
return None
mols = MoleculeSet([])
for file in files:
mol = None
self.lastDir = os.path.split(file)[0]
self.fileExt = os.path.splitext(file)[1]
if not self.fileExt in [".pdb",".pdbq", ".pdbqs", ".pdbqt",
".mol2", ".pqr", ".f2d", ".cif",".gro"]:
# popup a pannel to allow the user to choose the parser
val = self.showForm('parser')
if not val == {}:
self.fileExt = self.parserToExt[val['parser']]
self.vf.GUI.configMenuEntry(self.GUI.menuButton,
cmdmenuEntry,
state='disabled')
mol = self.vf.tryto(self.doitWrapper, file, kw={})
self.vf.GUI.configMenuEntry(self.GUI.menuButton,
cmdmenuEntry,state='normal')
if mol is not None:
mols.data.extend(mol.data)
if len(mols): return mols
else: return None
def __call__(self, filename, parser=None, **kw):
"""mols <- readMolecule(filename,parser=None, **kw)
\nfilename --- path to a file describing a molecule
\nparser --- you can specify the parser to use to parse the file
has to be one of 'PDB', 'PDBQ', 'PDBQS','PDBQT', 'PQR', 'MOL2'.
This is useful when your file doesn't have the correct
extension.
"""
self.fileExt = os.path.splitext(filename)[1]
kw['parser'] = parser
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
def doit(self, filename, parser=None, ask=True, addToRecent=True, **kw):
import os
if not os.path.exists(filename):
self.warningMsg("ERROR: %s doesn't exists"%filename)
return None
if not parser is None and self.parserToExt.has_key(parser):
self.fileExt = self.parserToExt[parser]
# Call the right parser
if self.fileExt == ".pdb" or self.fileExt == ".ent":
# Call readPDB
mols = self.vf.readPDB(filename, ask=ask, topCommand=0)
elif self.fileExt == ".pdbq":
# Call readPDBQ
mols = self.vf.readPDBQ(filename, ask=ask,topCommand=0)
elif self.fileExt == ".pdbqs":
# Call readPDBQS
mols = self.vf.readPDBQS(filename,ask=ask, topCommand=0)
elif self.fileExt == ".pdbqt":
foundModelsAs = kw.has_key("modelsAs")
#print "readMolecule: foundModelsAs=", foundModelsAs
setupUpdates = kw.get("setupUpdates", 0)
#print "readMolecule: setupUpdates=", setupUpdates
#set default in any case
modelsAs = kw.get('modelsAs', 'molecules')
#check for multimodel file
fptr = open(filename)
lines = fptr.readlines()
fptr.close()
found = 0
for l in lines:
if l.find("MODEL")==0:
found = found + 1
if found>1:
break
if found > 0:
if not foundModelsAs:
ifd = InputFormDescr(title="Load MODELS as: ")
ifd.append({'name': 'ModelsAsMols',
'text': 'separate molecules',
'widgetType':Tkinter.Radiobutton,
'tooltip':'Check this button to add a separate molecule for each model.',
'variable': self.modelsAsMols,
'value': '1',
'text': 'Molecules ',
'gridcfg': {'sticky':'w','columnspan':2}})
ifd.append({'name': 'ModelsAsConfs',
'widgetType':Tkinter.Radiobutton,
'tooltip':'Check this button to add a single molecule\n with a separate conformation for each model',
'variable': self.modelsAsMols,
'value': '0',
'text': 'Conformations ',
'gridcfg': {'sticky':'w'}})
ifd.append({'name': 'updates label',
'widgetType':Tkinter.Label,
'tooltip':'On sets changing models with arrow keys',
'text': 'If conformations, change models using arrow keys',
'gridcfg': {'sticky':'w', 'column':0, 'columnspan':2}})
ifd.append({'name': 'updates',
'widgetType':Tkinter.Radiobutton,
'tooltip':'Yes sets changing models with arrow keys',
'variable': self.doModelUpdates,
'value': '1',
'text': 'Yes',
'gridcfg': {'sticky':'w', 'column':0}})
ifd.append({'name': 'no_updates',
'widgetType':Tkinter.Radiobutton,
'tooltip':'No do not change models with arrow keys',
'variable': self.doModelUpdates,
'value': '0',
'text': 'No',
'gridcfg': {'sticky':'w', 'row':-1, 'column':1}})
d = self.vf.getUserInput(ifd)
# if cancel, stop
if not len(d): return
ans = d['ModelsAsMols']
if not ans:
modelsAs = 'conformations'
if modelsAs=='conformations' and (self.doModelUpdates.get() or setupUpdates):
e = self.vf.GUI.VIEWER.currentCamera.eventManager
if "<Right>" in e.eventHandlers.keys():
l = e.eventHandlers["<Right>"]
if self.processArrowEvent not in l:
self.vf.GUI.addCameraCallback("<Right>", self.processArrowEvent)
else:
self.vf.GUI.addCameraCallback("<Right>", self.processArrowEvent)
if "<Left>" in e.eventHandlers.keys():
l = e.eventHandlers["<Left>"]
if self.processArrowEvent not in l:
self.vf.GUI.addCameraCallback("<Left>", self.processArrowEvent)
else:
self.vf.GUI.addCameraCallback("<Left>", self.processArrowEvent)
#self.warningMsg("added arrow keys to camera callbacks!")
# Call readPDBQT
mols = self.vf.readPDBQT(filename, ask=ask, modelsAs=modelsAs,
setupUpdates=setupUpdates, topCommand=0)
elif self.fileExt == ".pqr":
# Call readPQR
mols = self.vf.readPQR(filename,ask=ask, topCommand=0)
elif self.fileExt == ".mol2":
# Call readMOL2
mols = self.vf.readMOL2(filename,ask=ask, topCommand=0)
elif self.fileExt == ".cif":
# Call readMMCIF
mols = self.vf.readMMCIF(filename, ask=ask, topCommand=0)
elif self.fileExt == ".gro":
# Call readGRO
mols = self.vf.readGRO(filename, ask=ask, topCommand=0)
elif self.fileExt == ".f2d":
# Call readGRO
mols = self.vf.readF2D(filename, ask=ask, topCommand=0)
else:
self.warningMsg("ERROR: Extension %s not recognized"%self.fileExt)
return None
if mols is None:
self.warningMsg("ERROR: Could not read %s"%filename)
if addToRecent and hasattr(self.vf,'recentFiles'):
self.vf.recentFiles.add(filename, self.name)
return mols
from Pmv.fileCommandsGUI import MoleculeReaderGUI
class PDBReader(MoleculeLoader):
"""Command to load PDB files using a PDB spec compliant parser
\nPackage : Pmv
\nModule : fileCommands
\nClass : MoleculeReader
\nCommand : readMolecule
\nSynopsis:\n
mols <--- readPDB(filename, **kw)
\nRequired Arguments:\n
filename --- path to the PDB file
"""
lastDir = None
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
modelsAs = self.vf.userpref['Read molecules as']['value']
newparser = PdbParser(filename,modelsAs=modelsAs)
# overwrite progress bar methods
if self.vf.hasGui:
newparser.updateProgressBar = self.vf.GUI.updateProgressBar
newparser.configureProgressBar = self.vf.GUI.configureProgressBar
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <- readPDB(filename, **kw)
\nfilename --- path to the PDB file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
pdbReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read PDB ...',
'index':0}
#PDBReaderGUI = CommandGUI()
#PDBReaderGUI.addMenuCommand('menuRoot', 'File', 'Read PDB ...',index=0)
class MMCIFReader(MoleculeLoader):
"""This command reads macromolecular Crystallographic Information File (mmCIF)
\nPackage : Pmv
\nModule : fileCommands
\nClass : MMCIFReader
\nCommand :readMMCIF
\nSynopsis:\n
mols <- readMMCIF(filename, **kw)
\nRequired Arguments:\n
filename --- path to the MMCIF file
"""
lastDir = None
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
newparser = MMCIFParser(filename)
# overwrite progress bar methods
if self.vf.hasGui:
newparser.updateProgressBar = self.vf.GUI.updateProgressBar
newparser.configureProgressBar = self.vf.GUI.configureProgressBar
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <- readMMCIF(filename, **kw)
\nfilename --- path to the PDB file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
class GROReader(MoleculeLoader):
"""This command reads macromolecular Crystallographic Information File (mmCIF)
\nPackage : Pmv
\nModule : fileCommands
\nClass : MMCIFReader
\nCommand :readMMCIF
\nSynopsis:\n
mols <- readMMCIF(filename, **kw)
\nRequired Arguments:\n
filename --- path to the MMCIF file
"""
lastDir = None
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
newparser = groParser(filename)
# overwrite progress bar methods
if self.vf.hasGui:
newparser.updateProgressBar = self.vf.GUI.updateProgressBar
newparser.configureProgressBar = self.vf.GUI.configureProgressBar
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <- readGRO(filename, **kw)
\nfilename --- path to the PDB file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
class PDBQReader(MoleculeLoader):
"""Command to load AutoDock PDBQ files.
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQReader
\nCommand : readPDBQ
\nSynopsis:\n
mols <--- readPDBQ(filename, **kw)
\nRequired Arguments:\n
filename --- path to the PDBQ file
"""
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbqParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
if hasattr(obj, 'ROOT'):
delattr(obj, 'ROOT')
if hasattr(obj, 'torTree') and hasattr(obj.torTree, 'parser'):
delattr(obj.torTree, 'parser')
del obj.parser
def doit(self, filename, ask=True ):
newparser = PdbqParser(filename )
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <- readPDBQ(filename, **kw)
\nfilename --- path to the PDBQ file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
pdbqReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read PDBQ ...',
'index':0}
#PDBQReaderGUI = CommandGUI()
#PDBQReaderGUI.addMenuCommand('menuRoot', 'File', 'Read PDBQ ...', index=0)
class PDBQSReader(MoleculeLoader):
"""Command to load AutoDock PDBQS files
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQSReader
\nCommand : readPDBQS
\nSynopsis:\n
mols <--- readPDBQS(filename, **kw)
\nRequired Arguments:\n
filename --- path to the PDBQS file
"""
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbqsParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
if hasattr(obj, 'ROOT'):
delattr(obj, 'ROOT')
if hasattr(obj, 'torTree') and hasattr(obj.torTree, 'parser'):
delattr(obj.torTree, 'parser')
del obj.parser
def doit(self, filename, ask=True):
newparser = PdbqsParser(filename)
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <--- readPDBQS(filename, **kw)
\nfilename --- path to the PDBQS file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
pdbqsReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read PDBQS ...',
'index':0}
#PDBQSReaderGUI = CommandGUI()
#PDBQSReaderGUI.addMenuCommand('menuRoot', 'File', 'Read PDBQS ...', index=0)
class PDBQTReader(MoleculeLoader):
"""Command to load AutoDock PDBQT files
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQTReader
\nCommand :readPDBQT
\nSynopsis:\n
mols <--- readPDBQT(filename, **kw)
\nRequired Arguments:\n
filename --- path to the PDBQT file
"""
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PdbqtParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
if hasattr(obj, 'ROOT'):
delattr(obj, 'ROOT')
if hasattr(obj, 'torTree') and hasattr(obj.torTree, 'parser'):
delattr(obj.torTree, 'parser')
del obj.parser
def processArrowEvent(self, event):
#detect molecules with conformations and vina_results
mols = self.vf.Mols.get(len(x.allAtoms[0]._coords)>1)
print "readPDBQT: mols=", mols
if not len(mols):
return
if hasattr(event, 'keysym') and event.keysym=='Right':
#print "Right"
for m in mols:
print m.name
geom = m.geomContainer.geoms['ProteinLabels']
ind = m.allAtoms[0].conformation
nconf = len(m.allAtoms[0]._coords)
if ind+1 < nconf:
m.allAtoms.setConformation(ind+1)
event = EditAtomsEvent('coords', m.allAtoms)
self.vf.dispatchEvent(event)
else:
print 'last MODEL of ', m.name
if hasattr(event, 'keysym') and event.keysym=='Left':
#print "Left"
for m in mols:
print m.name,
geom = m.geomContainer.geoms['ProteinLabels']
ind = m.allAtoms[0].conformation
if ind > 0:
ind = ind - 1
m.allAtoms.setConformation(ind)
event = EditAtomsEvent('coords', m.allAtoms)
self.vf.dispatchEvent(event)
else:
print 'first MODEL of ', m.name
def doit(self, filename, ask=True, modelsAs='molecules', **kw):
#msg ="readPDBQT: modelsAs=" + modelsAs
#self.vf.warningMsg(msg)
newparser = PdbqtParser(filename, modelsAs=modelsAs)
mols = newparser.parse()
if mols is None: return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <--- readPDBQT(filename, **kw)
\nfilename --- path to the PDBQT file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
pdbqtReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read PDBQT ...',
'index':0}
#PDBQTReaderGUI = CommandGUI()
#PDBQTReaderGUI.addMenuCommand('menuRoot', 'File', 'Read PDBQT ...', index=0)
class PQRReader(MoleculeLoader):
"""Command to load MEAD PQR files
\nPackage : Pmv
\nModule : fileCommands
\nClass : PQRReader
\nCommand : readpqr
\nSynopsis:\n
mols <- readPQR(filename, **kw)
\nRequired Arguments:\n
filename --- path to the PQR file
"""
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, PQRParser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
# Free the parser too !
# this dictionary contains referneces to itself through function.
if hasattr(obj.parser, 'pdbRecordParser'):
del obj.parser.pdbRecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
newparser = PQRParser(filename)
mols = newparser.parse()
if mols is None : return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <--- readPQR(filename, **kw)
\nfilename --- path to the PQR file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
pqrReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read PQR ...',
'index':0}
#PQRReaderGUI = CommandGUI()
#PQRReaderGUI.addMenuCommand('menuRoot', 'File', 'Read PQR ...',index=0)
class F2DReader(MoleculeLoader):
"""Command to load F2Dock .f2d files
\nPackage : Pmv
\nModule : fileCommands
\nClass : F2DReader
\nCommand : readF2D
\nSynopsis:\n
mols <- readF2D(filename, **kw)
\nRequired Arguments:\n
filename --- path to the F2D file
"""
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, Mol2Parser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
if hasattr(obj.parser, 'mol2RecordParser'):
del obj.parser.mol2RecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
newparser = F2DParser(filename)
mols = newparser.parse()
if mols is None : return
newmol = []
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <--- readF2D(filename, **kw)
\nfilename --- path to the F2D file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw)
f2dReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read F2D ...',
'index':0}
class MOL2Reader(MoleculeLoader):
"""Command to load MOL2 files
\nPackage : Pmv
\nModule : fileCommands
\nClass : MOL2Reader
\nCommand : readMOL2
\nSynopsis:\n
mols <- readMOL2(filename, **kw)
\nRequired Arguments:\n
filename --- path to the MOL2 file
"""
from MolKit.mol2Parser import Mol2Parser
def onAddCmdToViewer(self):
if not hasattr(self.vf,'readMolecule'):
self.vf.loadCommand('fileCommands', ['readMolecule'], 'Pmv',
topCommand=0)
def onRemoveObjectFromViewer(self, obj):
""" Function to remove the sets able to reference a TreeNode created
in this command : Here remove the alternate location list created
when a pdb File is read."""
if self.vf.undoableDelete__: return
if not hasattr(obj, 'parser') or \
not isinstance(obj.parser, Mol2Parser): return
MoleculeLoader.onRemoveObjectFromViewer(self, obj)
if hasattr(obj.parser, 'mol2RecordParser'):
del obj.parser.mol2RecordParser
if hasattr(obj.parser, 'mol'):
del obj.parser.mol
del obj.parser
def doit(self, filename, ask=True):
newparser = Mol2Parser(filename)
mols = newparser.parse()
newmol = []
if mols is None: return
for m in mols:
mol = self.vf.addMolecule(m, ask)
if mol is None:
del newparser
return mols.__class__([])
newmol.append(mol)
return mols.__class__(newmol)
def __call__(self, filename, **kw):
"""mols <- readMOL2(filename, **kw)
\nfilename --- path to the MOL2 file"""
kw['ask']=0
return apply ( self.doitWrapper, (filename,), kw )
mol2ReaderGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Read MOL2 ...',
'index':0}
#MOL2ReaderGUI = CommandGUI()
#MOL2ReaderGUI.addMenuCommand('menuRoot', 'File', 'Read MOL2',index=0)
class PDBWriter(MVCommand):
"""
Command to write the given molecule or the given subset of atoms
of one molecule as PDB file.
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBWriter
\nCommand : writePDB
\nSynopsis:\n
None <- writePDB( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'MODRES', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'MODRES', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.\n
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def doit(self, nodes, filename=None, sort=True, transformed=False,
pdbRec=['ATOM', 'HETATM', 'MODRES', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None):
if bondOrigin == 0:
bondOrigin = ('File', 'UserDefined')
elif bondOrigin == 1:
bondOrigin = 'all'
nodes = self.vf.expandNodes(nodes)
molecules = nodes.top.uniq()
if len(molecules)==0: return 'ERROR'
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDB file, the current selection contains more than one molecule")
return 'ERROR'
mol = molecules[0]
if filename is None:
filename = './%s.pdb'%mol.name
if transformed:
oldConf = mol.allAtoms[0].conformation
self.setNewCoords(mol)
writer = PdbWriter()
writer.write(filename, nodes, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
if transformed:
mol.allAtoms.setConformation(oldConf)
def setNewCoords(self, mol):
""" set the current conformation to be 1"""
allAtoms = mol.allAtoms
# get a handle on the master geometry
mg = mol.geomContainer.masterGeom
# get the transformation matrix of the root
matrix = mg.GetMatrix(mg) # followed the code in DejaVu/ViewerGUI.py
#def saveTransformation(self, filename, geom)
# Transpose the transformation matrix.
trMatrix = Numeric.transpose(matrix)
# Get the coords of the atoms of your molecule.
allAtoms.setConformation(0)
coords = allAtoms.coords
# Transform them into homogeneous coords.
hCoords = Numeric.concatenate((coords,Numeric.ones( (len(coords), 1), 'd')), 1)
# tranform the coords
#tCoords = Numeric.matrixmultiply(hCoords, matrix)
#tCoords = Numeric.matrixmultiply(hCoords, trMatrix)
tCoords = numpy.dot(hCoords, trMatrix)
# number of conformations available
confNum = len(allAtoms[0]._coords)
if hasattr(mol, 'transformedCoordsIndex'):
# uses the same conformation to store the transformed data
allAtoms.updateCoords(tCoords[:,:3].tolist(), \
mol.transformedCoordsIndex)
else:
# add new conformation to be written to file
allAtoms.addConformation(tCoords[:,:3].tolist())
mol.transformedCoordsIndex = confNum
allAtoms.setConformation( mol.transformedCoordsIndex )
def __call__(self, nodes, filename=None, sort=True, transformed=False,
pdbRec=['ATOM', 'HETATM', 'MODRES', 'CONECT'],
bondOrigin=('File','UserDefined'), ssOrigin=None, **kw):
"""None <- writePDB( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'MODRES', 'CONECT'],
bondOrigin=('File', 'UserDefined')', ssOrigin=None, **kw)
\nRequired Argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'MODRES', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.\n
"""
kw['sort'] = sort
kw['bondOrigin'] = bondOrigin
kw['pdbRec'] = pdbRec
kw['ssOrigin'] = ssOrigin
kw['filename'] = filename
kw['transformed'] = transformed
return apply(self.doitWrapper, (nodes,), kw)
def dismiss_cb(self):
if not self.cmdForms.has_key('PDBHelp'): return
f = self.cmdForms['PDBHelp']
if f.root.winfo_ismapped():
f.root.withdraw()
f.releaseFocus()
def showPDBHelp(self):
f = self.cmdForms['saveOptions']
f.releaseFocus()
nf = self.showForm("PDBHelp", modal=0, blocking=0)
def add_cb(self):
from mglutil.util.misc import uniq
ebn = self.cmdForms['saveOptions'].descr.entryByName
lb1 = ebn['avRec']['widget']
lb2 = ebn['pdbRec']['widget']
newlist = uniq(list(lb2.get()) + list(lb1.getcurselection()))
lb2.setlist(newlist)
if 'CONECT' in newlist:
self.idf.entryByName['bondOrigin']['widget'].grid(sticky='w')
def remove_cb(self):
ebn = self.cmdForms['saveOptions'].descr.entryByName
lb2 = ebn['pdbRec']['widget']
sel = lb2.getcurselection()
all = lb2.get()
if sel:
remaining = filter(lambda x: not x in sel, all)
lb2.setlist(remaining)
if 'CONECT' in sel:
self.idf.entryByName['bondOrigin']['widget'].grid_forget()
def setEntry_cb(self, filename ):
ebn = self.cmdForms['saveOptions'].descr.entryByName
entry = ebn['filename']['widget']
entry.setentry(filename)
def buildFormDescr(self, formName):
from mglutil.util.misc import uniq
if formName=='saveOptions':
idf = InputFormDescr(title='Write Options')
self.idf =idf
idf.append({'name':'fileGroup',
'widgetType':Pmw.Group,
'container':{'fileGroup':"w.interior()"},
'wcfg':{},
'gridcfg':{'sticky':'wnse', 'columnspan':4}})
idf.append({'name':'filename',
'widgetType':Pmw.EntryField,
'parent':'fileGroup',
'tooltip':'Enter a filename',
'wcfg':{'label_text':'Filename:',
'labelpos':'w', 'value':self.defaultFilename},
'gridcfg':{'sticky':'we'},
})
idf.append({'widgetType':SaveButton,
'name':'filebrowse',
'parent':'fileGroup',
'wcfg':{'buttonType':Tkinter.Button,
'title':self.title,
'types':self.fileType,
'callback':self.setEntry_cb,
'widgetwcfg':{'text':'BROWSE'}},
'gridcfg':{'row':-1, 'sticky':'we'}})
# Find the available records and the avalaibe options
# bond origin and secondary structure origin)
# default records
defRec = ['ATOM', 'HETATM', 'MODRES', 'CONECT']
if isinstance(self.mol.parser, PdbParser):
defRec = ['ATOM', 'HETATM', 'MODRES', 'CONECT', 'SHEET', 'TURN', 'HELIX']
avRec = uniq(self.mol.parser.keys)
#sargis added the following line to make sure that only
#PdbParser.PDBtags are displayed
avRec = filter(lambda x: x in avRec, PdbParser.PDBtags)
defRec = filter(lambda x: x in avRec, defRec)
else:
avRec = ['ATOM', 'HETATM', 'MODRES', 'CONECT']
# Source of the secondary structure information
ssRec = filter(lambda x: x in avRec, ['HELIX', 'SHEET', 'TURN'])
if self.mol.hasSS != []:
avRec = avRec + ['HELIX', 'SHEET', 'TURN']
ssOrigin = [self.mol.hasSS[0].split('From ')[1],]
if len(ssRec) !=0 and self.mol.hasSS != ['From File']:
ssOrigin.append('File')
elif len(ssRec) != 0:
ssOrigin=['File',]
else:
ssOrigin = None
# Source of the CONECT information
atms = self.nodes.findType(Atom)
bonds = atms.bonds[0]
bondOrigin = uniq(bonds.origin)
if len(bondOrigin)>0 and not 'CONECT' in avRec: avRec.append('CONECT')
# HYBND is also a record that can be created from
# the molecular data structure.
hydbnd = atms.get(lambda x: hasattr(x, 'hbonds'))
if hydbnd is not None and len(hydbnd) and not "HYDBND" in avRec:
avRec.append("HYDBND")
avRec.sort()
# Available records to write out
idf.append({'name':'recGroup',
'widgetType':Pmw.Group,
'container':{'recGroup':"w.interior()"},
'wcfg':{'tag_text':"PDB Records:"},
'gridcfg':{'sticky':'wnse', 'columnspan':2}})
idf.append({'name':'avRec',
'widgetType':Pmw.ScrolledListBox,
'parent':'recGroup',
'tooltip':'The available PDB records are the records present in the original PDB \n\
file when relevant and the PDB records that can be created from the MolKit data structure \n\
(such as ATOM, HETATM, CONECT, TER, HELIX, SHEET, TURN, HYDBND). The TER record will be automatically \n\
created with the ATOM records.',
'wcfg':{'label_text':'Available PDB Records: ',
'labelpos':'nw',
'items':avRec,
'listbox_selectmode':'extended',
'listbox_exportselection':0,
'listbox_height':5,'listbox_width':10,
},
'gridcfg':{'sticky': 'wesn','row':1, 'column':0,'rowspan':2}})
idf.append({'name':'pdbinfo',
'parent':'recGroup',
'widgetType':Tkinter.Button,
'tooltip':'Show PDB record description',
'wcfg':{'text':'Records \nInfo',
'command':self.showPDBHelp},
'gridcfg':{'sticky':'we', 'row':1, 'column':1}})
idf.append({'name':'add',
'parent':'recGroup',
'widgetType':Tkinter.Button,
'tooltip':""" Add the selected PDB record to the list
of saved in the file""",
'wcfg':{'text':'Add','command':self.add_cb},
'gridcfg':{'sticky':'we','row':2, 'column':1}})
idf.append({'name':'pdbRec',
'parent':'recGroup',
'widgetType':Pmw.ScrolledListBox,
'wcfg':{'label_text':'PDB Records to be saved: ',
'labelpos':'nw',
'items':defRec,
'listbox_selectmode':'extended',
'listbox_exportselection':0,
'listbox_height':5,'listbox_width':10,
},
'gridcfg':{'sticky': 'wesn', 'row':1, 'column':2, 'rowspan':2}})
idf.append({'name':'remove',
'parent':'recGroup',
'widgetType':Tkinter.Button,
'tooltip':""" Remove the selected records from the list of records to be saved in the file.""",
'wcfg':{'text':'REMOVE','width':10,
'command':self.remove_cb},
'gridcfg':{'sticky':'we', 'row':1, 'column':3}})
# OTHER OPTIONS
idf.append({'name':'optionGroup',
'widgetType':Pmw.Group,
'container':{'optionGroup':"w.interior()"},
'wcfg':{'tag_text':"Other write options:"},
'gridcfg':{'sticky':'wnse', 'columnspan':3}})
# sort the nodes
idf.append({'name':'sort',
'parent':'optionGroup',
'widgetType':Tkinter.Checkbutton,
'tooltip':'Choose whether or not to sort the nodes before writing in the PDB files',
'wcfg':{'text':'Sort Nodes', 'variable':Tkinter.IntVar()},
'gridcfg':{'sticky':'w'}})
# save transformed coords
idf.append({'name':'transformed',
'parent':'optionGroup',
'widgetType':Tkinter.Checkbutton,
'tooltip':'Choose to save original coordinates or the transformed coordinates in Viewer.',
'wcfg':{'text':'Save Transformed Coords', 'variable':Tkinter.IntVar()},
'gridcfg':{'sticky':'w'}})
if 'CONECT' in avRec: # bond origin
idf.append({'name':'bondOrigin',
'parent':'optionGroup',
'widgetType':Tkinter.Checkbutton,
'tooltip':'When this button is not checked, only bonds created from original CONECT records and\nbonds added by the user (i.e. addBond command) will generate CONECT records in the output file.',
'wcfg':{'text':'Write All Bonds as CONECT Records ', 'variable':Tkinter.IntVar()},
'gridcfg':{'sticky':'w'}})
# secondary structure origin
if not ssOrigin is None and len(ssOrigin)>1:
idf.append({'name':'ssOrigin',
'widgetType':Pmw.RadioSelect,
'listtext':ssOrigin,'defaultValue':ssOrigin[0],
'parent':'optionGroup',
'tooltip':"",
'wcfg':{'label_text': 'Secondary structure information source:',
'labelpos':'w','buttontype':'radiobutton', 'selectmode':'single',
},
'gridcfg':{'sticky':'w'}})
return idf
elif formName == 'PDBHelp':
idf = InputFormDescr(title='PDB FORMAT HELP')
idf.append({'name':'pdbHelp',
'widgetType':Pmw.ScrolledText,
'defaultValue':pdbDescr,
'wcfg':{ 'labelpos':'nw',
'label_text':'PDB Format description:',
'text_width':50,
'text_height':20},
'gridcfg':{'sticky':'we'}})
idf.append({'name':'dismiss',
'widgetType':Tkinter.Button,
'wcfg':{'text':'DISMISS',
'command':self.dismiss_cb},
'gridcfg':{'sticky':'we'}})
return idf
def guiCallback(self):
# Get the current selection
nodes = self.vf.getSelection()
if not len(nodes): return None
molecules, nodes = self.vf.getNodesByMolecule(nodes)
# Make sure that the current selection only belong to 1 molecule
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDB file.\n\
The current selection contains more than one molecule.")
return
self.mol = molecules[0]
self.nodes = nodes[0]
self.title = "Write PDB file"
self.fileType = [('PDB file', '*.pdb')]
currentPath = os.getcwd()
self.defaultFilename = os.path.join(currentPath,self.mol.name) + '.pdb'
val = self.showForm('saveOptions', force=1,
cancelCfg={'text':'Cancel',
'command':self.dismiss_cb},
okCfg={'text':'OK',
'command':self.dismiss_cb})
if val:
fileName = val['filename']
if os.path.exists(fileName):
if not askyesno("Overwrite", "File " +fileName+ " exists. Overwrite?"):
return
if val.has_key('filebrowse'):
del val['filebrowse']
del val['avRec']
ebn = self.cmdForms['saveOptions'].descr.entryByName
w = ebn['pdbRec']['widget']
val['pdbRec'] = w.get()
if len(val['pdbRec'])==0: return
apply(self.doitWrapper, (self.nodes,), val)
pdbWriterDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Write PDB ...',
'index':0}
from Pmv.fileCommandsGUI import PDBWriterGUI
class PQRWriter(PDBWriter):
"""Command to write PQR files using a PQR spec compliant writer
\nPackage : Pmv
\nModule : fileCommands
\nClass : PQRWriter
\nCommand : writePQR
\nSynopsis:\n
None <- writePQR(filename, nodes, sort=True, **kw)
\nRequired Arguments:\n
filename --- name of the PQR file
nodes --- TreeNodeSet holding the current selection\n
\nOptional Arguments:\n
sort --- default is 1
"""
from MolKit.pqrWriter import PqrWriter
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, filename, nodes, sort):
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
mol = nodes.top.uniq()
assert len(mol)==1
if sort:
#print 'nodes are sorted'
nodes.sort()
writer = self.PqrWriter()
writer.write(filename, nodes)
def __call__(self, filename, nodes, sort=True, recType='all', **kw):
"""None <--- writePQR(filename, nodes, sort=True, **kw)
\nfilename --- name of the PQR file
\nnodes --- TreeNodeSet holding the current selection
\nsort --- default is 1
"""
kw['sort'] = sort
apply(self.doitWrapper, (filename, nodes,), kw)
def guiCallback(self):
file = self.vf.askFileSave(types=[('prq files', '*.pqr')],
title="write PQR file:")
if file == None: return
nodes = self.vf.getSelection()
if not len(nodes): return None
if len(nodes.top.uniq())>1:
self.warningMsg("more than one molecule in selection")
return
elif len(nodes)!=len(nodes.top.uniq().findType(nodes[0].__class__)):
msg = 'writing only selected portion of '+ nodes[0].top.name
self.warningMsg(msg)
ans = Tkinter.IntVar()
ans.set(1)
ifd = InputFormDescr(title='Write Options')
ifd.append({'name':'sortLab',
'widgetType': Tkinter.Label,
'wcfg':{'text':'Sort Nodes:'},
'gridcfg': {'sticky':Tkinter.W}})
ifd.append({'name': 'yesWid',
'widgetType':Tkinter.Radiobutton,
'value': '1',
'variable': ans,
'text': 'Yes',
'gridcfg': {'sticky':Tkinter.W}})
ifd.append({'name': 'noWid',
'widgetType':Tkinter.Radiobutton,
'value': '0',
'text': 'No',
'variable': ans,
'gridcfg': {'sticky':Tkinter.W, 'row':-1,'column':1}})
val = self.vf.getUserInput(ifd)
if val:
sort = ans.get()
if sort == 1:
nodes.sort()
self.doitWrapper(file, nodes, sort)
pqrWriterDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Write PQR ...',
'index':0}
from Pmv.fileCommandsGUI import PQRWriterGUI
class PDBQWriter(PDBWriter):
"""Command to write PDBQ files using a PDBQ spec compliant writer
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQWriter
\nCommand : writePDBQ
\nSynopsis:\n
None <- writePDBQ( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)
\nRequired Argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.\n
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False):
if bondOrigin == 0:
bondOrigin = ('File', 'UserDefined')
elif bondOrigin == 1:
bondOrigin = 'all'
nodes = self.vf.expandNodes(nodes)
molecules = nodes.top.uniq()
if len(molecules)==0: return 'ERROR'
# Cannot save multiple molecules in one PDB file. They need to be merged into one molecule
# first
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQ file, the current selection contains more than one molecule")
return 'ERROR'
mol = molecules[0]
# Cannot save a PDBQ file if all the atoms donnot have a charge assigned.
allAtoms = nodes.findType(Atom)
try:
allAtoms.charge
except:
try:
allAtoms.charge=allAtoms.gast_charge
except:
self.warningMsg('ERROR: Cannot create the PDBQ file, all atoms in the current selection do not have a charge field. Use the commands in the editCommands module to either assign Kollman charges or compute Gasteiger charges')
return 'ERROR'
if filename is None:
filename = './%s.pdbq'%mol.name
if transformed:
oldConf = mol.allAtoms[0].conformation
self.setNewCoords(mol)
writer = PdbqWriter()
writer.write(filename, nodes, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
if transformed:
mol.allAtoms.setConformation(oldConf)
def __call__(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False, **kw):
"""None <- writePDBQ( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)
\nRequired Argument:\n
nodes: TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.\n
"""
kw['sort'] = sort
kw['bondOrigin'] = bondOrigin
kw['ssOrigin'] = ssOrigin
kw['filename'] = filename
kw['transformed'] = transformed
apply(self.doitWrapper, (nodes,), kw)
def guiCallback(self):
# Get the current selection
nodes = self.vf.getSelection()
if not len(nodes): return None
molecules, nodes = self.vf.getNodesByMolecule(nodes)
# Make sure that the current selection only belong to 1 molecule
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQ file.\n\
The current selection contains more than one molecule.")
return
self.mol = molecules[0]
self.nodes = nodes[0]
self.title = "Write PDBQ file"
self.fileType = [('PDBQ file', '*.pdbq')]
currentPath = os.getcwd()
self.defaultFilename = os.path.join(currentPath,self.mol.name) + '.pdbq'
val = self.showForm('saveOptions', force=1,cancelCfg={'text':'Cancel', 'command':self.dismiss_cb},
okCfg={'text':'OK', 'command':self.dismiss_cb})
if val:
del val['avRec']
if val.has_key('filebrowse'): del val['filebrowse']
ebn = self.cmdForms['saveOptions'].descr.entryByName
w = ebn['pdbRec']['widget']
val['pdbRec'] = w.get()
if len(val['pdbRec'])==0: return
apply(self.doitWrapper, (self.nodes,), val)
pdbqWriterGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Write PDBQ ...',
'index':0}
from Pmv.fileCommandsGUI import PDBQWriterGUI
class PDBQSWriter(PDBWriter):
"""Command to write PDBQS files using a PDBQS spec compliant writer
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQSWriter
\nCommand : writePDBQS
\nSynopsis:\n
None <- writePDBQS( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)
\nRequired Argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.\n
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False):
if bondOrigin == 0:
bondOrigin = ('File', 'UserDefined')
elif bondOrigin == 1:
bondOrigin = 'all'
nodes = self.vf.expandNodes(nodes)
molecules = nodes.top.uniq()
if len(molecules)==0: return 'ERROR'
# Cannot save multiple molecules in one PDB file. They need to be merged into one molecule
# first
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQS file, the current selection contains more than one molecule")
return 'ERROR'
mol = molecules[0]
# Cannot save a PDBQ file if all the atoms donnot have a charge assigned.
allAtoms = nodes.findType(Atom)
try:
allAtoms.charge
except:
try:
allAtoms.charge=allAtoms.gast_charge
except:
self.warningMsg('ERROR: Cannot create the PDBQS file, all atoms in the current selection do not have a charge field. Use the commands in the editCommands module to either assign Kollman charges or compute Gasteiger charges')
return 'ERROR'
try:
allAtoms.AtSolPar
allAtoms.AtVol
except:
self.warningMsg('ERROR: Cannot create the PDBQS file, all atoms do not have a solvation fields')
return 'ERROR'
if filename is None:
filename = './%s.pdbqs'%mol.name
if transformed:
oldConf = mol.allAtoms[0].conformation
self.setNewCoords(mol)
writer = PdbqsWriter()
writer.write(filename, nodes, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
if transformed:
mol.allAtoms.setConformation(oldConf)
def __call__(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False, **kw):
"""None <- writePDBQS( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)
\nRequired Argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or From Stride.
"""
kw['sort'] = sort
kw['bondOrigin'] = bondOrigin
kw['ssOrigin'] = ssOrigin
kw['filename'] = filename
kw['transformed'] = transformed
apply(self.doitWrapper, (nodes,), kw)
def guiCallback(self):
# Get the current selection
nodes = self.vf.getSelection()
if not len(nodes): return None
molecules, nodes = self.vf.getNodesByMolecule(nodes)
# Make sure that the current selection only belong to 1 molecule
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQS file.\n\
The current selection contains more than one molecule.")
return
self.mol = molecules[0]
self.nodes = nodes[0]
self.title = "Write PDBQS file"
self.fileType = [('PDBQS file', '*.pdbqs')]
currentPath = os.getcwd()
self.defaultFilename = self.defaultFilename = os.path.join(currentPath,self.mol.name) + '.pdbqs'
val = self.showForm('saveOptions', force=1,cancelCfg={'text':'Cancel', 'command':self.dismiss_cb},
okCfg={'text':'OK', 'command':self.dismiss_cb})
if val:
del val['avRec']
if val.has_key('filebrowse'): del val['filebrowse']
ebn = self.cmdForms['saveOptions'].descr.entryByName
w = ebn['pdbRec']['widget']
val['pdbRec'] = w.get()
if len(val['pdbRec'])==0: return
apply(self.doitWrapper, (self.nodes,), val)
pdbqsWriterGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Write PDBS ...',
'index':0}
from Pmv.fileCommandsGUI import PDBQSWriterGUI
class PDBQTWriter(PDBWriter):
"""Command to write PDBQT files using a PDBQT spec compliant writer
\nPackage : Pmv
\nModule : fileCommands
\nClass : PDBQTWriter
\nCommand : write PDBQT
\nSynopsis:\n
None <--- writePDBQT( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)\n
\nRequired argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False):
if bondOrigin == 0:
bondOrigin = ('File', 'UserDefined')
elif bondOrigin == 1:
bondOrigin = 'all'
nodes = self.vf.expandNodes(nodes)
molecules = nodes.top.uniq()
if len(molecules)==0: return 'ERROR'
# Cannot save multiple molecules in one PDB file. They need to be merged into one molecule
# first
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQT file, the current selection contains more than one molecule")
return 'ERROR'
mol = molecules[0]
# Cannot save a PDBQ file if all the atoms donnot have a charge assigned.
allAtoms = nodes.findType(Atom)
try:
allAtoms.charge
except:
try:
allAtoms.charge=allAtoms.gast_charge
except:
self.warningMsg('ERROR: Cannot create the PDBQT file, all atoms in the current selection do not have a charge field. Use the commands in the editCommands module to either assign Kollman charges or compute Gasteiger charges')
return 'ERROR'
try:
allAtoms.autodock_element
except:
self.warningMsg('ERROR: Cannot create the PDBQT file, all atoms do not have an autodock_element field')
return 'ERROR'
if filename is None:
filename = './%s.pdbqt'%mol.name
if transformed:
oldConf = mol.allAtoms[0].conformation
self.setNewCoords(mol)
writer = PdbqtWriter()
writer.write(filename, nodes, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
if transformed:
mol.allAtoms.setConformation(oldConf)
def __call__(self, nodes, filename=None, sort=True, pdbRec = ['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, transformed=False, **kw):
"""None <- writePDBQT( nodes, filename=None, sort=True,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin=('File', 'UserDefined'), ssOrigin=None, **kw)\n
\nRequired Argument:\n
nodes --- TreeNodeSet holding the current selection
\nOptional Arguments:\n
filename --- name of the PDB file (default=None). If None is given
The name of the molecule plus the .pdb extension will be used\n
sort --- Boolean flag to either sort or not the nodes before writing
the PDB file (default=True)\n
pdbRec --- List of the PDB Record to save in the PDB file.
(default: ['ATOM', 'HETATM', 'CONECT']\n
bondOrigin --- string or list specifying the origin of the bonds to save
as CONECT records in the PDB file. Can be 'all' or a tuple\n
ssOrigin --- Flag to specify the origin of the secondary structure
information to be saved in the HELIX, SHEET and TURN
record. Can either be None, File, PROSS or Stride.
"""
kw['sort'] = sort
kw['bondOrigin'] = bondOrigin
kw['ssOrigin'] = ssOrigin
kw['filename'] = filename
kw['transformed'] = transformed
apply(self.doitWrapper, (nodes,), kw)
def guiCallback(self):
# Get the current selection
nodes = self.vf.getSelection()
if not len(nodes): return None
molecules, nodes = self.vf.getNodesByMolecule(nodes)
# Make sure that the current selection only belong to 1 molecule
if len(molecules)>1:
self.warningMsg("ERROR: Cannot create the PDBQT file.\n\
The current selection contains more than one molecule.")
return
self.mol = molecules[0]
self.nodes = nodes[0]
self.title = "Write PDBQT file"
self.fileType = [('PDBQT file', '*.pdbqt')]
currentPath = os.getcwd()
self.defaultFilename = self.defaultFilename = os.path.join(currentPath,self.mol.name) + '.pdbqt'
val = self.showForm('saveOptions', force=1,cancelCfg={'text':'Cancel', 'command':self.dismiss_cb},
okCfg={'text':'OK', 'command':self.dismiss_cb})
if val:
del val['avRec']
if val.has_key('filebrowse'): del val['filebrowse']
ebn = self.cmdForms['saveOptions'].descr.entryByName
w = ebn['pdbRec']['widget']
val['pdbRec'] = w.get()
if len(val['pdbRec'])==0: return
apply(self.doitWrapper, (self.nodes,), val)
pdbqtWriterGuiDescr = {'widgetType':'Menu', 'menyBarName':'menuRoot',
'menuButtonName':'File',
'menyEntryLabel':'Write PDBQT ...',
'index':0}
from Pmv.fileCommandsGUI import PDBQTWriterGUI
class SaveMMCIF(MVCommand):
"""This command writes macromolecular Crystallographic Information File (mmCIF).
\nPackage : Pmv
\nModule : fileCommands
\nClass : SaveMMCIF
\nCommand : saveMMCIF
\nSynopsis:\n
None<---saveMMCIF(filename, nodes)
\nRequired Arguments:\n
filename --- name of the mmcif file (default=None). If None is given
The name of the molecule plus the .cif extension will be used\n
nodes --- TreeNodeSet holding the current selection
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, filename, nodes):
nodes = self.vf.expandNodes(nodes)
writer = MMCIFWriter()
writer.write(filename, nodes)
def __call__(self, filename, nodes,**kw):
"""None<---saveMMCIF(filename,nodes)
\nfilename --- name of the mmcif file (default=None). If None is given
The name of the molecule plus the .cif extension will be used\n
\nnodes --- TreeNodeSet holding the current selection
"""
nodes = self.vf.expandNodes(nodes)
apply(self.doitWrapper, (filename, nodes), kw)
def guiCallback(self):
filename = self.vf.askFileSave(types=[('MMCIF files', '*.cif')],
title="Write MMCIF File:")
if not filename: return
nodes = self.vf.getSelection()
if not len(nodes) : return None
if len(nodes.top.uniq())>1:
self.warningMsg("more than one molecule in selection")
return
self.doitWrapper(filename, nodes)
from Pmv.fileCommandsGUI import SaveMMCIFGUI
class STLWriter(MVCommand):
"""Command to write coords&normals of currently displayed geometries as
ASCII STL files (STL = stereolithography, don't confuse with standard
template library)
\nPackage : Pmv
\nModule : fileCommands
\nClass : STLWriter
\nCommand : writeSTL
\nSynopsis:\n
None<---Write STL ( filename, sphereQuality=2,
cylinderQuality=10 )
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def doit(self, filename, sphereQuality=0,
cylinderQuality=0):
"""Write all displayed geoms of all displayed molecules in
the STL format"""
from DejaVu.DataOutput import OutputSTL
STL = OutputSTL()
stl = STL.getSTL(self.vf.GUI.VIEWER.rootObject, filename,
sphereQuality=sphereQuality,
cylinderQuality=cylinderQuality)
if stl is not None and len(stl) != 0:
f = open(filename, 'w')
map( lambda x,f=f: f.write(x), stl)
f.close()
def __call__(self, filename, **kw):
"""None <--- Write STL ( filename, sphereQuality=0,
cylinderQuality=0 )"""
apply( self.doitWrapper, (filename,), kw )
def guiCallback(self):
newfile = self.vf.askFileSave(types=[('STL files', '*.stl'),],
title='Select STL files:')
if not newfile or newfile == '':
return
from DejaVu.DataOutput import STLGUI
opPanel = STLGUI(master=None, title='STL Options')
opPanel.displayPanel(create=1)
if not opPanel.readyToRun:
return
# get values from options panel
di = opPanel.getValues()
sq = di['sphereQuality']
cq = di['cylinderQuality']
self.doitWrapper(newfile, sq, cq)
stlWriterGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'File',
'menuEntryLabel':'Write STL',
}
from Pmv.fileCommandsGUI import STLWriterGUI
class VRML2Writer(MVCommand):
"""Command to save currently displayed geometries in VRML 2.0 format
\nPackage : Pmv
\nModule : fileCommands
\nClass : VRML2Writer
\nCommand : writeVRML2.0file
\nSynopsis:\n
None<---Write VRML 2.0 file (filename, saveNormals=0,
colorPerVertex=True, useProto=0, sphereQuality=2, cylinderQuality=10 )
"""
# def logString(self, *args, **kw):
# """return None as log string as we don't want to log this
#"""
# pass
def onAddCmdToViewer(self):
if self.vf.hasGui:
from DejaVu.DataOutput import VRML2GUI
self.opPanel = VRML2GUI(master=None, title='VRML2 Options')
def __init__(self):
MVCommand.__init__(self)
def doit(self, filename, saveNormals=0,
colorPerVertex=True, useProto=0,
sphereQuality=2, cylinderQuality=10):
from DejaVu.DataOutput import OutputVRML2
V = OutputVRML2()
# add hook to progress bar
if self.vf.hasGui:
V.updateProgressBar = self.vf.GUI.updateProgressBar
V.configureProgressBar = self.vf.GUI.configureProgressBar
vrml2 = V.getVRML2(self.vf.GUI.VIEWER.rootObject, complete=1,
normals=saveNormals,
colorPerVertex=colorPerVertex, usePROTO=useProto,
sphereQuality=sphereQuality,
cylinderQuality=cylinderQuality)
if vrml2 is not None and len(vrml2) != 0:
f = open(filename, 'w')
map( lambda x,f=f: f.write(x), vrml2)
f.close()
del vrml2
def __call__(self, filename, saveNormals=0,
colorPerVertex=True, useProto=0,
sphereQuality=2, cylinderQuality=10, **kw):
"""Write VRML 2.0 file (filename, saveNormals=0,
colorPerVertex=True, useProto=0, sphereQuality=2, cylinderQuality=10 )"""
kw['saveNormals'] = saveNormals
kw['colorPerVertex'] = colorPerVertex
kw['useProto'] = useProto
kw['sphereQuality'] = sphereQuality
kw['cylinderQuality'] = cylinderQuality
apply( self.doitWrapper, (filename,), kw)
def guiCallback(self):
newfile = self.vf.askFileSave(types=[('VRML 2.0 files', '*.wrl'),],
title='Select VRML 2.0 files:')
if newfile is None or newfile == '':
return
# if not self.opPanel.readyToRun:
# self.opPanel.displayPanel(create=1)
# else:
# self.opPanel.displayPanel(create=0)
# get values from options panel
di = self.opPanel.getValues()
sn = di['saveNormals']
co = di['colorPerVertex']
if co == 1:
co = True
else:
co = False
up = di['usePROTO']
sq = di['sphereQuality']
cq = di['cylinderQuality']
kw = {'saveNormals':di['saveNormals'],
'colorPerVertex':di['colorPerVertex'],
'useProto':di['usePROTO'], 'sphereQuality':di['sphereQuality'],
'cylinderQuality':di['cylinderQuality'], 'redraw':0}
apply(self.doitWrapper, (newfile,), kw)
#self.doitWrapper(newfile, sn, ni, co, up, sq, cq)
vrml2WriterGuiDescr = {'widgetType':'Menu', 'menuBarName':'menuRoot',
'menuButtonName':'File',
'menuEntryLabel':'Write VRML 2.0',
}
from Pmv.fileCommandsGUI import VRML2WriterGUI
import urllib
class fetch(MVCommand):
"""This command read a molecule from the web.
\nPackage : Pmv
\nModule : fileCommands
\nClass : readFromWebCommand
\nCommand : readFromWeb
\nSynopsis:\n
mols <- readFromWeb(pdbID=None, URL="Default")
\nguiCallback:
Opens InputForm with 3 EntryFields
PDB ID: 4-character code (e.g. 1crn).
Keyword: searched using RCSB.ORG search engine
URL: should point to an existing molecule (e.g http://mgltools.scripps.edu/documentation/tutorial/molecular-electrostatics/HIS.pdb)
If Keyword contains a text it is searched first. When URL field is not empty this URL is used instead of PDB ID to retrieve molecule.
Mouse over PDB Cache Directory label to see the path, or click Clear button to remove all files from there.
"""
baseURI = "http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId="
searchURI = "http://www.rcsb.org/pdb/search/navbarsearch.do?inputQuickSearch="
resultURI = 'http://www.rcsb.org/pdb/results/results.do'
from mglutil.util.packageFilePath import getResourceFolderWithVersion
rcFolder = getResourceFolderWithVersion()
width = 440 #width of the GUI
height = 200 #height of the GUI
forceIt = False #do we force the fect even if in the pdbcache dir
def onAddCmdToViewer(self):
self.vf.userpref.add( 'PDB Cache Storage (MB)', 100,
validateFunc = self.validateUserPref,
callbackFunc = [self.userPref_cb],
doc="""Maximum space allowed for File -> Read -> fetch From Web.""")
def message_box(self):
txt = "The file you requested does not exist\n"
txt+= "Do you want to search again?"
if askyesno(title = 'Invalid Input',message=txt):
self.guiCallback()
def find_list(self,keyword):
"""This function is to find out number of pages molecules are
listed and get all molecule and information. """
if keyword:
keyword = keyword.replace(' ','%20')
uri = self.searchURI+keyword
try:
fURL = urllib.urlopen(uri)
except Exception, inst:
print inst
return
# if 'content-type' not in fURL.headers.keys():
# self.message_box()
# return
# if fURL.headers['content-type'] == 'text/html;charset=ISO-8859-1' or fURL.headers['content-type'] =="text/html; charset=iso-8859-1":
m=[]
self.listmols=[]
self.information=[]
newurl = fURL.geturl()
#shows first hundred files
cur_url = newurl.split(";")[-1]
st = "startAt=0&resultsperpage=100"
cURL = self.resultURI+";"+cur_url+"?"+st
fURL = urllib.urlopen(cURL)
fp = open("dataf" ,"w")
fp.write(fURL.read())
fp.close()
fp = open("dataf")
lines =fp.readlines()
fp.close()
os.remove("dataf")
## file names
for i in lines:
if '<input type="checkbox" name=' in i:
m.append(i)
for j in m:
h = eval(str(j.split(" ")[-1][:-2]).split("=")[-1])
self.listmols.append(h)
if len(self.listmols)==0:
return
##information
z=[]
c=[]
for i in lines:
if 'href="/pdb/explore.do?structureId=' in i:
z.append(i)
for i in z:
c.append(i.split(">"))
for i in c:
if len(i[-1])>6:
self.information.append(i[-1][:-2])
def __call__(self, pdbID=None, URL="Default", **kw):
if kw.has_key('f'):
self.forceIt = kw['f']
else :
self.forceIt = False
return apply(self.doitWrapper, (pdbID,URL))
def doit(self, pdbID=None, URL="Default"):
gz=False
#forceIt = True
ext = ".pdb"
URI = URL
if not hasattr(self,'db'):
self.db=""
if pdbID == None and URL !="Default":
URI = URL
txt = URL.split("/")[-1]
pdbID = txt[:-4]
ext = txt[-4:]
elif pdbID != None:
if len(pdbID) > 4 or self.db != "":
if pdbID[4:] == '.trpdb' or self.db == "Protein Data Bank of Transmembrane Proteins (TMPDB)":
#most are xml format just look if the 1t5t.trpdb.gz exist
URI = 'http://pdbtm.enzim.hu/data/database/'+pdbID[1:3]+'/'+pdbID[:4]+'.trpdb.gz'
pdbID = pdbID[:4]
gz=True
#print URI,pdbID
elif pdbID[4:] == '.pdb' or self.db == "Protein Data Bank (PDB)" :
pdbID = pdbID[:4]
URI = self.baseURI + pdbID
elif pdbID[4:] == '.opm' or self.db == "Orientations of Proteins in Membranes (OPM)" :
pdbID = pdbID[:4]
URI = 'http://opm.phar.umich.edu/pdb/'+pdbID[:4]+'.pdb'
elif pdbID[4:] == '.cif' or self.db == "Crystallographic Information Framework (CIF)":
pdbID = pdbID[:4]
URI = 'http://www.rcsb.org/pdb/files/'+pdbID[:4]+'.cif'
ext = ".cif"
elif pdbID[4:] == '.pqs' or self.db == "PQS":
pdbID = pdbID[:4]
URI ='ftp://ftp.ebi.ac.uk/pub/databases/msd/pqs/macmol/'+pdbID[:4]+'.mmol'
ext = '.mmol'
else : #==4 ?
URI = self.baseURI + pdbID
if pdbID:
#pdbID
if self.rcFolder is not None:
dirnames = os.listdir(self.rcFolder)
else:
dirnames = []
#checks in pdb cache before searching in rcsb.org.
if "pdbcache" in dirnames:
#forceit : even if in pdbcache use the web pdb file
filenames = os.listdir(self.rcFolder+os.sep+'pdbcache')
if pdbID+ext in filenames and not self.forceIt:
tmpFileName = self.rcFolder + os.sep +"pdbcache"+os.sep+pdbID+ext
mols = self.vf.readMolecule(tmpFileName, log=0)
if hasattr(self.vf, 'recentFiles'):
self.vf.recentFiles.add(os.path.abspath(tmpFileName), 'readMolecule')
return mols
try:
#print "ok try urllib open", URI
#but first check it ...
import WebServices
test = WebServices.checkURL(URI)
if test :
fURL = urllib.urlopen(URI)
else :
print "didn't exist try another ID"
return None
except Exception, inst:
print inst
return None
#if URL != "Default" or fURL.headers['content-type'] =='application/download':
if self.rcFolder is not None:
if "pdbcache" not in dirnames:
curdir = os.getcwd()
os.mkdir(self.rcFolder + os.sep +"pdbcache")
#check if gzipped file...
tmpFileName = self.rcFolder + os.sep +"pdbcache"+os.sep+pdbID+ext
if gz :
tmpFileName = self.rcFolder + os.sep +"pdbcache"+os.sep+pdbID+ext+'.gz'
tmpFile = open(tmpFileName,'w')
tmpFile.write(fURL.read())
tmpFile.close()
if gz :
print "ok gunzip"
out = self.rcFolder + os.sep +"pdbcache"+os.sep+pdbID+ext
gunzip(tmpFileName, out)
tmpFileName = out
mols = self.vf.readMolecule(tmpFileName, log=0)
if hasattr(self.vf, 'recentFiles'):
self.vf.recentFiles.add(os.path.abspath(tmpFileName), 'readMolecule')
return mols
#else:
# self.message_box()
def hide(self, event=None):
if self.root:
self.root.withdraw()
def chooseDB(self,value):
self.db = value#self.fetchmenu.getcurselection()
def buildFormDescr(self, formName):
self.db=""
self.fetchmenu = None
if formName == "Fetch":
self.ifd = ifd = InputFormDescr(title="Fetch PDB")
ifd.append({'name': 'fetch',
'label_text': 'Fetch',
'widgetType':Pmw.OptionMenu,
'variable': self.fetchmenu,
'wcfg':{'labelpos':'w','label_text':"choose:",
#'menubutton_width':10,
'items': ['Protein Data Bank (PDB)','Crystallographic Information Framework (CIF)','Orientations of Proteins in Membranes (OPM)','Protein Data Bank of Transmembrane Proteins (TMPDB)'],
'command': self.chooseDB},
'gridcfg': {'sticky':'w','columnspan':2}})
ifd.append({'name':"pdbID",
'widgetType':Pmw.EntryField,
'tooltip':'PDB ID is 4-character code (e.g. 1crn)',
'wcfg':{'labelpos':'w','label_text':" ID:",
'entry_width':1,
'validate':{'validator':'alphanumeric',
'min':4, 'max':4, 'minstrict':False
},
'command':self.onEnter,
},
'gridcfg':{'columnspan':2}
})
# ifd.append({'name':"keyword",
# 'widgetType':Pmw.EntryField,
# 'tooltip':'Keyword are Searched Using RCSB.ORG Search Engine',
# 'wcfg':{'labelpos':'w','label_text':"Keyword:",
# 'entry_width':1,
#
# },
# 'gridcfg':{'columnspan':2}
# })
ifd.append({'name':"URL",
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'w','label_text':" URL:",
'entry_width':1,
},
'gridcfg':{'columnspan':2}
})
ifd.append({'name':'PDBCachedir',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Clear Cache Directory',
'command':self.clearPDBCache},
'gridcfg':{'sticky':'we', 'row':4, 'column':0, 'columnspan':2}})
return ifd
def initFunc(self, foo):
if self.vf.hasGui:
self.vf.GUI.ROOT.after(1, self.focus)
def focus(self):
self.ifd.entryByName['pdbID']['widget'].component('entry').focus_set()
def onEnter(self):
self.ifd.form.OK_cb()
self.dismiss_cb()
def guiCallback(self, **kw):
if hasattr(self,"root"):
if self.root!=None:
self.root.withdraw()
if not self.getPDBCachedir() \
and self.rcFolder is not None:
os.mkdir(self.rcFolder+os.sep+'pdbcache')
val = self.showForm('Fetch', force=1, initFunc=self.initFunc,
cancelCfg={'text':'Cancel',
'command':self.dismiss_cb},
okCfg={'text':'OK',
'command':self.dismiss_cb})
if val:
self.vf.GUI.ROOT.config(cursor='watch')
# if val[ "keyword"]:
# from mglutil.gui.BasicWidgets.Tk.multiListbox import MultiListbox
# self.root = Tkinter.Toplevel()
# self.root.title("Select PDB file")
# self.root.protocol("WM_DELETE_WINDOW", self.hide)
# self.PanedWindow = Tkinter.PanedWindow(self.root, handlepad=0,
# handlesize=0,
# orient=Tkinter.VERTICAL,
# bd=1,height=2*self.height,width=self.width
# )
#
# self.PanedWindow.pack(fill=Tkinter.BOTH, expand=1)
# self.mlb = MultiListbox(self.PanedWindow, ((' PDB ID', 9),
# ('Information ', 20)),
#
# hull_height = 2*self.height,
# usehullsize = 1,
# hull_width = self.width)
#
# self.mlb.pack(expand=Tkinter.NO, fill=Tkinter.X)
# self.find_list(val["keyword"])
# if len(self.listmols)==0:
# self.hide()
# self.message_box()
# return
# for m,info in zip(self.listmols,self.information):
# mol_name = m
# self.mlb.insert(Tkinter.END, (m,info))
# self.PanedWindow.add(self.mlb)
# self.ok_b = Tkinter.Button(self.root, text="Load",
# command=self.ok,width=20)
# self.ok_b.pack(fill=Tkinter.X,side = "left")
# self.close_b = Tkinter.Button(self.root, text=" Dismiss ",
# command=self.hide,width=20)
# self.close_b.pack(fill=Tkinter.X,side = "left")
if val['pdbID']:
if len(val['pdbID']) != 4:
txt = val['pdbID'] + 'is not a valid PDB ID\n'
txt += "Please enter 4-character code"
showinfo(message = txt)
self.guiCallback()
return
if val['URL']:
self.vf.GUI.ROOT.config(cursor= '')
self.doitWrapper(URL=val['URL'])
else:
self.vf.GUI.ROOT.config(cursor= '')
self.doitWrapper(val['pdbID'], **kw)
def getPDBCachedir(self):
from mglutil.util.packageFilePath import getResourceFolderWithVersion
rcFolder = getResourceFolderWithVersion()
if rcFolder is not None \
and os.path.exists(self.rcFolder+os.sep+'pdbcache'):
dirname = self.rcFolder+os.sep+'pdbcache'
return dirname
else:
return None
def clearPDBCache(self):
dirname = self.getPDBCachedir()
if dirname and os.path.exists(dirname):
filenames = os.listdir(dirname)
for f in filenames:
os.remove(dirname+os.sep+f)
def dismiss_cb(self):
if not self.cmdForms.has_key('FetchPDB'): return
f = self.cmdForms['FetchPDB']
if f.root.winfo_ismapped():
f.root.withdraw()
f.releaseFocus()
def ok(self):
selection = self.mlb.curselection()
self.doitWrapper(self.listmols[eval(selection[0])])
def validateUserPref(self, value):
try:
val = int(value)
if val >-1:
return 1
else:
return 0
except:
return 0
def userPref_cb(self, name, old, new):
if self.vf.hasGui:
self.vf.GUI.ROOT.after_idle(self.checkCache)
def checkCache(self, threshold = 1024*1024):
size = self.getCacheSize()
maxSize = self.vf.userpref['PDB Cache Storage (MB)']['value']
if size > maxSize:
folder = self.getPDBCachedir()
if not folder: return
folder_size = 0
for (path, dirs, files) in os.walk(folder):
for file in files:
filename = os.path.join(path, file)
fileSize = os.path.getsize(filename)
if fileSize > threshold:
os.remove(filename)
else:
folder_size += os.path.getsize(filename)
if (folder_size/(1024*1024.0)) > maxSize:
self.checkCache(threshold = threshold/2.)
def getCacheSize(self):
# pick a folder you have ...
folder = self.getPDBCachedir()
if not folder: return
folder_size = 0
for (path, dirs, files) in os.walk(folder):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
return (folder_size/(1024*1024.0))
from Pmv.fileCommandsGUI import fetchGUI
class ReadPmvSession(MVCommand):
"""Reads Full Pmv Session
\nPackage : Pmv
\nModule : fileCommands
\nClass : ReadPmvSession
\nCommand : readPmvSession
\nSynopsis:\n
mols <- readPmvSession(path)
"""
def guiCallback(self, **kw):
self.fileBrowserTitle ="Read Session:"
files = self.vf.askFileOpen([
('Pmv Session files', '*.psf'),
('All Files', '*.*')], title="Read Pmv Session:",
multiple=True)
if files is None:
return None
for file in files:
self.doitWrapper(file, **kw)
def doit(self, file):
self.vf.readFullSession(file)
ReadPmvSessionGUI = CommandGUI()
ReadPmvSessionGUI.addMenuCommand('menuRoot', 'File', 'Read Session', after = "Read Molecule")
class ReadSourceMolecule(MVCommand):
"""Reads Molecule or Python script
\nPackage : Pmv
\nModule : fileCommands
\nClass : ReadSourceMolecule
\nCommand : readSourceMolecule
\nSynopsis:\n
mols <- readSourceMolecule(path)
"""
def guiCallback(self, event, **kw):
self.fileTypes =[(
'All supported formats',
'*.psf *.cif *.mol2 *.pdb *.pqr *.pdbq *.pdbqs *.pdbqt *.gro *.py', )]
self.fileTypes += [
('Pmv Session files', '*.psf'),
('PDB files', '*.pdb'),
('MEAD files', '*.pqr'),('MOL2 files', '*.mol2'),
('AutoDock files (pdbq)', '*.pdbq'),
('AutoDock files (pdbqs)', '*.pdbqs'),
('AutoDock files (pdbqt)', '*.pdbqt'),
('Gromacs files (gro)', '*.gro'),
]
self.parserToExt = {'PDB':'.pdb', 'PDBQ':'.pdbq',
'PDBQS':'.pdbqs', 'PDBQT':'.pdbqt',
'MOL2':'.mol2',
'PQR':'.pqr',
'GRO':'.gro',
}
self.fileTypes += [('MMCIF files', '*.cif'),]
self.parserToExt['CIF'] = '.cif'
#self.fileTypes += [('All files', '*')]
self.fileBrowserTitle ="Read Molecule:"
files = self.vf.askFileOpen(types=self.fileTypes+[
('Python scripts', '*.py'),
('Resource file','*.rc'),
('All Files', '*.*')], title="Read Molecule or Python Script:",
multiple=True)
if files is None:
return None
for file in files:
self.doitWrapper(file, **kw)
def doit(self, file):
ext = os.path.splitext(file)[1].lower()
if ext in ['.py','.rc']:
self.vf.source(file, log=0)
elif ext == ".psf":
# Load Pmv session file
self.vf.readFullSession(file)
else:
self.vf.readMolecule(file, log=0)
from Pmv.fileCommandsGUI import ReadSourceMoleculeGUI
commandList = [
{'name':'writePDB', 'cmd':PDBWriter(), 'gui':PDBWriterGUI },
{'name':'writePDBQ', 'cmd':PDBQWriter(), 'gui':PDBQWriterGUI },
{'name':'writePDBQT', 'cmd':PDBQTWriter(), 'gui':PDBQTWriterGUI },
{'name':'writePDBQS', 'cmd':PDBQSWriter(), 'gui':PDBQSWriterGUI },
{'name':'writeMMCIF', 'cmd':SaveMMCIF(), 'gui':SaveMMCIFGUI },
{'name':'writePQR', 'cmd':PQRWriter(), 'gui':PQRWriterGUI },
{'name':'readPDB', 'cmd':PDBReader(), 'gui':None },
{'name':'readGRO', 'cmd':GROReader(), 'gui':None },
{'name':'readMolecule', 'cmd':MoleculeReader(), 'gui':MoleculeReaderGUI},
{'name':'readPmvSession', 'cmd':ReadPmvSession(), 'gui':ReadPmvSessionGUI},
{'name':'fetch', 'cmd': fetch(), 'gui': fetchGUI},
{'name':'readPDBQ', 'cmd':PDBQReader(), 'gui':None },
{'name':'readPDBQS', 'cmd':PDBQSReader(), 'gui':None },
{'name':'readPDBQT', 'cmd':PDBQTReader(), 'gui':None },
{'name':'readPQR', 'cmd':PQRReader(), 'gui':None },
{'name':'readF2D', 'cmd':F2DReader(), 'gui':None },
{'name':'readMOL2', 'cmd': MOL2Reader(), 'gui': None },
{'name':'readMMCIF', 'cmd':MMCIFReader(), 'gui':None},
{'name':'writeVRML2', 'cmd':VRML2Writer(), 'gui': VRML2WriterGUI},
{'name':'writeSTL', 'cmd':STLWriter(), 'gui': STLWriterGUI},
{'name':'readSourceMolecule', 'cmd':ReadSourceMolecule(), 'gui': ReadSourceMoleculeGUI}
]
def gunzip(gzpath, path):
import gzip
gzf = gzip.open(gzpath)
f = open(path, 'wb')
f.write(gzf.read())
f.close()
gzf.close()
def initModule(viewer):
for dict in commandList:
viewer.addCommand( dict['cmd'], dict['name'], dict['gui'])
```
#### File: MGLToolsPckgs/Pmv/hbondCommands.py
```python
from ViewerFramework.VFCommand import CommandGUI
from Pmv.moleculeViewer import AddAtomsEvent
from mglutil.gui.BasicWidgets.Tk.colorWidgets import ColorChooser
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.util.callback import CallBackFunction
from mglutil.gui.BasicWidgets.Tk.customizedWidgets \
import ExtendedSliderWidget, ListChooser
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
from mglutil.util.misc import ensureFontCase
from Pmv.mvCommand import MVCommand, MVAtomICOM, MVBondICOM
from Pmv.measureCommands import MeasureAtomCommand
from MolKit.molecule import Atom, AtomSet, Bond
from MolKit.molecule import BondSet, HydrogenBond, HydrogenBondSet
from MolKit.distanceSelector import DistanceSelector
from MolKit.hydrogenBondBuilder import HydrogenBondBuilder
from MolKit.pdbWriter import PdbWriter
from DejaVu.Geom import Geom
from DejaVu.Spheres import Spheres
from DejaVu.Points import CrossSet
from DejaVu.Cylinders import Cylinders
from DejaVu.spline import DialASpline, SplineObject
from DejaVu.GleObjects import GleExtrude, GleObject
from DejaVu.Shapes import Shape2D, Triangle2D, Circle2D, Rectangle2D,\
Square2D, Ellipse2D
from Pmv.stringSelectorGUI import StringSelectorGUI
from PyBabel.util import vec3
import Tkinter, numpy.oldnumeric as Numeric, math, string, os
from string import strip, split
from types import StringType
from opengltk.OpenGL import GL
from DejaVu.glfLabels import GlfLabels
def check_hbond_geoms(VFGUI):
hbond_geoms_list = VFGUI.VIEWER.findGeomsByName('hbond_geoms')
if hbond_geoms_list==[]:
hbond_geoms = Geom("hbond_geoms", shape=(0,0), protected=True)
VFGUI.VIEWER.AddObject(hbond_geoms, parent=VFGUI.miscGeom)
hbond_geoms_list = [hbond_geoms]
return hbond_geoms_list[0]
# lists of babel_types for donor-acceptor
# derived from MacDonald + Thornton
# 'Atlas of Side-Chain + Main-Chain Hydrogen Bonding'
# plus sp2Acceptor Nam
sp2Donors = ['Nam', 'Ng+', 'Npl']
sp3Donors = ['N3+', 'O3','S3']
allDonors = []
allDonors.extend(sp2Donors)
allDonors.extend(sp3Donors)
#added Nam because of bdna cytidine N3
#NB: Npl cannot be an acceptor if the sum of its bonds' bondOrder>2
sp2Acceptors = ['O2', 'O-', 'Npl', 'Nam']
sp3Acceptors = ['S3', 'O3']
allAcceptors = []
allAcceptors.extend(sp2Acceptors)
allAcceptors.extend(sp3Acceptors)
a_allAcceptors = []
for n in allAcceptors:
a_allAcceptors.append('a'+n)
def dist(c1, c2):
d = Numeric.array(c2) - Numeric.array(c1)
ans = math.sqrt(Numeric.sum(d*d))
return round(ans, 3)
def getAngle(ac, hat, don ):
acCoords = getTransformedCoords(ac)
hCoords = getTransformedCoords(hat)
dCoords = getTransformedCoords(don)
pt1 = Numeric.array(acCoords, 'f')
pt2 = Numeric.array(hCoords, 'f')
pt3 = Numeric.array(dCoords, 'f')
#pt1 = Numeric.array(ac.coords, 'f')
#pt2 = Numeric.array(hat.coords, 'f')
#pt3 = Numeric.array(don.coords, 'f')
v1 = Numeric.array(pt1 - pt2)
v2 = Numeric.array(pt3 - pt2)
dist1 = math.sqrt(Numeric.sum(v1*v1))
dist2 = math.sqrt(Numeric.sum(v2*v2))
sca = Numeric.dot(v1, v2)/(dist1*dist2)
if sca>1.0:
sca = 1.0
elif sca<-1.0:
sca = -1.0
ang = math.acos(sca)*180./math.pi
return round(ang, 5)
def applyTransformation(pt, mat):
pth = [pt[0], pt[1], pt[2], 1.0]
return Numeric.dot(mat, pth)[:3]
def getTransformedCoords(atom):
# when there is no viewer, the geomContainer is None
if atom.top.geomContainer is None:
return atom.coords
g = atom.top.geomContainer.geoms['master']
c = applyTransformation(atom.coords, g.GetMatrix(g))
return c.astype('f')
class GetHydrogenBondDonors(MVCommand):
"""This class allows user to get AtomSets of sp2 hydridized and sp3 hybridized hydrogenBond Donors able.
\nPackage : Pmv
\nModule : bondsCommands
\nClass : GetHydrogenBondDonors
\nCommand :getHBDonors
\nSynopsis:\n
sp2Donors, sp3Donors <- getHBDonors(nodes, donorList, **kw)
\nRequired Arguments:\n
nodes ---
donorList ---
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('typeAtoms'):
self.vf.loadCommand('editCommands', 'typeAtoms', 'Pmv',
topCommand=0)
def __call__(self, nodes, donorList=allDonors,**kw):
"""sp2Donors, sp3Donors <- getHBDonors(nodes, donorList, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
try:
ats.babel_type
except AttributeError:
tops = ats.top.uniq()
for t in tops:
self.vf.typeAtoms(t.allAtoms, topCommand=0)
return apply(self.doitWrapper, (ats, donorList), kw)
def checkForPossibleH(self, ats, blen):
#check that if at has all bonds, at least one is to a hydrogen
# have to do this by element??
probAts = AtomSet(ats.get(lambda x, blen=blen: len(x.bonds)==blen))
#probOAts = ats.get(lambda x, blen=blen: len(x.bonds)==blen)
#probSAts = ats.get(lambda x, blen=blen: len(x.bonds)==blen)
if probAts:
rAts = AtomSet([])
for at in probAts:
if not len(at.findHydrogens()):
rAts.append(at)
if len(rAts):
ats = ats.subtract(rAts)
return ats
def doit(self, ats, donorList):
#getHBDonors
sp2 = []
sp3 = []
for item in sp2Donors:
if item in donorList: sp2.append(item)
for item in sp3Donors:
if item in donorList: sp3.append(item)
dAts2 = ats.get(lambda x, l=sp2: x.babel_type in l)
if not dAts2: dAts2=AtomSet([])
else:
dAts2 = self.checkForPossibleH(dAts2, 3)
dAts3 = ats.get(lambda x, l=sp3: x.babel_type in l)
if not dAts3: dAts3=AtomSet([])
else: dAts3 = self.checkForPossibleH(dAts3, 4)
return dAts2, dAts3
class GetHydrogenBondAcceptors(MVCommand):
"""This class allows user to get AtomSets of sp2 hydridized and sp3 hybridized
hydrogenBond Acceptors.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : GetHydrogenBondEnergies
\nCommand : getHBondEnergies
\nSynopsis:\n
sp2Acceptors, sp3Acceptors <- getHBAcceptors(nodes, acceptorList, **kw)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('typeAtoms'):
self.vf.loadCommand('editCommands', 'typeAtoms', 'Pmv',
topCommand=0)
def __call__(self, nodes, acceptorList=allAcceptors,**kw):
"""sp2Acceptors, sp3Acceptors <- getHBAcceptors(nodes, acceptorList, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
#no way to know if typeBonds has been called on each molecule!
try:
ats._bndtyped
except:
tops = ats.top.uniq()
for t in tops:
self.vf.typeBonds(t.allAtoms, topCommand=0)
return apply(self.doitWrapper, (ats, acceptorList), kw)
def filterAcceptors(self, accAts):
ntypes = ['Npl', 'Nam']
npls = accAts.get(lambda x, ntypes=ntypes: x.babel_type=='Npl')
nams = accAts.get(lambda x, ntypes=ntypes: x.babel_type=='Nam')
#nAts = accAts.get(lambda x, ntypes=ntypes: x.babel_type in ntypes)
restAts = accAts.get(lambda x, ntypes=ntypes: x.babel_type not in ntypes)
if not restAts: restAts = AtomSet([])
#if nAts:
if npls:
#for at in nAts:
for at in npls:
s = 0
for b in at.bonds:
if b.bondOrder=='aromatic':
s = s + 2
else: s = s + b.bondOrder
#if s<3:
#apparently this is wrong
if s<4:
restAts.append(at)
if nams:
#for at in nAts:
for at in nams:
s = 0
for b in at.bonds:
if b.bondOrder=='aromatic':
s = s + 2
else: s = s + b.bondOrder
#s = s + b.bondOrder
if s<3:
restAts.append(at)
return restAts
def doit(self, ats, acceptorList):
#getHBAcceptors
sp2 = []
sp3 = []
for item in sp2Acceptors:
if item in acceptorList: sp2.append(item)
for item in sp3Acceptors:
if item in acceptorList: sp3.append(item)
dAts2 = AtomSet(ats.get(lambda x, l=sp2: x.babel_type in l))
if dAts2:
dAts2 = self.filterAcceptors(dAts2)
dAts3 = AtomSet(ats.get(lambda x, l=sp3: x.babel_type in l))
return dAts2, dAts3
class GetHydrogenBondEnergies(MVCommand):
"""This class allows user to get a list of energies of HydrogenBonds. For this calculation, the bond must have a hydrogen atom AND it must know its type.
Energy calculation based on "Protein Flexibility and dynamics using constraint
theory", J. Molecular Graphics and Modelling 19, 60-69, 2001. <NAME>, <NAME>, <NAME>, <NAME> and <NAME>.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : GetHydrogenBondEnergies
\nCommand : getHBondEnergies
\nSynopsis:\n
[energies] <- getHBondEnergies(nodes, **kw)
\nRequired Arguments:\n
nodes --- TreeNodeSet holding the current selection
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
self.vf.loadModule('measureCommands', 'Pmv', log=0)
if not self.vf.commands.has_key('typeAtoms'):
self.vf.loadCommand('editCommands', 'typeAtoms', 'Pmv',
topCommand=0, log=0)
def __call__(self, nodes, **kw):
"""[energies] <- getHBondEnergies(nodes, **kw)
\nnodes --- TreeNodeSet holding the current selection
"""
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
hats = AtomSet([])
for at in ats:
if hasattr(at, 'hbonds'): hats.append(at)
if not len(hats):
self.warningMsg('no hbonds in specified nodes')
return 'ERROR'
return apply(self.doitWrapper, (hats,), kw)
def getEnergy(self, b):
accAt = b.accAt
b0 = accAt.bonds[0]
acN = b0.atom1
if id(acN)==id(accAt): acN = b0.atom2
b.acN = acN
#b.acN = b.accAt.bonds[0].neighborAtom(b.accAt)
if b.dlen is None:
b.dlen = dist(getTransformedCoords(b.donAt),
getTransformedCoords(b.accAt))
#b.dlen = dist(b.donAt.coords, b.accAt.coords)
r = 2.8/b.dlen
if b.phi is None: b.phi = self.vf.measureAngle(b.hAt, b.accAt,
acN, topCommand=0)
if b.theta is None: b.theta = self.vf.measureAngle(b.donAt, b.hAt,
b.accAt, topCommand=0)
b.gamma = self.vf.measureTorsion(b.donAt, b.hAt, b.accAt,
acN, topCommand=0)
#make all angles into radians
theta = b.theta * math.pi/180.
newAngle = math.pi - theta
gamma = b.gamma * math.pi/180.
phi = b.phi * math.pi/180.
n = 109.5*math.pi/180.
if b.type is None:
#get # of donAt+# of accAt
try:
b.donAt.babel_type
b.accAt.babel_type
except AttributeError:
b_ats = AtomSet([b.donAt, b.accAt])
tops = b_ats.top.uniq()
for t in tops:
self.vf.typeAtoms(t.allAtoms, topCommand=0)
if b.donAt.babel_type in sp2Donors:
d1=20
else:
d1=30
if b.accAt.babel_type in sp2Acceptors:
d2=2
else:
d2=3
b.type = d1+d2
if b.type==33:
f = (math.cos(theta)**2)*\
(math.e**(-(newAngle)**6))*(math.cos(phi-n)**2)
elif b.type==32:
f = (math.cos(theta)**2)*\
(math.e**(-(newAngle)**6))*(math.cos(phi)**2)
elif b.type==23:
f = ((math.cos(theta)**2)*\
(math.e**(-(newAngle)**6)))**2
else:
f = (math.cos(theta)**2)*\
(math.e**(-(newAngle)**6))*(math.cos(max(theta, gamma))**2)
newVal = 8.*(5.*(r**12) - 6.*(r**10))*f
b.energy = round(newVal, 3)
return b.energy
def doit(self, hats):
#getHBondEnergies
energyList = []
hbonds = hats.hbonds
#SHOULD hbonds be checked for type??? HERE???????
for b in hbonds:
if b.energy:
energyList.append(b.energy)
elif b.hAt is None:
energyList.append(None)
else:
energyList.append(self.getEnergy(b))
#print 'returning ', len(energyList), ' hbond energies: ', energyList
return energyList
class ShowHBDonorsAcceptors(MVCommand):
"""This class allows user to show AtomSets of HydrogenBond donors and acceptors.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : ShowHBDonorsAcceptors
\nCommand : showHBDA
\nSynopsis:\n
None <- showHBDA(dnodes, anodes, donorList, acceptorList, **kw)
"""
def onAddCmdToViewer(self):
self.vf.loadModule('editCommands', 'Pmv', log=0)
self.vf.loadCommand('interactiveCommands','setICOM', 'Pmv', log=0)
#setup geoms
#miscGeom = self.vf.GUI.miscGeom
self.masterGeom = Geom('hbondDonorAcceptorGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
if self.vf.hasGui:
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
self.hbdonor2=CrossSet('hbSP2Donors',
materials=((0.,1.,1.),), offset=0.4, lineWidth=2,
inheritMaterial=0, protected=True)
self.hbdonor2.Set(visible=1, tagModified=False)
self.hbdonor2.pickable = 0
self.hbdonor3=CrossSet('hbSP3Donors',
materials=((0.,.3,1.),), offset=0.4, lineWidth=2,
inheritMaterial=0, protected=True)
self.hbacceptor2=Spheres('hbSP2Acceptors', shape=(0,3),
radii=0.2, quality=15, materials=((1.,.8,0.),), inheritMaterial=0, protected=True)
self.hbacceptor3=Spheres('hbSP3Acceptors', shape=(0,3),
radii=0.2, quality=15, materials=((1.,.2,0.),), inheritMaterial=0, protected=True)
for item in [self.hbdonor2, self.hbdonor3, self.hbacceptor2,\
self.hbacceptor3]:
item.Set(visible=1, tagModified=False)
item.pickable = 0
if self.vf.hasGui:
self.vf.GUI.VIEWER.AddObject(item, parent=self.masterGeom)
#setup Tkinter variables
varNames = ['hideDSel', 'N3', 'O3','S3','Nam', 'Ng', 'Npl',\
'hideASel', 'aS3', 'aO3', 'aO2', 'aO', 'aNpl',
'aNam', 'sp2D', 'sp3D', 'sp2A', 'sp3A','useSelection']
for n in varNames:
exec('self.'+n+'=Tkinter.IntVar()')
exec('self.'+n+'.set(1)')
self.showDTypeSel = Tkinter.IntVar()
self.showATypeSel = Tkinter.IntVar()
def __call__(self, dnodes, anodes, donorList=allDonors,
acceptorList=allAcceptors, **kw):
"""None <- showHBDA(dnodes, anodes, donorList, acceptorList, **kw) """
dnodes = self.vf.expandNodes(dnodes)
donats = dnodes.findType(Atom)
anodes = self.vf.expandNodes(anodes)
acats = anodes.findType(Atom)
if not (len(donats) or len(acats)): return 'ERROR'
apply(self.doitWrapper, (donats, acats, donorList, acceptorList), kw)
def doit(self, donats, acats, donorList, acceptorList):
#showHBDA
if len(donats):
dAts2, dAts3 = self.vf.getHBDonors(donats,
donorList=donorList, topCommand=0)
msg = ''
if dAts2:
newVerts = []
for at in dAts2:
newVerts.append(getTransformedCoords(at).tolist())
self.hbdonor2.Set(vertices=newVerts, visible=1,
tagModified=False)
#self.hbdonor2.Set(vertices = dAts2.coords, visible=1,
# tagModified=False)
else:
msg = msg + 'no sp2 donors found '
dAts2 = AtomSet([])
self.hbdonor2.Set(vertices=[], tagModified=False)
if dAts3:
newVerts = []
for at in dAts3:
newVerts.append(getTransformedCoords(at).tolist())
self.hbdonor3.Set(vertices=newVerts, visible=1,
tagModified=False)
#self.hbdonor3.Set(vertices = dAts3.coords, visible=1, tagModified=False
else:
if len(msg): msg = msg + ';'
msg = msg + 'no sp3 donors found'
dAts3 = AtomSet([])
self.hbdonor3.Set(vertices=[], tagModified=False)
if len(msg):
self.warningMsg(msg)
else:
dAts2 = AtomSet([])
dAts3 = AtomSet([])
self.hbdonor2.Set(vertices=[], tagModified=False)
self.hbdonor3.Set(vertices=[], tagModified=False)
#NOW THE ACCEPTORS:
if len(acats):
acAts2, acAts3 = self.vf.getHBAcceptors(acats,
acceptorList=acceptorList, topCommand=0)
msg = ''
if acAts2:
newVerts = []
for at in acAts2:
newVerts.append(getTransformedCoords(at).tolist())
self.hbacceptor2.Set(vertices = newVerts, visible=1,
tagModified=False)
#self.hbacceptor2.Set(vertices = acAts2.coords, visible=1, tagModified=False)
else:
msg = msg + 'no sp2 acceptors found '
acAts2 = AtomSet([])
self.hbacceptor2.Set(vertices=[], tagModified=False)
if acAts3:
newVerts = []
for at in acAts3:
newVerts.append(getTransformedCoords(at).tolist())
self.hbacceptor3.Set(vertices = newVerts, visible=1,
tagModified=False)
#self.hbacceptor3.Set(vertices = acAts3.coords, visible=1, tagModified=False)
else:
if len(msg): msg = msg + ';'
msg = msg + 'no sp3 acceptors found'
acAts3 = AtomSet([])
self.hbacceptor3.Set(vertices=[], tagModified=False)
if len(msg): self.warningMsg(msg)
else:
acAts2 = AtomSet([])
acAts3 = AtomSet([])
self.hbacceptor2.Set(vertices=[], tagModified=False)
self.hbacceptor3.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
#PUT UP A FORM TO TOGGLE Visibility etc (?)
# show/hide sp2/sp3
# select, save
if not len(dAts2) and not len(dAts3) and not len(acAts2)\
and not len(acAts3):
self.warningMsg('no donors or acceptors found')
return
ifd2 = self.ifd2 = InputFormDescr(title = "Show/Hide Donors and Acceptors")
if len(dAts2):
ifd2.append({'name':'donor2',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'sp2 donors ',
'variable': self.sp2D,
'command': CallBackFunction(self.showGeom,
self.hbdonor2, self.sp2D),
},
'gridcfg':{'sticky':'w'}})
if len(dAts3):
ifd2.append({'name':'donor3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'sp3 donors ',
'variable': self.sp3D,
'command': CallBackFunction(self.showGeom,
self.hbdonor3, self.sp3D),
},
'gridcfg':{'sticky':'w'}})
# 'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
if len(acAts2):
ifd2.append({'name':'accept2',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'sp2 acceptors ',
'variable': self.sp2A,
'command': CallBackFunction(self.showGeom,
self.hbacceptor2, self.sp2A),
},
'gridcfg':{'sticky':'w'}})
if len(acAts3):
ifd2.append({'name':'accept3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'sp3 acceptors ',
'variable': self.sp3A,
'command': CallBackFunction(self.showGeom,
self.hbacceptor3, self.sp3A),
},
'gridcfg':{'sticky':'w'}})
#'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd2.append({'widgetType': Tkinter.Button,
'text':'Select',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'ew' },
'command':CallBackFunction(self.select_cb,dAts2,dAts3,acAts2,acAts3)})
ifd2.append({'widgetType': Tkinter.Button,
'text':'Cancel',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'ew', 'column':1,'row':-1},
'command':self.cancel_cb})
self.form2 = self.vf.getUserInput(self.ifd2, modal=0, blocking=0)
self.form2.root.protocol('WM_DELETE_WINDOW',self.cancel_cb)
def showGeom(self, geom, var, event=None):
geom.Set(visible=var.get(), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def select_cb(self, dAts2, dAts3, acAts2, acAts3):
#NB need to set level to Atom
self.vf.setIcomLevel(Atom)
vars = [self.sp2D, self.sp2D, self.sp2A, self.sp3A]
atL = [dAts2, dAts3, acAts2, acAts3]
for i in range(4):
if vars[i].get() and len(atL[i]):
self.vf.select(atL[i])
def cancel_cb(self, event=None):
for g in [self.hbdonor2, self.hbdonor3, self.hbacceptor2,\
self.hbacceptor3]:
g.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.form2.destroy()
def buildForm(self):
ifd = self.ifd = InputFormDescr(title = "Select nodes + types of donor-acceptors:")
ifd.append({'name':'DkeyLab',
'widgetType':Tkinter.Label,
'text':'For Hydrogen Bonds Donors:',
'gridcfg':{'sticky':'w','columnspan':3}})
ifd.append({'name':'selDRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Use all atoms',
'variable': self.hideDSel,
'value':1,
'command':self.hideDSelector
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selDRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Set atoms to use',
'variable': self.hideDSel,
'value':0,
'command':self.hideDSelector
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name': 'keyDSelector',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(0.,1.,.2),
},
'gridcfg':{'sticky':'we', 'columnspan':2 }})
ifd.append({'name':'limitDTypes',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Limit donor types ',
'variable': self.showDTypeSel,
'command':self.hideDTypes
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'N3+',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'N3+',
'variable': self.N3, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'O3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O3',
'variable': self.O3, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'S3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'S3',
'variable': self.S3, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'Nam',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Nam',
'variable': self.Nam, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'Ng+',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Ng+',
'variable': self.Ng, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'Npl',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Npl',
'variable': self.Npl, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
#now the acceptors
ifd.append({'name':'AkeyLab',
'widgetType':Tkinter.Label,
'text':'For Hydrogen Bonds Acceptors:',
'gridcfg':{'sticky':'w','columnspan':3}})
ifd.append({'name':'selARB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Use all atoms',
'variable': self.hideASel,
'value':1,
'command':self.hideASelector
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selARB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Set atoms to use',
'variable': self.hideASel,
'value':0,
'command':self.hideASelector
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name': 'keyASelector',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(0.,1.,.2),
},
'gridcfg':{'sticky':'we', 'columnspan':2 }})
ifd.append({'name':'limitTypes',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Limit acceptor types ',
'variable': self.showATypeSel,
'command':self.hideATypes
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'aO3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O3',
'variable': self.aO3, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'aS3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'S3',
'variable': self.aS3, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'aO2',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O2',
'variable': self.aO2, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'aO-',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O-',
'variable': self.aO,},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'aNpl',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Npl',
'variable': self.aNpl, },
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name':'aNam',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Nam',
'variable': self.aNam, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'useSelCB',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'select from current selection',
'variable': self.useSelection, },
'gridcfg':{'sticky':'w'}})
ifd.append({'widgetType': Tkinter.Button,
'text':'Ok',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'ew', 'columnspan':2 },
'command':self.Accept_cb})
ifd.append({'widgetType': Tkinter.Button,
'text':'Cancel',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'ew', 'column':2,'row':-1},
'command':self.Close_cb})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
self.hideDSelector()
self.hideDTypes()
self.hideASelector()
self.hideATypes()
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
if not hasattr(self, 'ifd'):
self.buildForm()
def Close_cb(self, event=None):
self.form.destroy()
def Accept_cb(self, event=None):
self.form.withdraw()
dnodesToCheck = self.ifd.entryByName['keyDSelector']['widget'].get()
if not len(dnodesToCheck):
self.warningMsg('no donor atoms specified')
dats = AtomSet([])
else:
dats = dnodesToCheck.findType(Atom)
if self.useSelection.get():
curSel = self.vf.getSelection()
if len(curSel):
curAts = curSel.findType(Atom)
if curAts != self.vf.allAtoms:
dats = curAts.inter(dats)
if dats is None:
msg = 'no specified donor atoms in current selection'
self.warningMsg(msg)
dats = AtomSet([])
else:
msg = 'no current selection'
self.warningMsg(msg)
dats = AtomSet([])
donorList = []
for n in allDonors:
v = self.ifd.entryByName[n]['wcfg']['variable']
if v.get():
donorList.append(n)
if not len(donorList):
self.warningMsg('no donor types selected')
###FIX THIS!!!
anodesToCheck = self.ifd.entryByName['keyASelector']['widget'].get()
if not len(anodesToCheck):
self.warningMsg('no acceptor atoms specified')
acats = AtomSet([])
#return
else:
acats = anodesToCheck.findType(Atom)
if self.useSelection.get():
curSel = self.vf.getSelection()
if len(curSel):
curAts = curSel.findType(Atom)
if curAts != self.vf.allAtoms:
acats = curAts.inter(acats)
if not acats: #NB inter returns empty set!
msg = 'no specified acceptor atoms in current selection'
self.warningMsg(msg)
acats = AtomSet([])
else:
msg = 'no current selection'
self.warningMsg(msg)
acats = AtomSet([])
acceptorList = []
for n in allAcceptors:
name = 'a' + n
v = self.ifd.entryByName[name]['wcfg']['variable']
if v.get():
acceptorList.append(n)
if not len(acceptorList):
self.warningMsg('no acceptor types selected')
if not (len(donorList) or len(acceptorList)):
return
self.Close_cb()
return self.doitWrapper(dats, acats, donorList, acceptorList, topCommand=0)
def hideDSelector(self, event=None):
e = self.ifd.entryByName['keyDSelector']
if self.hideDSel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideDTypes(self, event=None):
for n in allDonors:
e = self.ifd.entryByName[n]
if not self.showDTypeSel.get():
e['wcfg']['variable'].set(1)
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideASelector(self, event=None):
e = self.ifd.entryByName['keyASelector']
if self.hideASel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideATypes(self, event=None):
for n in a_allAcceptors:
e = self.ifd.entryByName[n]
if not self.showATypeSel.get():
e['wcfg']['variable'].set(1)
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
ShowHBDonorsAcceptorsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Show Donors + Acceptors',
'menuCascadeName': 'Build'}
ShowHBDonorsAcceptorsGUI = CommandGUI()
ShowHBDonorsAcceptorsGUI.addMenuCommand('menuRoot','Hydrogen Bonds','Show Donors + Acceptors', cascadeName = 'Build')
class ShowHydrogenBonds(MVCommand):
"""This class allows user to visualize pre-existing HydrogenBonds between
atoms in viewer
\nPackage : Pmv
\nModule : hbondCommands
\nClass : ShowHydrogenBonds
\nCommand : showHBonds
\nSynopsis:\n
None <- showHBonds(nodes, **kw)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
from DejaVu.IndexedPolylines import IndexedPolylines
#from DejaVu.Labels import Labels
miscGeom = self.vf.GUI.miscGeom
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.masterGeom = Geom('HbondsAsLinesGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
self.lines = IndexedPolylines('showHbondLines',
materials = ((0,1,0),), lineWidth=4,
stippleLines=1, inheritMaterial=0, protected=True)
self.labels = GlfLabels(name='showHbondLabs', shape=(0,3),
materials = ((0,1,1),), inheritMaterial=0,
billboard=True, fontStyle='solid',
fontScales=(.3,.3,.3,))
self.labels.font = 'arial1.glf'
self.thetaLabs = GlfLabels(name='hbondThetaLabs', shape=(0,3),
materials = ((1,1,0),), inheritMaterial=0,
billboard=True, fontStyle='solid',
fontScales=(.3,.3,.3,))
self.thetaLabs.font = 'arial1.glf'
self.phiLabs = GlfLabels(name='hbondPhiLabs', shape=(0,3),
materials = ((1,.2,0),), inheritMaterial=0,
billboard=True, fontStyle='solid',
fontScales=(.3,.3,.3,))
self.phiLabs.font = 'arial1.glf'
self.engLabs = GlfLabels(name='hbondELabs', shape=(0,3),
materials = ((1,1,1),), inheritMaterial=0,
billboard=True, fontStyle='solid',
fontScales=(.3,.3,.3,))
self.engLabs.font = 'arial1.glf'
geoms = [self.lines, self.labels, self.thetaLabs,
self.phiLabs, self.engLabs]
for item in geoms:
self.vf.GUI.VIEWER.AddObject(item, parent=self.masterGeom)
self.vf.loadModule('labelCommands', 'Pmv', log=0)
self.showAll = Tkinter.IntVar()
self.showAll.set(1)
self.showDistLabels = Tkinter.IntVar()
self.showDistLabels.set(1)
self.dispTheta = Tkinter.IntVar()
self.dispTheta.set(0)
self.dispPhi = Tkinter.IntVar()
self.dispPhi.set(0)
self.dispEnergy = Tkinter.IntVar()
self.dispEnergy.set(0)
self.dverts = []
self.dlabs = []
self.angVerts = []
self.phi_labs = []
self.theta_labs = []
self.e_labs = []
self.hasDist = 0
self.hasAngles = 0
self.hasEnergies = 0
self.height = None
self.width = None
self.winfo_x = None
self.winfo_y = None
def __call__(self, nodes, **kw):
"""None <- showHBonds(nodes, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes =self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
apply(self.doitWrapper, (ats,), kw)
def reset(self):
self.hasAngles = 0
self.hasEnergies = 0
self.hasDist = 0
self.lines.Set(vertices=[], tagModified=False)
self.labels.Set(vertices=[], tagModified=False)
self.engLabs.Set(vertices=[], tagModified=False)
self.dverts = []
self.dlabs = []
self.angVerts = []
self.phi_labs = []
self.theta_labs = []
self.e_labs = []
def doit(self, ats):
#asLines: ShowHBonds
hbats = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
self.reset()
if not hbats:
self.warningMsg('1:no hydrogen bonds found')
return 'ERROR'
hats = AtomSet(hbats.get(lambda x: x.element=='H'))
atNames = []
if hats:
for h in hats:
atNames.append((h.full_name(), None))
else:
hats = AtomSet([])
bnds = []
for at in hbats:
bnds.extend(at.hbonds)
bndD = {}
for b in bnds:
bndD[b] = 0
hbnds2 = bndD.keys()
hbnds2.sort()
for b in hbnds2:
atNames.append((b.donAt.full_name(), None))
hats.append(b.donAt)
self.showAllHBonds(hats)
if not hasattr(self, 'ifd'):
ifd = self.ifd=InputFormDescr(title = 'Hydrogen Bonds:')
ifd.append({'name': 'hbondLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': str(len(atNames)) + ' Atoms in hbonds:'},
'gridcfg':{'sticky': 'we', 'columnspan':2}})
ifd.append({'name': 'atsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': atNames,
'mode': 'single',
'title': '',
'command': CallBackFunction(self.showHBondLC, atNames),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'we', 'weight':2,'row':2,
'column':0, 'columnspan':2}})
ifd.append({'name':'showAllBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show All ',
'variable': self.showAll,
'command': CallBackFunction(self.showAllHBonds, \
hats)},
'gridcfg':{'sticky':'we','weight':2}})
ifd.append({'name':'showDistBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show Distances ',
'variable': self.showDistLabels,
'command': self.showDistances},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1,'weight':2}})
ifd.append({'name':'showThetaBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show theta\n(don-h->acc)',
'variable': self.dispTheta,
'command': CallBackFunction(self.showAngles, hats)},
'gridcfg':{'sticky':'we','weight':2}})
ifd.append({'name':'showPhiBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show phi\n(h->acc-accN)',
'variable': self.dispPhi,
'command': CallBackFunction(self.showAngles, hats)},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1,'weight':2}})
ifd.append({'name':'showEnBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show Energy',
'variable': self.dispEnergy,
'command': CallBackFunction(self.showEnergies, hats)},
'gridcfg':{'sticky':'we','weight':2}})
ifd.append({'name':'selAllBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Select All ',
'command': CallBackFunction(self.selAllHBonds, hats)},
'gridcfg':{'sticky':'we','weight':2}})
ifd.append({'name':'closeBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Dismiss',
'command': self.dismiss_cb},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1,'weight':2}})
self.form = self.vf.getUserInput(ifd, modal=0, blocking=0,
width=350, height=350)
self.form.root.protocol('WM_DELETE_WINDOW',self.dismiss_cb)
self.toplevel = self.form.f.master.master
self.toplevel.positionfrom(who='user')
if self.winfo_x is not None and self.winfo_y is not None:
geom = self.width +'x'+ self.height +'+'
geom += self.winfo_x + '+' + self.winfo_y
self.toplevel.geometry(newGeometry=geom)
else:
self.ifd.entryByName['showAllBut']['widget'].config(command= \
CallBackFunction(self.showAllHBonds, hats))
self.ifd.entryByName['showThetaBut']['widget'].config(command= \
CallBackFunction(self.showAngles, hats))
self.ifd.entryByName['showPhiBut']['widget'].config(command= \
CallBackFunction(self.showAngles, hats))
self.ifd.entryByName['showEnBut']['widget'].config(command= \
CallBackFunction(self.showEnergies, hats))
self.ifd.entryByName['selAllBut']['widget'].config(command= \
CallBackFunction(self.selAllHBonds, hats))
if self.winfo_x is not None and self.winfo_y is not None:
geom = self.width +'x'+ self.height +'+'
geom += self.winfo_x + '+' + self.winfo_y
self.toplevel.geometry(newGeometry=geom)
def showHBondLC(self, hats, event=None):
#this caused infinite loop:
if not hasattr(self, 'ifd'):
self.doit(hats)
lb = self.ifd.entryByName['atsLC']['widget'].lb
if lb.curselection() == (): return
self.showAll.set(0)
atName = lb.get(lb.curselection())
ind = int(lb.curselection()[0])
ats = self.vf.Mols.NodesFromName(atName)
at = ats[0]
#to deal with two atoms with the exact same name:
if len(ats)>1:
for a in ats:
if hasattr(a, 'hbonds'):
at = a
break
b = at.hbonds[0]
faces = ((0,1),)
if b.hAt is not None:
lineVerts = (getTransformedCoords(b.hAt).tolist(), getTransformedCoords(b.accAt).tolist())
#lineVerts = (b.hAt.coords, b.accAt.coords)
else:
lineVerts = (getTransformedCoords(b.donAt).tolist(), getTransformedCoords(b.accAt).tolist())
#lineVerts = (b.donAt.coords, b.accAt.coords)
faces = ((0,1),)
if self.hasAngles:
verts = [self.angVerts[ind]]
labs = [self.theta_labs[ind]]
self.thetaLabs.Set(vertices=verts, labels=labs, tagModified=False)
labs = [self.phi_labs[ind]]
self.phiLabs.Set(vertices=verts, labels=labs, tagModified=False)
if self.hasEnergies:
labs = [self.e_labs[ind]]
verts = [self.dverts[ind]]
self.engLabs.Set(vertices=verts,labels=labs,\
visible=self.dispEnergy.get(), tagModified=False)
labelVerts = [self.dverts[ind]]
labelStrs = [self.dlabs[ind]]
self.labels.Set(vertices=labelVerts, labels=labelStrs,
tagModified=False)
self.lines.Set(vertices=lineVerts, type=GL.GL_LINE_STRIP,
faces=faces, freshape=1, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def dismiss_cb(self, event=None, **kw):
#showHBonds
self.lines.Set(vertices=[], tagModified=False)
self.labels.Set(vertices=[], tagModified=False)
self.thetaLabs.Set(vertices=[], tagModified=False)
self.phiLabs.Set(vertices=[], tagModified=False)
self.engLabs.Set(vertices=[], tagModified=False)
try:
self.width = str(self.form.f.master.master.winfo_width())
self.height = str(self.form.f.master.master.winfo_height())
self.winfo_x = str(self.form.f.master.master.winfo_x())
self.winfo_y = str(self.form.f.master.master.winfo_y())
except:
pass
self.vf.GUI.VIEWER.Redraw()
if hasattr(self, 'ifd'):
delattr(self, 'ifd')
if hasattr(self, 'form'):
self.form.destroy()
if hasattr(self, 'palette'):
self.palette.hide()
def showDistances(self, event=None):
self.labels.Set(visible=self.showDistLabels.get(), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def showEnergies(self, hats):
if not self.hasEnergies:
self.buildEnergies(hats)
self.hasEnergies = 1
if not self.showAll.get():
self.showHBondLC(hats)
else:
self.engLabs.Set(labels = self.e_labs, vertices = self.dverts,
visible=self.dispEnergy.get(), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def buildEnergies(self, hats):
#FIX THIS: for some reason, eList is disordered...???
eList = self.vf.getHBondEnergies(hats, topCommand=0)
for hat in hats:
self.e_labs.append(str(hat.hbonds[0].energy))
def showAngles(self, hats, event=None):
if not self.hasAngles:
self.buildAngles(hats)
self.hasAngles = 1
if not self.showAll.get():
self.showHBondLC(hats)
else:
self.thetaLabs.Set(vertices=self.angVerts, labels=self.theta_labs,
tagModified=False)
self.phiLabs.Set(vertices = self.angVerts, labels = self.phi_labs,
tagModified=False)
self.thetaLabs.Set(visible=self.dispTheta.get(), tagModified=False)
self.phiLabs.Set(visible=self.dispPhi.get(), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def buildAngles(self, hats):
#NB: hats are either donAts or hAts
# theta is don-h->acc, phi is h->acc-accN
# calc 1 angle for each closeAt
# hat is h,
if self.hasAngles: return
tlabs = []
plabs = []
verts = []
for hat in hats:
b = hat.hbonds[0]
accAt = b.accAt
donAt = b.donAt
if b.hAt is not None:
ang = getAngle(donAt, hat, accAt)
ang = round(ang, 3)
b.theta = ang
b0 = accAt.bonds[0]
accN = b0.atom1
if id(accN)==id(accAt): accN = b0.atom2
#accN = b.accAt.bonds[0].neighborAtom(b.accAt)
ang = getAngle(hat, accAt, accN)
ang = round(ang, 3)
b.phi = ang
p1=Numeric.array(getTransformedCoords(hat))
p2=Numeric.array(getTransformedCoords(accAt))
#p1=Numeric.array(hat.coords)
#p2=Numeric.array(accAt.coords)
newVert = tuple((p1+p2)/2.0 + .2)
tlabs.append(str(b.theta))
verts.append(newVert)
plabs.append(str(b.phi))
self.thetaLabs.Set(vertices=verts, labels=tlabs, tagModified=False)
self.angVerts = verts
self.theta_labs = tlabs
self.phi_labs = plabs
self.phiLabs.Set(vertices=verts, labels=plabs, tagModified=False)
def setupDisplay(self):
#draw lines between hAts OR donAts and accAts
self.labels.Set(vertices=self.dverts, labels=self.dlabs,
tagModified=False)
self.lines.Set(vertices=self.lineVerts, type=GL.GL_LINE_STRIP,
faces=self.faces, freshape=1, tagModified=False)
if self.hasAngles:
self.thetaLabs.Set(vertices=self.angVerts, labels=self.theta_labs,
tagModified=False)
self.phiLabs.Set(vertices=self.angVerts, labels=self.theta_labs,
tagModified=False)
if self.hasEnergies:
self.engLabs.Set(vertices=self.dverts, labels=self.e_labs,
tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def showAllHBonds(self, hats, event=None):
if not self.showAll.get() and hasattr(self, 'ifd'):
self.showHBondLC(hats)
elif not self.hasDist:
lineVerts = []
faces = []
labelVerts = []
labelStrs = []
dlabelStrs = []
atCtr = 0
for at in hats:
for b in at.hbonds:
dCoords = getTransformedCoords(b.donAt)
aCoords = getTransformedCoords(b.accAt)
if b.hAt is not None:
hCoords = getTransformedCoords(b.hAt)
lineVerts.append(hCoords)
else:
lineVerts.append(dCoords)
lineVerts.append(aCoords)
#lineVerts.append(b.accAt.coords)
faces.append((atCtr, atCtr+1))
#c1 = Numeric.array(at.coords, 'f')
c1 = getTransformedCoords(at)
c3 = aCoords
#c3 = Numeric.array(b.accAt.coords, 'f')
labelVerts.append(tuple((c1 + c3)/2.0))
if b.hAt is not None:
if b.hlen is not None:
labelStrs.append(str(b.hlen))
else:
#d = dist(hCoords,aCoords)
#d=self.vf.measureDistance(b.hAt,b.accAt, topCommand=0)
b.hlen=round(dist(hCoords, aCoords),3)
labelStrs.append(str(b.hlen))
if b.dlen is not None:
dlabelStrs.append(str(b.dlen))
else:
#d = dist(dCoords, aCoords)
##d = dist(b.donAt.coords, b.accAt.coords)
#d=self.vf.measureDistance(b.donAt,b.accAt, topCommand=0)
#b.dlen=round(d,3)
b.dlen=round(dist(dCoords, aCoords) ,3)
dlabelStrs.append(str(b.dlen))
atCtr = atCtr + 2
self.lineVerts = lineVerts
self.faces = faces
self.dverts = labelVerts
if len(labelStrs):
self.dlabs = labelStrs
else:
self.dlabs = dlabelStrs
self.hasDist = 1
self.setupDisplay()
else:
self.setupDisplay()
def selAllHBonds(self, hats, event=None):
self.vf.select(hats)
def guiCallback(self):
#showHbonds
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
sel = self.vf.getSelection()
#put a selector here
if len(sel):
ats = sel.findType(Atom)
apply(self.doitWrapper, (ats,), {})
ShowHydrogenBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'As Lines',
'menuCascadeName': 'Display'}
ShowHydrogenBondsGUI = CommandGUI()
ShowHydrogenBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'As Lines', cascadeName='Display')
class BuildHydrogenBondsGUICommand(MVCommand):
"""This class provides Graphical User Interface to BuildHydrogenBonds which is invoked by it.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : BuildHydrogenBondsGUICommand
\nCommand : buildHydrogenBondsGC
\nSynopsis:\n
None<---buildHydrogenBondsGC(nodes1, nodes2, paramDict, reset=1)
"""
def onAddCmdToViewer(self):
self.showSel = Tkinter.IntVar()
self.resetVar = Tkinter.IntVar()
self.resetVar.set(1)
self.showDef = Tkinter.IntVar()
self.distOnly = Tkinter.IntVar()
self.hideDTypeSel = Tkinter.IntVar()
self.hideATypeSel = Tkinter.IntVar()
self.showTypes = Tkinter.IntVar()
varNames = ['hideDSel', 'N3', 'O3','S3','Nam', 'Ng', 'Npl',\
'hideASel', 'aS3', 'aO3', 'aO2', 'aO', 'aNpl',
'aNam']
for n in varNames:
exec('self.'+n+'=Tkinter.IntVar()')
exec('self.'+n+'.set(1)')
def doit(self, nodes1, nodes2, paramDict, reset=1):
#buildHbondGC
self.hasAngles = 0
atDict = self.vf.buildHBonds(nodes1, nodes2, paramDict, reset)
if not len(atDict.keys()):
self.warningMsg('3:no hydrogen bonds found')
return 'ERROR'
else:
msg = str(len(atDict.keys()))+' hydrogen bonds formed'
self.warningMsg(msg)
#ats = AtomSet(atDict.keys())
#ats.parent.sort()
#self.vf.showHBonds(ats)
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
if not hasattr(self, 'ifd'):
self.buildForm()
else:
self.form.deiconify()
def buildForm(self):
ifd = self.ifd = InputFormDescr(title = "Select nodes + change parameters(optional):")
ifd.append({'name':'keyLab',
'widgetType':Tkinter.Label,
'text':'For Hydrogen Bond detection:',
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Use all atoms',
'variable': self.showSel,
'value':0,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Specify two sets:',
'variable': self.showSel,
'value':1,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name': 'group1',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(0.,1.,.2),
},
'gridcfg':{'sticky':'we', 'columnspan':2 }})
ifd.append({'name': 'group2',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(1.,2.,0.),
},
'gridcfg':{'sticky':'we', 'columnspan':2}})
ifd.append({'name':'typeRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Use all donor-acceptorTypes',
'variable': self.showTypes,
'value':0,
'command':self.hideTypeCBs,
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Limit types:',
'variable': self.showTypes,
'value':1,
'command':self.hideTypeCBs
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name':'limitDTypes',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Limit donor types ',
'variable': self.hideDTypeSel,
'command':self.hideDTypes
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'N3+',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'N3+',
'variable': self.N3, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'O3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O3',
'variable': self.O3, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'S3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'S3',
'variable': self.S3, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'Nam',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Nam',
'variable': self.Nam, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'Ng+',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Ng+',
'variable': self.Ng, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'Npl',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Npl',
'variable': self.Npl, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
#now the acceptors
ifd.append({'name':'limitATypes',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Limit acceptor types ',
'variable': self.hideATypeSel,
'command':self.hideATypes
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'aO3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O3',
'variable': self.aO3, },
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'aS3',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'S3',
'variable': self.aS3, },
'gridcfg':{'sticky':'w','row':-1, 'column':1}})
ifd.append({'name':'aO2',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O2',
'variable': self.aO2, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'aO-',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'O-',
'variable': self.aO,},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'aNpl',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Npl',
'variable': self.aNpl, },
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name':'aNam',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Nam',
'variable': self.aNam, },
'gridcfg':{'sticky':'w','row':-1, 'column':2}})
ifd.append({'name':'distOnly',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Use distance as only criteria',
'variable': self.distOnly,
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'defRB0',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Adjust default hydrogen bond parameters',
'variable': self.showDef,
'command':self.hideDefaults
},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'distCutoff',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'H-Acc Distance Cutoff',
'minval':1.5,'maxval':3.0 ,
'init':2.25,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}})
ifd.append({'name':'distCutoff2',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Donor-Acc Distance Cutoff',
'minval':1.5,'maxval':5.0 ,
'init':3.00,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}})
#min+max theta values for sp2 and for sp3 donors:
ifd.append({ 'name':'d2lab',
'widgetType':Tkinter.Label,
'wcfg':{ 'text': 'sp2 donor-hydrogen-acceptor angle limits:',
'font':(ensureFontCase('helvetica'),12,'bold')},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'d2min',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'min',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':180, 'type':float, 'precision':3,
'value':120,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we'}})
#modified this 10/1 because of 1crn:ILE35NH to THR1:O hbond
ifd.append({'name':'d2max',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'max',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':190, 'type':float, 'precision':3,
'value':180,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
ifd.append({ 'name':'d3lab',
'widgetType':Tkinter.Label,
'wcfg':{ 'text': 'sp3 donor-hydrogen-acceptor angle limits:',
'font':(ensureFontCase('helvetica'),12,'bold')},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'d3min',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'min',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':180, 'type':float, 'precision':3,
'value':120,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'d3max',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'max',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':180, 'type':float, 'precision':3,
'value':180,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
#min+max phi values for sp2 and for sp3 donors:
ifd.append({ 'name':'a2lab',
'widgetType':Tkinter.Label,
'wcfg':{ 'text': 'sp2 donor-acceptor-acceptorN angle limits:',
'font':(ensureFontCase('helvetica'),12,'bold')},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'a2min',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'min',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':90, 'max':180, 'type':float, 'precision':3,
'value':110,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'a2max',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'max',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':180, 'type':float, 'precision':3,
'value':150,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
ifd.append({ 'name':'a3lab',
'widgetType':Tkinter.Label,
'wcfg':{ 'text': 'sp3 donor-acceptor-acceptorN angle limits:',
'font':(ensureFontCase('helvetica'),12,'bold')},
'gridcfg':{'sticky':'w', 'columnspan':2}})
ifd.append({'name':'a3min',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'min',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':90, 'max':180, 'type':float, 'precision':3,
'value':100,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'a3max',
'wtype':ThumbWheel,
'widgetType':ThumbWheel,
'wcfg':{ 'labCfg':{'text':'max',
'font':(ensureFontCase('helvetica'),12,'bold')},
'showLabel':2, 'width':100,
'min':100, 'max':180, 'type':float, 'precision':3,
'value':150,
'showLabel':1,
'continuous':1, 'oneTurn':2, 'wheelPad':2, 'height':20},
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
ifd.append({'name':'resetRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Remove all previous hbonds',
'variable': self.resetVar,
'value':1,
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'resetRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Add to previous hbonds',
'variable': self.resetVar,
'value':0,
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'widgetType': Tkinter.Button,
'text':'Ok',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'we'},
'command':self.Accept_cb})
ifd.append({'widgetType': Tkinter.Button,
'text':'Cancel',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'we', 'column':1,'row':-1},
'command':self.Close_cb})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.Close_cb)
self.hideSelector()
self.hideDefaults()
self.hideDTypes()
self.hideATypes()
self.hideTypeCBs()
self.form.autoSize()
def cleanUpCrossSet(self):
chL = []
for item in self.vf.GUI.VIEWER.rootObject.children:
if isinstance(item, CrossSet) and item.name[:8]=='strSelCr':
chL.append(item)
if len(chL):
for item in chL:
item.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.vf.GUI.VIEWER.RemoveObject(item)
def Close_cb(self, event=None):
#self.cleanUpCrossSet()
self.form.withdraw()
#self.form.destroy()
def hideTypeCBs(self, event=None):
if not self.showTypes.get():
for n in ['limitDTypes', 'limitATypes']:
e = self.ifd.entryByName[n]
e['widget'].grid_forget()
self.hideDTypeSel.set(0)
self.hideDTypes()
self.hideATypeSel.set(0)
self.hideATypes()
#reset all variables to 1 here
varNames = ['N3', 'O3','S3','Nam', 'Ng', 'Npl',\
'aS3', 'aO3', 'aO2', 'aO', 'aNpl', 'aNam']
for n in varNames:
exec('self.'+n+'.set(1)')
else:
for n in ['limitDTypes', 'limitATypes']:
e = self.ifd.entryByName[n]
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideDTypes(self, event=None):
for n in allDonors:
e = self.ifd.entryByName[n]
if not self.hideDTypeSel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideASelector(self, event=None):
e = self.ifd.entryByName['keyASelector']
if self.hideASel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def hideATypes(self, event=None):
for n in a_allAcceptors:
e = self.ifd.entryByName[n]
if not self.hideATypeSel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def Accept_cb(self, event=None):
self.form.withdraw()
if self.showSel.get():
nodesToCheck1 = self.ifd.entryByName['group1']['widget'].get()
nodesToCheck2 = self.ifd.entryByName['group2']['widget'].get()
else:
# user didn't choose to specify two sets:
nodesToCheck1 = nodesToCheck2 = self.vf.getSelection()
#nodesToCheck2 = self.vf.getSelection()
if not len(nodesToCheck1):
self.warningMsg('no atoms in first set')
return
if not len(nodesToCheck2):
self.warningMsg('no atoms in second set')
return
distCutoff = self.ifd.entryByName['distCutoff']['widget'].get()
distCutoff2 = self.ifd.entryByName['distCutoff2']['widget'].get()
d2min = self.ifd.entryByName['d2min']['widget'].get()
d2max = self.ifd.entryByName['d2max']['widget'].get()
d3min = self.ifd.entryByName['d3min']['widget'].get()
d3max = self.ifd.entryByName['d3max']['widget'].get()
a2min = self.ifd.entryByName['a2min']['widget'].get()
a2max = self.ifd.entryByName['a2max']['widget'].get()
a3min = self.ifd.entryByName['a3min']['widget'].get()
a3max = self.ifd.entryByName['a3max']['widget'].get()
if nodesToCheck1[0].__class__!=Atom:
ats1 = nodesToCheck1.findType(Atom)
nodesToCheck1 = ats1
if not self.showSel.get():
nodesToCheck2 = nodesToCheck1
elif nodesToCheck2[0].__class__!=Atom:
ats2 = nodesToCheck2.findType(Atom)
nodesToCheck2 = ats2
donorList = []
for w in allDonors:
if self.ifd.entryByName[w]['wcfg']['variable'].get():
donorList.append(w)
acceptorList = []
for w in a_allAcceptors:
if self.ifd.entryByName[w]['wcfg']['variable'].get():
acceptorList.append(w[1:])
self.Close_cb()
paramDict = {}
paramDict['distCutoff'] = distCutoff
paramDict['distCutoff2'] = distCutoff2
paramDict['d2min'] = d2min
paramDict['d2max'] = d2max
paramDict['d3min'] = d3min
paramDict['d3max'] = d3max
paramDict['a2min'] = a2min
paramDict['a2max'] = a2max
paramDict['a3min'] = a3min
paramDict['a3max'] = a3max
paramDict['distOnly'] = self.distOnly.get()
paramDict['donorTypes'] = donorList
paramDict['acceptorTypes'] = acceptorList
if len(donorList)==0 and len(acceptorList)==0:
self.warningMsg('no donors or acceptors possible')
return 'ERROR'
#print 'donorList=', donorList
#print 'acceptorList=', acceptorList
return self.doitWrapper(nodesToCheck1, nodesToCheck2,
paramDict, reset=self.resetVar.get(), topCommand=0)
def hideSelector(self, event=None):
e = self.ifd.entryByName['group1']
e2 = self.ifd.entryByName['group2']
if not self.showSel.get():
e['widget'].grid_forget()
e2['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
e2['widget'].grid(e2['gridcfg'])
self.form.autoSize()
def hideDefaults(self, event=None):
e = self.ifd.entryByName['distCutoff']
e2 = self.ifd.entryByName['distCutoff2']
if not self.showDef.get():
e['widget'].frame.grid_forget()
e2['widget'].frame.grid_forget()
else:
e['widget'].frame.grid(e['gridcfg'])
e2['widget'].frame.grid(e2['gridcfg'])
wids = ['d2lab', 'd2min', 'd2max', 'd3lab', 'd3min', 'd3max',
'a2lab', 'a2min', 'a2max', 'a3lab', 'a3min', 'a3max']
for item in wids:
e = self.ifd.entryByName[item]
if not self.showDef.get():
e['widget'].grid_forget()
else:
e = self.ifd.entryByName[item]
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
BuildHydrogenBondsGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Set Params + Build',
'menuCascadeName':'Build'}
BuildHydrogenBondsGUICommandGUI = CommandGUI()
BuildHydrogenBondsGUICommandGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds', 'Set Parms + Build', cascadeName = 'Build')
class BuildHydrogenBonds(MVCommand):
"""This command finds hydrogen donor atoms within 2.4*percentCutoff angstrom distance of hydrogen acceptor atoms. It builds and returns a dictionary atDict whose keys are hydrogen atoms (or hydrogenbond donor atoms if there are no hydrogens) and whose values are potential h-bond acceptors and distances to these atoms, respectively
\nPackage : Pmv
\nModule : hbondCommands
\nClass : BuildHydrogenBonds
\nCommand : buildHbonds
\nSynopsis:\n
atDict <- buildHbonds(group1, group2, paramDict, **kw)
\nRequired Arguments:\n
group1 --- atoms\n
group2 --- atoms\n
paramDict --- a dictionary with these keys and default values\n
keywords --\n
distCutoff: 2.25 hydrogen--acceptor distance\n
distCutoff2: 3.00 donor... acceptor distance\n
d2min: 120 <min theta for sp2 hybridized donors>\n
d2max: 180 <max theta for sp2 hybridized donors>\n
d3min: 120 <min theta for sp3 hybridized donors>\n
d3max: 170 <max theta for sp3 hybridized donors>\n
a2min: 120 <min phi for sp2 hybridized donors>\n
a2max: 150 <max phi for sp2 hybridized donors>\n
a3min: 100 <min phi for sp3 hybridized donors>\n
a3max: 150 <max phi for sp3 hybridized donors>\n
donorTypes = allDonors\n
acceptorTypes = allAcceptors\n
reset: remove all previous hbonds\n
"""
def onAddCmdToViewer(self):
self.distSelector = DistanceSelector(return_dist=0)
if not self.vf.commands.has_key('typeAtoms'):
self.vf.loadCommand('editCommands', 'typeAtoms', 'Pmv',
topCommand=0)
def reset(self):
ct = 0
for at in self.vf.allAtoms:
if hasattr(at, 'hbonds'):
for item in at.hbonds:
del item
ct = ct +1
delattr(at, 'hbonds')
#print 'reset: deleted hbonds from ' + str(ct)+ ' atoms '
def doit(self, group1, group2, paramDict, reset):
hb = HydrogenBondBuilder()
atDict = hb.build(group1, group2,reset=reset, paramDict=paramDict)
return atDict
# #buildHbonds
# # two steps:
# # group1 donors v group2 acceptors and group1 acceptors vs group2 donors
# if reset:
# #delattr(group1, 'hbonds')
# #delattr(group2, 'hbonds')
# self.reset()
# atDict = {}
# dict1 = self.buildD(group1, paramDict)
# if group1==group2:
# atD1 =self.process(dict1, dict1, paramDict)
# #print 'len(atD1).keys()=', len(atD1.keys())
# else:
# dict2 = self.buildD(group2, paramDict)
# atD1 = self.process(dict1, dict2, paramDict)
# atD2 = self.process(dict2, dict1, paramDict)
# #print 'len(atD1).keys()=', len(atD1.keys())
# #print 'len(atD2).keys()=', len(atD2.keys())
# #if called with 1 atom could get tuple of two empty dictionaries
# if type(atD1)==type(atDict):
# atDict.update(atD1)
# if group1!=group2 and type(atD2)==type(atDict):
# atDict.update(atD2)
# return atDict
# def buildD(self, ats, paramDict):
# d = {}
# donorTypes = paramDict['donorTypes']
# donor2Ats, donor3Ats = self.vf.getHBDonors(ats,
# donorTypes, topCommand=0)
# d23 = donor2Ats+donor3Ats
# #hAts = ats.get(lambda x, d23=d23: x.element=='H' \
# #and x.bonds[0].neighborAtom(x) in d23)
# hAts = AtomSet(ats.get(lambda x, donorTypes=donorTypes: x.element=='H' \
# and (x.bonds[0].atom1.babel_type in donorTypes\
# or x.bonds[0].atom2.babel_type in donorTypes)))
# d['hAts'] = hAts
# d['donor2Ats'] = donor2Ats
# d['donor3Ats'] = donor3Ats
# acceptor2Ats, acceptor3Ats = self.vf.getHBAcceptors(ats,
# paramDict['acceptorTypes'], topCommand=0)
# d['acceptor2Ats'] = acceptor2Ats
# d['acceptor3Ats'] = acceptor3Ats
# if acceptor2Ats:
# acceptorAts = acceptor2Ats
# if acceptor3Ats:
# acceptorAts = acceptorAts + acceptor3Ats
# elif acceptor3Ats:
# acceptorAts = acceptor3Ats
# else:
# #CHECK THIS: should it be None or AtomSet([])
# acceptorAts = None
# d['acceptorAts'] = acceptorAts
# return d
#
# def getMat(self, ats):
# tops = ats.top.uniq()
# if len(tops)>1:
# self.warningMsg('transformation mat=None:>1 mol in atomset!')
# return None
# g = tops[0].geomContainer.geoms['master']
# return g.GetMatrix(g)
# def process(self, dict1, dict2, paramDict):
# #hAts are keys, aceptorAts are checks
# hAts = dict1['hAts']
# tAts = hAts
# dist = paramDict['distCutoff']
# distOnly = paramDict['distOnly']
# if not hAts:
# #then use donors and a different distance
# tAts = dict1['donor2Ats'] + dict1['donor3Ats']
# dist = paramDict['distCutoff2']
#
# acceptorAts = dict2['acceptorAts']
# if not acceptorAts or not tAts: #6/14/2004
# return {}, {}
# #call distanceSelector on two groups of atoms with dist
# keyMat = self.getMat(tAts)
# checkMat = self.getMat(acceptorAts)
# atDict = self.distSelector.select(tAts, acceptorAts, dist,
# keyMat=keyMat, checkMat=checkMat)
# #atDict = self.distSelector.select(tAts, acceptorAts, dist)
# #first remove bonded angles
# atDict = self.removeNeighbors(atDict)
# donor2Ats = dict1['donor2Ats']
# donor3Ats = dict1['donor3Ats']
# acceptor2Ats = dict2['acceptor2Ats']
# acceptor3Ats = dict2['acceptor3Ats']
# if distOnly:
# #need to build hbonds and return dictionary
# self.makeBonds(atDict, donor2Ats, donor3Ats, \
# acceptor2Ats, acceptor3Ats, paramDict)
# return atDict
# badAtDict = self.filterBasedOnAngs(atDict, donor2Ats, donor3Ats, \
# acceptor2Ats, acceptor3Ats, paramDict)
# atDict = self.removeBadAts(atDict, badAtDict)
# if atDict is None:
# atDict = {}
# return atDict
# def makeBonds(self, pD, d2Ats, d3Ats, a2Ats, a3ats, paramDict):
# for k in pD.keys():
# if k.element=='H':
# if hasattr(k, 'hbonds') and len(k.hbonds):
# continue
# d = k.bonds[0].atom1
# if id(d)==id(k): d = k.bonds[0].atom2
# #d = k.bonds[0].neighborAtom(k)
# h = k
# else:
# d = k
# h = None
# #pD[k] is a list of close-enough ats
# for ac in pD[k]:
# if ac==d: continue
# dSp2 = d in d2Ats
# aSp2 = ac in a2Ats
# if dSp2:
# if aSp2: typ = 22
# else: typ = 23
# elif aSp2: typ = 32
# else: typ = 33
# #THEY could be already bonded
# alreadyBonded = 0
# if hasattr(d, 'hbonds') and hasattr(ac,'hbonds'):
# for hb in d.hbonds:
# if hb.donAt==ac or hb.accAt==ac:
# alreadyBonded = 1
#
# if not alreadyBonded:
# newHB = HydrogenBond(d, ac, h, typ=typ)
# if not hasattr(ac, 'hbonds'):
# ac.hbonds=[]
# if not hasattr(d, 'hbonds'):
# d.hbonds=[]
# ac.hbonds.append(newHB)
# d.hbonds.append(newHB)
# if h is not None:
# #hydrogens can have only 1 hbond
# h.hbonds = [newHB]
# def filterBasedOnAngs(self, pD, d2Ats, d3Ats, a2Ats, a3ats, paramDict):
# badAtDict = {}
# d2max = paramDict['d2max']
# d2min = paramDict['d2min']
# d3max = paramDict['d3max']
# d3min = paramDict['d3min']
# #NEED these parameters
# a2max = paramDict['a2max']
# a2min = paramDict['a2min']
# a3max = paramDict['a3max']
# a3min = paramDict['a3min']
# #NB now pD keys could be hydrogens OR donors
# for k in pD.keys():
# if k.element=='H':
# d = k.bonds[0].atom1
# if id(d)==id(k): d = k.bonds[0].atom2
# #d = k.bonds[0].neighborAtom(k)
# h = k
# else:
# d = k
# h = None
# badAts = AtomSet([])
# ct = 0
# for ac in pD[k]:
# if h is not None:
# ang = getAngle(ac, h, d)
# else:
# acN = ac.bonds[0].atom1
# if id(acN) == id(ac): acN = ac.bonds[0].atom2
# #acN = ac.bonds[0].neighborAtom(ac)
# ang = getAngle(d, ac, acN)
# #print 'ang=', ang
# dSp2 = d in d2Ats
# aSp2 = ac in a2Ats
# #these limits could be adjustable
# if h is not None:
# if dSp2:
# upperLim = d2max
# lowerLim = d2min
# #upperLim = 170
# #lowerLim = 130
# else:
# upperLim = d3max
# lowerLim = d3min
# #upperLim = 180
# #lowerLim = 120
# else:
# #if there is no hydrogen use d-ac-acN angles
# if dSp2:
# upperLim = a2max
# lowerLim = a2min
# #upperLim = 150
# #lowerLim = 110
# else:
# upperLim = a3max
# lowerLim = a3min
# #upperLim = 150
# #lowerLim = 100
# if ang>lowerLim and ang <upperLim:
# #AT THIS MOMENT BUILD HYDROGEN BOND:
# if dSp2:
# if aSp2: typ = 22
# else: typ = 23
# elif aSp2: typ = 32
# else: typ = 33
# #THEY could be already bonded
# alreadyBonded = 0
# if hasattr(d, 'hbonds') and hasattr(ac,'hbonds'):
# for hb in d.hbonds:
# if hb.donAt==ac or hb.accAt==ac:
# alreadyBonded = 1
# if not alreadyBonded:
# newHB = HydrogenBond(d, ac, h, theta=ang, typ=typ)
# if not hasattr(ac, 'hbonds'):
# ac.hbonds=[]
# if not hasattr(d, 'hbonds'):
# d.hbonds=[]
# ac.hbonds.append(newHB)
# d.hbonds.append(newHB)
# if h is not None:
# #hydrogens can have only 1 hbond
# h.hbonds = [newHB]
# # newHB.hlen = dist
# #else:
# # newHB.dlen = dist
# else:
# badAts.append(ac)
# ct = ct + 1
# badAtDict[k] = badAts
# return badAtDict
# def removeBadAts(self, atDict, badAtDict):
# #clean-up function called after filtering on angles
# badKeys= badAtDict.keys()
# for at in atDict.keys():
# if at not in badKeys:
# continue
# if not len(badAtDict[at]):
# continue
# closeAts = atDict[at]
# badAts = badAtDict[at]
# goodAts = []
# for i in range(len(closeAts)):
# cAt = closeAts[i]
# if cAt not in badAts:
# goodAts.append(cAt)
# if len(goodAts):
# atDict[at] = goodAts
# else:
# del atDict[at]
# return atDict
# def removeNeighbors(self, atDict):
# #filter out at-itself and at-bondedat up to 1:4
# #NB keys could be hydrogens OR donors
# for at in atDict.keys():
# closeAts = atDict[at]
# bondedAts = AtomSet([])
# for b in at.bonds:
# ###at2 = b.neighborAtom(at)
# at2 = b.atom1
# if id(at2)==id(at): at2 = b.atom2
# bondedAts.append(at2)
# #9/13 remove this:
# ##also remove 1-3
# for b2 in at2.bonds:
# at3 = b2.atom1
# if id(at3)==id(at2): at3 = b.atom2
# #at3 = b2.neighborAtom(at2)
# if id(at3)!=id(at):
# bondedAts.append(at3)
# #for b3 in at3.bonds:
# #at4 = b2.neighborAtom(at3)
# #if at4!=at and at4!=at2:
# #bondedAts.append(at4)
# bondedAts = bondedAts.uniq()
# goodAts = []
# for i in range(len(closeAts)):
# cAt = closeAts[i]
# if cAt not in bondedAts:
# goodAts.append(cAt)
# if len(goodAts):
# atDict[at] = goodAts
# else:
# del atDict[at]
# return atDict
#
# def getDonors(self, nodes, paramDict):
# donorList = paramDict['donorTypes']
# print 'donorList=', donorList
# # currently this is a set of hydrogens
# hats = AtomSet(nodes.get(lambda x: x.element=='H'))
# #hats are optional: if none, process donors
# # if there are hats: dAts are all atoms bonded to all hydrogens
# if hats:
# dAts = AtomSet([])
# for at in hats:
# for b in at.bonds:
# at2 = b.atom1
# if id(at2)==id(at): at2 = b.atom2
# dAts.append(at2)
# #dAts.append(b.neighborAtom(at))
# else:
# dAts = nodes
# #get the sp2 hybridized possible donors which are all ns
# sp2 = []
# for t in ['Nam', 'Ng+', 'Npl']:
# if t in donorList:
# sp2.append(t)
# #ntypes = ['Nam', 'Ng+', 'Npl']
# sp2DAts = None
# if len(sp2):
# sp2DAts = AtomSet(dAts.get(lambda x, sp2=sp2: x.babel_type in sp2))
# hsp2 = AtomSet([])
# if sp2DAts:
# if hats:
# hsp2 = AtomSet(hats.get(lambda x, sp2DAts=sp2DAts:x.bonds[0].atom1 \
# in sp2DAts or x.bonds[0].atom2 in sp2DAts))
# if sp2DAts:
# #remove any sp2 N atoms which already have 3 bonds not to hydrogens
# n2Dons = AtomSet(sp2DAts.get(lambda x: x.element=='N'))
# if n2Dons:
# n2Dons.bl=0
# for at in n2Dons:
# for b in at.bonds:
# if type(b.bondOrder)==type(2):
# at.bl = at.bl + b.bondOrder
# else:
# at.bl = at.bl + 2
# #allow that there might already be a hydrogen
# nH = at.findHydrogens()
# at.bl = at.bl - len(nH)
# badAts = AtomSet(n2Dons.get(lambda x: x.bl>2))
# if badAts:
# sp2DAts = sp2DAts - badAts
# delattr(n2Dons,'bl')
# #get the sp3 hybridized possible donors
# sp3 = []
# for t in ['N3+', 'S3', 'O3']:
# if t in donorList:
# sp3.append(t)
# n3DAts = None
# if 'N3+' in sp3:
# n3DAts = AtomSet(dAts.get(lambda x: x.babel_type=='N3+'))
# o3DAts = None
# if 'O3' in sp3:
# o3DAts = AtomSet(dAts.get(lambda x: x.babel_type=='O3'))
# if o3DAts:
# #remove any O3 atoms which already have 2 bonds not to hydrogens
# badO3s = AtomSet([])
# for at in o3DAts:
# if len(at.bonds)<2: continue
# if len(at.findHydrogens()): continue
# else:
# badO3s.append(at)
# if len(badO3s):
# o3DAts = o3DAts - badO3s
# s3DAts = None
# if 'S3' in sp3:
# s3DAts = AtomSet(dAts.get(lambda x: x.babel_type=='S3'))
# sp3DAts = AtomSet([])
# for item in [n3DAts, o3DAts, s3DAts]:
# if item:
# sp3DAts = sp3DAts + item
# hsp3 = AtomSet([])
# if sp3DAts:
# if hats:
# hsp3 = AtomSet(hats.get(lambda x, sp3DAts=sp3DAts:x.bonds[0].atom1 \
# in sp3DAts or x.bonds[0].atom2 in sp3DAts))
# hsp = hsp2 + hsp3
# #print 'hsp=', hsp.name
# #print 'sp2DAts=', sp2DAts.name
# #print 'sp3DAts=', sp3DAts.name
# return hsp, sp2DAts, sp3DAts
# def getAcceptors(self, nodes, paramDict):
# acceptorList = paramDict['acceptorTypes']
# print 'acceptorList=', acceptorList
# sp2 = []
# for t in ['Npl', 'Nam']:
# if t in acceptorList: sp2.append(t)
# n2Accs = None
# if 'Npl' in sp2:
# n2Accs = AtomSet(nodes.get(lambda x: x.babel_type=='Npl'))
# if 'Nam' in sp2:
# n2Accs2 = AtomSet(nodes.get(lambda x: x.babel_type=='Nam'))
# if n2Accs2:
# if n2Accs:
# n2Accs = n2Accs+n2Accs2
# else:
# n2Accs = n2Accs2
# if n2Accs is None:
# n2Accs = AtomSet([])
# o_sp2 = []
# for t in ['O2', 'O-']:
# if t in acceptorList: sp2.append(t)
# o2Accs = None
# if 'O2' in o_sp2:
# o2Accs = AtomSet(nodes.get(lambda x: x.babel_type=='O2'))
# if 'O-' in sp2:
# o2Accs2 = AtomSet(nodes.get(lambda x: x.babel_type=='O-'))
# if o2Accs2:
# if o2Accs:
# o2Accs = o2Accs+o2Accs2
# else:
# o2Accs = o2Accs2
# if o2Accs is None:
# o2Accs = AtomSet([])
#
# o3Accs = None
# if 'O3' in acceptorList:
# o3Accs = AtomSet(nodes.get(lambda x: x.babel_type=='O3'))
# if o3Accs is None: o3Accs = AtomSet([])
# s3Accs = None
# if 'S3' in acceptorList:
# s3Accs = AtomSet(nodes.get(lambda x: x.babel_type=='S3'))
# if s3Accs is None: s3Accs = AtomSet([])
# ret2Ats = AtomSet([])
# for item in [n2Accs, o2Accs]:
# ret2Ats = ret2Ats + item
# ret3Ats = AtomSet([])
# for item in [s3Accs, o3Accs]:
# ret3Ats = ret3Ats + item
# if ret2Ats: print 'ret2Ats=', ret2Ats.name
# else: print 'no ret2Ats'
# if ret3Ats: print 'ret3Ats=', ret3Ats.name
# else: print 'no ret3Ats'
# return ret2Ats, ret3Ats
def __call__(self, group1, group2=None, paramDict={}, reset=1, **kw):
"""atDict <--- buildHbonds(group1, group2, paramDict, **kw)
\ngroup1 --- atoms
\ngroup2 --- atoms
\nparamDict --- a dictionary with these keys and default values
\nkeywprds ---\n
\ndistCutoff: 2.25 hydrogen--acceptor distance
\ndistCutoff2: 3.00 donor... acceptor distance
\nd2min: 120 <min theta for sp2 hybridized donors>
\nd2max: 180 <max theta for sp2 hybridized donors>
\nd3min: 120 <min theta for sp3 hybridized donors>
\nd3max: 170 <max theta for sp3 hybridized donors>
\na2min: 120 <min phi for sp2 hybridized donors>
\na2max: 150 <max phi for sp2 hybridized donors>
\na3min: 100 <min phi for sp3 hybridized donors>
\na3max: 150 <max phi for sp3 hybridized donors>
\ndonorTypes = allDonors
\nacceptorTypes = allAcceptors
\nreset: remove all previous hbonds
"""
group1 = self.vf.expandNodes(group1)
if group2 is None:
group2 = group1
else:
group2 = self.vf.expandNodes(group2)
if not (len(group1) and len(group2)):
return 'ERROR'
#for item in [group1, group2]:
if group1.__class__!=Atom:
group1 = group1.findType(Atom)
try:
group1.babel_type
except:
tops = group1.top.uniq()
for t in tops:
t.buildBondsByDistance()
self.vf.typeAtoms(t.allAtoms, topCommand=0)
if group2.__class__!=Atom:
group2 = group2.findType(Atom)
try:
group2.babel_type
except:
tops = group2.top.uniq()
for t in tops:
self.vf.typeAtoms(t.allAtoms, topCommand=0)
if not paramDict.has_key('distCutoff'):
paramDict['distCutoff'] = 2.25
if not paramDict.has_key('distCutoff2'):
paramDict['distCutoff2'] = 3.00
if not paramDict.has_key('d2min'):
paramDict['d2min'] = 120.
if not paramDict.has_key('d2max'):
paramDict['d2max'] = 180.
if not paramDict.has_key('d3min'):
paramDict['d3min'] = 120.
if not paramDict.has_key('d3max'):
paramDict['d3max'] = 170.
if not paramDict.has_key('a2min'):
paramDict['a2min'] = 130.
if not paramDict.has_key('a2max'):
paramDict['a2max'] = 170.
if not paramDict.has_key('a3min'):
paramDict['a3min'] = 120.
if not paramDict.has_key('a3max'):
paramDict['a3max'] = 170.
if not paramDict.has_key('distOnly'):
paramDict['distOnly'] = 0
if not paramDict.has_key('donorTypes'):
paramDict['donorTypes'] = allDonors
if not paramDict.has_key('acceptorTypes'):
paramDict['acceptorTypes'] = allAcceptors
return apply( self.doitWrapper, (group1, group2, paramDict, reset), kw)
class AddHBondHydrogensGUICommand(MVCommand):
"""This class provides Graphical User Interface to AddHBondHydrogens
which is invoked by it.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : AddHBondHydrogensGUICommand
\nCommand : addHBondHsGC
\nSynopsis:\n
None<---addHBondHsGC(nodes)
"""
def onAddCmdToViewer(self):
self.showSel = Tkinter.IntVar()
self.showSel.set(0)
def doit(self, nodes):
#addhydrogens to hbonds GC
self.hasAngles = 0
newHs = self.vf.addHBondHs(nodes)
#print 'newHs=', newHs
if not len(newHs):
self.warningMsg('no hbonds found missing hydrogens')
return 'ERROR'
else:
msg = str(len(newHs)) + ' hydrogens added to hbonds'
self.warningMsg(msg)
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
ifd = self.ifd = InputFormDescr(title = "Select nodes + change parameters(optional):")
ifd.append({'name':'keyLab',
'widgetType':Tkinter.Label,
'text':'Add missing hydrogens to hbonds for:',
'gridcfg':{'sticky':Tkinter.W, 'columnspan':2}})
ifd.append({'name':'selRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'all atoms',
'variable': self.showSel,
'value':0,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'a subset of atoms ',
'variable': self.showSel,
'value':1,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name': 'keySelector',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(0.,1.,.2),
},
'gridcfg':{'sticky':'we', 'columnspan':2 }})
ifd.append({'widgetType': Tkinter.Button,
'text':'Ok',
'wcfg':{'bd':6},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W},
'command':self.Accept_cb})
ifd.append({'widgetType': Tkinter.Button,
'text':'Cancel',
'wcfg':{'bd':6},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W, 'column':1,'row':-1},
'command':self.Close_cb})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.Close_cb)
self.hideSelector()
def cleanUpCrossSet(self):
chL = []
for item in self.vf.GUI.VIEWER.rootObject.children:
if isinstance(item, CrossSet) and item.name[:8]=='strSelCr':
chL.append(item)
if len(chL):
for item in chL:
item.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.vf.GUI.VIEWER.RemoveObject(item)
def Close_cb(self, event=None):
self.cleanUpCrossSet()
self.form.destroy()
def Accept_cb(self, event=None):
self.form.withdraw()
nodesToCheck = self.ifd.entryByName['keySelector']['widget'].get()
if not len(nodesToCheck):
self.warningMsg('no atoms specified')
return
if nodesToCheck[0].__class__!='Atom':
ats = nodesToCheck.findType(Atom)
nodesToCheck = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
self.Close_cb()
if not nodesToCheck:
self.warningMsg('no hbonds present in specified atoms')
return
else:
return self.doitWrapper(ats, topCommand=0)
def hideSelector(self, event=None):
e = self.ifd.entryByName['keySelector']
if not self.showSel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
AddHBondHydrogensGUICommandGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Add Hydrogens to Hbonds',
'menuCascadeName':'Build'}
AddHBondHydrogensGUICommandGUI = CommandGUI()
AddHBondHydrogensGUICommandGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds', 'Add Hydrogens to Hbonds', cascadeName='Build')
class AddHBondHydrogens(MVCommand):
"""This command adds hydrogen atoms to preexisting hydrogen bonds
\nPackage : Pmv
\nModule : hbondCommands
\nClass : AddHBondHydrogens
\nCommand : addHBondHs
\nSynopsis:\n
newHs <- addHBondHs(nodes, **kw):
\nRequired Arguments:\n
nodes --- atoms \n
newHs are new atoms, added to hbond.donAt\n
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('typeAtoms'):
self.vf.loadCommand('editCommands', 'typeAtoms', 'Pmv',
topCommand=0)
def dist(self, c1, c2):
c1 = Numeric.array(c1)
c2 = Numeric.array(c2)
d = c2 - c1
return math.sqrt(Numeric.sum(d*d))
def chooseH(self, at, accAt):
#do this for sp2 nitrogens with 1 bond
c2 = at.bonds[0].neighborAtom(at)
c3 = None
c4 = None
for b in c2.bonds:
if b.neighborAtom(c2)==at:
continue
elif c3 is None:
c3 = b.neighborAtom(c2)
elif c4 is None:
c4 = b.neighborAtom(c2)
accCoords = getTransformedCoords(accAt)
c2Coords = getTransformedCoords(c2)
c3Coords = getTransformedCoords(c3)
c4Coords = getTransformedCoords(c4)
v = vec3(c3Coords, c2Coords, 1.020)
v1 = vec3(c4Coords, c2Coords, 1.020)
#v = vec3(c3.coords, c2.coords, 1.020)
#v1 = vec3(c4.coords, c2.coords, 1.020)
#check angles of c3-at-b.accAt
c = getTransformedCoords(at)
#c = at.coords
coords1 = [c[0]+v[0], c[1]+v[1], c[2]+v[2]]
coords2 = [c[0]+v1[0], c[1]+v1[1], c[2]+v1[2]]
dist1 = dist(c3Coords, accCoords)
dist2 = dist(c4Coords, accCoords)
#dist1 = dist(c3.coords, accAt.coords)
#dist2 = dist(c4.coords, accAt.coords)
if dist1 > dist2:
coords = coords1
else:
coords = coords2
name = 'H' + at.name
childIndex = at.parent.children.index(at)+1
atom = Atom(name, at.parent, top=at.top, childIndex=childIndex,
assignUniqIndex=0)
atom._coords = [coords]
if hasattr(at, 'segID'): atom.setID = at.segID
atom.hetatm = at.hetatm
atom.alternate = []
atom.element = 'H'
atom.occupancy = 1.0
atom.conformation = 0
atom.temperatureFactor = 0.0
atom.babel_atomic_number = 1
atom.babel_type = 'H'
atom.babel_organic = 1
bond = Bond(at, atom)
atom.colors = {}
for key, value in at.colors.items():
atom.colors[key] = (0.0, 1.0, 1.0)
atom.opacities[key] = 1.0
atom.number = len(at.parent.children)
return atom
def doit(self, ats, renumber=1):
#addhydrogens to hbonds
withHBondAts = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
if not withHBondAts:
return 'ERROR'
newHs = AtomSet([])
for at in withHBondAts:
for b in at.hbonds:
if at!=b.donAt:
continue
if b.hAt is None:
if len(at.bonds)==1 and \
at.babel_type in ['Ng+', 'Nam','Npl']:
h = self.chooseH(at, b.accAt)
else:
self.vf.add_h(AtomSet([b.donAt]), 1,'noBondOrder',
1,topCommand=0)
h = at.bonds[-1].neighborAtom(at)
h.hbonds = [b]
newHs.append(h)
b.hAt = h
if renumber:
for mol in ats.top.uniq():
mol.allAtoms.sort()
fst = mol.allAtoms[0].number
mol.allAtoms.number = range(fst, len(mol.allAtoms)+fst)
# MS
#assert len(newHs)==len(newHs.uniq())
# tester -V Pmv.Tests.test_hbondCommands.hbond_hbondTests.test_addhbonds_hsGC__log_checks_that_it_runs
# creates
#hbond_barrel: :GLY22:HN1
#hbond_barrel: :THR23:HG1
#hbond_barrel: :THR23:HG1
#hbond_barrel: :ALA28:HN
# ...
# THR32:HG1 is double !
#print 'OKKKKKKKKKKKKKKKKKKKKKK', newHs
#for a in newHs:
# print a.full_name()
set = newHs.uniq()
# (MS) seems like we do not add atom here, They have been added by the
# self.vf.add_h above
#event = AddAtomsEvent(objects=set)
#self.vf.dispatchEvent(event)
return set
def __call__(self, nodes, **kw):
"""newHs <--- addHBondHs(nodes, **kw)
\nnodes --- atoms
\nnewHs are new atoms, added to hbond.donAt
"""
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes =self.vf.expandNodes(nodes)
if not len(nodes):
return 'ERROR'
if nodes.__class__!=Atom:
ats = nodes.findType(Atom)
else:
ats = nodes
try:
ats.babel_type
except AttributeError:
tops = ats.top.uniq()
for t in tops:
self.vf.typeAtoms(t.allAtoms, topCommand=0)
return apply( self.doitWrapper, (ats,), kw)
class LimitHydrogenBonds(MVCommand):
"""This class allows user to detect pre-existing HydrogenBonds with energy values
'lower' than a designated cutoff. Optionally the user can remove these bonds.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : LimitHydrogenBonds
\nCommand : limitHBonds
\nSynopsis:\n
None <- limitHBonds(nodes, energy, **kw)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onRemoveObjectFromViewer(self, obj):
if not len(self.hbonds):
return
removedAts = obj.findType(Atom)
changed = 0
bndsToRemove=[]
for b in self.hbonds:
ats = AtomSet([b.donAt,b.accAt])
if b.hAt is not None:
ats.append(b.hAt)
if ats.inter(removedAts):
bndsToRemove.append(b)
for b in bndsToRemove:
self.hbonds.remove(b)
changed = 1
ats = AtomSet([b.donAt,b.accAt])
if b.hAt is not None:
ats.append(b.hAt)
for at in ats:
at.hbonds.remove(b)
if not len(at.hbonds):
delattr(at, 'hbonds')
if changed:
self.update()
def onAddCmdToViewer(self):
from DejaVu.IndexedPolylines import IndexedPolylines
#from DejaVu.Labels import Labels
miscGeom = self.vf.GUI.miscGeom
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.masterGeom = Geom('limitHbondGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
self.lines = IndexedPolylines('limitHbondLines',
materials = ((1,0,0),), lineWidth=8,
stippleLines=1, inheritMaterial=0, protected=True)
self.labels = GlfLabels(name='limitELabs', shape=(0,3),
materials=((1,1,0),), inheritMaterial=0,
billboard=True, fontStyle='solid',
fontScales=(.3,.3,.3,))
self.labels.font = 'arial1.glf'
geoms = [self.lines, self.labels]
for item in geoms:
self.vf.GUI.VIEWER.AddObject(item, parent=self.masterGeom)
self.vf.loadModule('labelCommands', 'Pmv', log=0)
self.showAll = Tkinter.IntVar()
self.showAll.set(1)
self.disp_energy = Tkinter.IntVar()
self.disp_energy.set(0)
self.everts = []
self.e_labs = []
self.hideSel = Tkinter.IntVar()
self.hideSel.set(1)
self.bondsToDelete = []
#SHOULD THIS BE A HYDROGENBONDSET?
self.hbonds = []
def __call__(self, nodes, **kw):
"""None <- limitHBonds(nodes, energy, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes =self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
apply(self.doitWrapper, (ats,), kw)
def doit(self, ats):
#limit HBonds by energy
self.hasEnergies = 0
self.bondsToDelete = []
self.hbonds = []
self.everts = []
self.e_labs = []
self.resetDisplay()
hbats = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
if not hbats:
self.warningMsg('no hydrogen bonds found')
return 'ERROR'
hats = AtomSet(hbats.get(lambda x: x.element=='H'))
atNames = []
if hats:
for h in hats:
atNames.append((h.full_name(), None))
#self.hbonds.append(h.hbonds[0])
for b in h.hbonds:
self.hbonds.append(b)
else:
hats = AtomSet([])
bnds = []
for at in hbats:
bnds.extend(at.hbonds)
bndD = {}
for b in bnds:
bndD[b] = 0
hbnds2 = bndD.keys()
hbnds2.sort()
for b in hbnds2:
atNames.append((b.donAt.full_name(), None))
hats.append(b.donAt)
self.hbonds.append(b)
#self.vf.showHBonds.doit(hats)
#self.vf.showHBonds.showAllHBonds(hats)
#self.vf.showHBonds.buildEnergies(hats)
self.vf.getHBondEnergies(hats, topCommand=0)
#self.vf.showHBonds.showDistLabels.set(0)
#self.vf.showHBonds.showDistances()
#self.vf.showHBonds.dispEnergy.set(0)
#self.vf.showHBonds.showEnergies(hats)
self.origLabel = '0 hbonds to delete:'
ifd = self.ifd=InputFormDescr(title = 'Hydrogen Bonds to Delete:')
ifd.append({'name': 'hbondLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': self.origLabel},
'gridcfg':{'sticky': 'wens', 'columnspan':2}})
ifd.append({'name': 'atsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': atNames,
'mode': 'multiple',
'title': '',
'command': CallBackFunction(self.showHBondLC, atNames),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'row':2,'column':0, 'columnspan':2}})
ifd.append( {'name':'energy',
'widgetType': ExtendedSliderWidget,
'wcfg':{'label':'energy limit ',
'minval':-10, 'maxval':10,
'immediate':1,
'init':-2.0,
'width':150,
'command':self.update,
'sliderType':'float',
'entrypackcfg':{'side':'bottom'}},
'gridcfg':{'sticky':'we', 'columnspan':2}})
ifd.append({'name':'resetBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Reset',
'command': self.reset},
'gridcfg':{'sticky':'wens'}})
ifd.append({'name':'showEnBut',
'widgetType':Tkinter.Checkbutton,
'wcfg': { 'text':'Show Energy',
'variable': self.disp_energy,
'command': CallBackFunction(self.showEnergies, hats)},
'gridcfg':{'sticky':'wens', 'column':1, 'row':-1}})
ifd.append({'name':'acceptBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Delete',
'command': self.Delete_cb},
'gridcfg':{'sticky':'wens'}})
ifd.append({'name':'closeBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Dismiss',
'command': self.dismiss_cb},
'gridcfg':{'sticky':'wens', 'row':-1, 'column':1}})
self.form2 = self.vf.getUserInput(ifd, modal=0, blocking=0,
width=350, height=330)
self.form2.root.protocol('WM_DELETE_WINDOW',self.dismiss_cb)
self.lb = self.ifd.entryByName['atsLC']['widget'].lb
self.energyWid = self.ifd.entryByName['energy']['widget']
self.hbondLabel = self.ifd.entryByName['hbondLabel']['widget']
self.update()
def Delete_cb(self, event=None):
bl = []
for b in self.bondsToDelete:
for at in [b.donAt, b.hAt, b.accAt]:
at.hbonds.remove(b)
if not len(at.hbonds):
delattr(at, 'hbonds')
bl.append(b)
self.bondsToDelete = []
for b in bl:
del b
#also reset self.hbondLabel, self.lb
self.reset()
#also need to reset showHBonds so it will recalc everything
self.vf.showHBonds.reset()
self.vf.showHBonds.lines.Set(vertices=[], tagModified=False)
self.vf.showHBonds.labels.Set(vertices=[], tagModified=False)
self.vf.showHBonds.engLabs.Set(vertices=[], tagModified=False)
self.vf.showHBonds.dispEnergy.set(0)
self.vf.GUI.VIEWER.Redraw()
self.everts = []
self.dismiss_cb()
def resetDisplay(self, event=None):
self.lines.Set(vertices=[], tagModified=False)
self.labels.Set(vertices=[], labels=[], tagModified=False)
def updateDisplay(self, event=None):
#this draws red lines along bondToDelete
lineVerts = []
faces = []
self.everts = []
labs = []
ctr = 0
n = len(self.bondsToDelete)
self.lb.delete(0, 'end')
if n:
for b in self.bondsToDelete:
hAtCoords = getTransformedCoords(b.hAt)
accAtCoords = getTransformedCoords(b.accAt)
lineVerts.append(hAtCoords)
lineVerts.append(accAtCoords)
#lineVerts.append(b.hAt.coords)
#lineVerts.append(b.accAt.coords)
faces.append((ctr, ctr+1))
pt = (Numeric.array(hAtCoords)+Numeric.array(accAtCoords))/2.0
self.everts.append(pt.tolist())
labs.append(str(b.energy))
ctr = ctr + 2
self.lb.insert('end', b.hAt.full_name())
self.lines.Set(vertices = lineVerts, faces=faces,
tagModified=False)
self.labels.Set(vertices = self.everts, labels = labs,
tagModified=False)
msg = str(n) + ' hbonds to delete:'
self.hbondLabel.config(text=msg)
else:
msg = '0 hbonds to delete:'
self.hbondLabel.config(text=msg)
self.resetDisplay()
self.vf.GUI.VIEWER.Redraw()
def reset(self):
self.lb.select_clear(0, 'end')
self.lb.delete(0, 'end')
self.hbondLabel.config(text=self.origLabel)
self.energyWid.set(-2.0)
#also change bonds to delete
self.bondsToDelete = []
self.everts = []
self.resetDisplay()
self.update()
def update(self, event=None):
energy = self.energyWid.get()
self.bondsToDelete = []
for b in self.hbonds:
if b.energy > energy and not b in self.bondsToDelete:
self.bondsToDelete.append(b)
self.updateDisplay()
def showHBondLC(self, hats, event=None):
if not hasattr(self, 'ifd'):
self.doit(hats)
if self.lb.curselection() == (): return
self.showAll.set(0)
#THIS COULD BE >1
labs = []
verts = []
lineVerts = []
faces = []
ctr = 0
for n in self.lb.curselection():
#n in ('0','1','2')
name = self.lb.get(n)
at = self.vf.Mols.NodesFromName(name)[0]
b = at.hbonds[0]
#NB THESE MUST HAVE hydrogens
hAtCoords = getTransformedCoords(b.hAt)
accAtCoords = getTransformedCoords(b.accAt)
lineVerts.append(hAtCoords)
lineVerts.append(accAtCoords)
#lineVerts.append(b.hAt.coords)
#lineVerts.append(b.accAt.coords)
faces = ((ctr,ctr+1),)
if self.hasEnergies:
labs.append(self.e_labs[ind])
verts.append(self.everts[ind])
ctr = ctr + 2
self.labels.Set(vertices=verts,labels=labs,\
visible=self.disp_energy.get(), tagModified=False)
self.lines.Set(vertices=lineVerts, type=GL.GL_LINE_STRIP,
faces=faces, freshape=1, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def dismiss_cb(self, event=None, **kw):
#limitHbonds
self.lines.Set(vertices=[], tagModified=False)
self.labels.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
delattr(self, 'ifd')
self.form2.destroy()
self.hbonds = []
self.everts = []
self.vf.showHBonds.dismiss_cb()
def showEnergies(self, hats):
if not self.showAll.get():
self.showHBondLC(hats)
else:
self.labels.Set(labels = self.e_labs, vertices = self.everts,
visible=self.disp_energy.get(), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def buildEnergies(self, hats):
#FIX THIS: for some reason, eList is disordered...???
eList = self.vf.getHBondEnergies(hats, topCommand=0)
for hat in hats:
self.e_labs.append(str(hat.hbonds[0].energy))
def hideSelector(self, event=None):
e = self.ifd.entryByName['keySelector']
if self.hideSel.get():
e['widget'].grid_forget()
else:
e['widget'].grid(e['gridcfg'])
self.form.autoSize()
def cleanUpCrossSet(self):
chL = []
for item in self.vf.GUI.VIEWER.rootObject.children:
if isinstance(item, CrossSet) and item.name[:8]=='strSelCr':
chL.append(item)
if len(chL):
for item in chL:
item.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.vf.GUI.VIEWER.RemoveObject(item)
def Close_cb(self, event=None):
self.cleanUpCrossSet()
self.form.destroy()
def Ok_cb(self, event=None):
if self.hideSel.get():
nodes = self.vf.getSelection()
else:
nodes = self.ifd.entryByName['keySelector']['widget'].get()
if not len(nodes):
self.warningMsg('no nodes specified')
return
ats = nodes.findType(Atom)
self.form.withdraw()
apply(self.doitWrapper, (ats,), {})
def guiCallback(self):
#limitHbonds
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
sel = self.vf.getSelection()
ifd = self.ifd = InputFormDescr(title = "Select nodes + energy limit")
ifd.append({'name':'DkeyLab',
'widgetType':Tkinter.Label,
'text':'For Hydrogen Bonds:',
'gridcfg':{'sticky':Tkinter.W,'columnspan':3}})
ifd.append({'name':'selDRB0',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Use all atoms',
'variable': self.hideSel,
'value':1,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w'}})
ifd.append({'name':'selDRB1',
'widgetType':Tkinter.Radiobutton,
'wcfg':{'text':'Set atoms to use',
'variable': self.hideSel,
'value':0,
'command':self.hideSelector
},
'gridcfg':{'sticky':'w', 'row':-1, 'column':1}})
ifd.append({'name': 'keySelector',
'wtype':StringSelectorGUI,
'widgetType':StringSelectorGUI,
'wcfg':{ 'molSet': self.vf.Mols,
'vf': self.vf,
'all':1,
'crColor':(0.,1.,.2),
},
'gridcfg':{'sticky':'we', 'columnspan':2 }})
ifd.append({'widgetType': Tkinter.Button,
'text':'Ok',
'wcfg':{'bd':6,
'command':self.Ok_cb,
},
'gridcfg':{'sticky':'ew', 'columnspan':2 }})
ifd.append({'widgetType': Tkinter.Button,
'text':'Cancel',
'wcfg':{'bd':6},
'gridcfg':{'sticky':'ew', 'column':2,'row':-1},
'command':self.Close_cb})
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
self.form.root.protocol('WM_DELETE_WINDOW',self.Close_cb)
self.hideSelector()
LimitHydrogenBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Limit Existing Hbonds',
'menuCascadeName': 'Edit'}
LimitHydrogenBondsGUI = CommandGUI()
LimitHydrogenBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'Limit Existing Hbonds by Energy', cascadeName='Edit')
class DisplayHBonds(MVCommand):
"""Base class to allow user to visualize pre-existing HydrogenBonds between
atoms in viewer
\nPackage : Pmv
\nModule : hbondCommands
\nClass : DisplayHBonds
\nCommand : displayHBonds
\nSynopsis:\n
None <--- displayHBonds(ats)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def initGeom(self):
#initialize:
# self.geom
# self.hasGeom
pass
def onAddCmdToViewer(self):
self.initGeom()
#from DejaVu.Labels import Labels
self.verts = []
self.showAll = Tkinter.IntVar()
self.showAll.set(1)
self.vf.loadModule('labelCommands', 'Pmv', log=0)
# Create a ColorChooser.
self.palette = ColorChooser(commands=self.color_cb,
exitFunction = self.hidePalette_cb)
# pack
self.palette.pack(fill='both', expand=1)
# hide it
self.palette.hide()
self.width = 100
self.height = 100
self.winfo_x = None
self.winfo_y = None
def hidePalette_cb(self, event=None):
self.palette.hide()
def reset(self):
self.geom.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.hasGeom = 0
def update(self, event=None):
self.radii = self.radii_esw.get()
self.hasGeom =0
self.showAllHBonds()
def showHBondLC(self, atName, event=None):
#perhaps toggle on and off displaying the hbond with this???
#find the bond and change its visible field
for n in self.lb.curselection():
#n in ('0','1','2')
entry = self.lb.get(n)
name = entry[:-2]
#at = self.vf.Mols.NodesFromName(name)[0]
ats = self.vf.Mols.NodesFromName(name)
at = ats[0]
#to deal with two atoms with the exact same name:
if len(ats)>1:
for a in ats:
if hasattr(a, 'hbonds'):
at = a
break
b = at.hbonds[0]
#b.visible = not(b.visible)
if b.visible==0: b.visible = 1
else: b.visible = 0
entry = name + ' ' + str(b.visible)
self.lb.delete(n)
self.lb.insert(n, entry)
self.hasGeom = 0
self.showAllHBonds()
def color_cb(self, colors):
from DejaVu import colorTool
self.geom.Set(materials = (colors[:3],), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def changeColor(self, event=None):
#col = self.palette.display(callback=self.color_cb, modal=1)
#self.palette.pack(fill='both', expand=1)
# Create a ColorChooser.
if not hasattr(self, 'palette') or not self.palette.master.winfo_exists():
self.palette = ColorChooser(commands=self.color_cb,
exitFunction = self.hidePalette_cb)
# pack
self.palette.pack(fill='both', expand=1)
#??rh WHY hide it??
#self.palette.hide()
if not self.palette.master.winfo_ismapped():
self.palette.master.deiconify()
def getIfd(self, atNames):
#base class
pass
# print 'in spheres getIfd'
# if not hasattr(self, 'ifd'):
# ifd = self.ifd = InputFormDescr(title = 'Show Hydrogen Bonds as Spheres')
# ifd.append({'name': 'hbondLabel',
# 'widgetType': Tkinter.Label,
# 'wcfg':{'text': str(len(atNames)) + ' Atoms in hbonds:'},
# 'gridcfg':{'sticky': 'wens', 'columnspan':2}})
# ifd.append({'name': 'atsLC',
# 'widgetType':ListChooser,
# 'wcfg':{
# 'entries': atNames,
# 'mode': 'multiple',
# 'title': '',
# 'command': CallBackFunction(self.showHBondLC, atNames),
# 'lbwcfg':{'height':5,
# 'selectforeground': 'red',
# 'exportselection': 0,
# 'width': 30},
# },
# 'gridcfg':{'sticky':'wens', 'row':2,'column':0, 'columnspan':2}})
# ifd.append( {'name':'spacing',
# 'widgetType': ExtendedSliderWidget,
# 'wcfg':{'label':'spacing',
# 'minval':.01, 'maxval':1.0,
# 'immediate':1,
# 'init':.4,
# 'width':150,
# 'command':self.update,
# 'sliderType':'float',
# 'entrypackcfg':{'side':'bottom'}},
# 'gridcfg':{'sticky':'wens'}})
# ifd.append( {'name':'radii',
# 'widgetType': ExtendedSliderWidget,
# 'wcfg':{'label':'radii',
# 'minval':.01, 'maxval':1.0,
# 'immediate':1,
# 'init':.1,
# 'width':150,
# 'command':self.update,
# 'sliderType':'float',
# 'entrypackcfg':{'side':'bottom'}},
# 'gridcfg':{'sticky':'wens','row':-1, 'column':1}})
# ifd.append( {'name':'quality',
# 'widgetType': Tkinter.Scale,
# 'wcfg':{'label':'quality',
# 'troughcolor':'green',
# 'from_':2, 'to_':20,
# 'orient':'horizontal',
# 'length':'2i',
# 'command':self.updateQuality },
# 'gridcfg':{'sticky':'wens'}})
# ifd.append({'name':'changeColorBut',
# 'widgetType':Tkinter.Button,
# 'wcfg': { 'text':'Choose color',
# 'relief':'flat',
# 'command': self.changeColor},
# 'gridcfg':{'sticky':'wes', 'row':-1, 'column':1}})
# ifd.append({'name':'changeVertsBut',
# 'widgetType':Tkinter.Button,
# 'wcfg': { 'text':'Set anchors',
# 'command': self.changeDVerts},
# 'gridcfg':{'sticky':'wens'}})
# ifd.append({'name':'closeBut',
# 'widgetType':Tkinter.Button,
# 'wcfg': { 'text':'Dismiss',
# 'command': self.dismiss_cb},
# 'gridcfg':{'sticky':'wens', 'row':-1, 'column':1}})
def setUpWidgets(self, atNames):
if not hasattr(self, 'ifd'):
self.getIfd(atNames)
self.radii_esw = self.ifd.entryByName['radii']['widget']
self.lb = self.ifd.entryByName['atsLC']['widget'].lb
def doit(self, ats):
#DisplayHBonds base class
self.reset()
hbats = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
if not hbats:
self.warningMsg('no hydrogen bonds found')
return 'ERROR'
hats = AtomSet(hbats.get(lambda x: x.element=='H'))
atNames = []
if hats:
for h in hats:
nStr = h.full_name() + ' 1'
atNames.append((nStr, None))
#h.hbonds[0].visible = 1
for b in h.hbonds:
b.visible = 1
else:
hats = AtomSet([])
bnds = []
for at in hbats:
bnds.extend(at.hbonds)
bndD = {}
for b in bnds:
bndD[b] = 0
hbnds2 = bndD.keys()
hbnds2.sort()
for b in hbnds2:
b.visible = 1
nStr = b.donAt.full_name() + ' 1'
atNames.append((nStr, None))
hats.append(b.donAt)
self.hats = hats
self.showAllHBonds()
#print "hasattr(self, form)==", hasattr(self, 'form')
self.getIfd(atNames)
if not hasattr(self, 'form'):
#print "building form"
self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0,
width=380, height=390)
self.form.root.protocol('WM_DELETE_WINDOW',self.dismiss_cb)
self.toplevel = self.form.f.master.master
self.toplevel.positionfrom(who='user')
if self.winfo_x is not None and self.winfo_y is not None:
geom = self.width +'x'+ self.height +'+'
geom += self.winfo_x + '+' + self.winfo_y
self.toplevel.geometry(newGeometry=geom)
#else:
#print "already has form"
self.setUpWidgets(atNames)
def updateQuality(self, event=None):
# asSpheres
self.quality = self.quality_sl.get()
self.geom.Set(quality=quality, tagModified=False)
self.showAllHBonds()
def dismiss_cb(self, event=None, **kw):
# base class
self.reset()
try:
self.width = str(self.toplevel.winfo_width())
self.height = str(self.toplevel.winfo_height())
self.winfo_x = str(self.toplevel.winfo_x())
self.winfo_y = str(self.toplevel.winfo_y())
except:
pass
self.vf.GUI.VIEWER.Redraw()
if hasattr(self, 'ifd'):
delattr(self, 'ifd')
if hasattr(self, 'form2'):
self.form2.destroy()
delattr(self, 'form2')
if hasattr(self, 'form'):
self.form.destroy()
delattr(self, 'form')
if hasattr(self, 'palette'):
#self.palette.exit()
self.palette.hide()
def setupDisplay(self):
#draw geom between hAts OR donAts and accAts
self.geom.Set(vertices = self.verts, radius = self.radius,
tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def interpolate(self, pt1, pt2):
# self.spacing = .4
length = dist(pt1, pt2)
c1 = Numeric.array(pt1)
c2 = Numeric.array(pt2)
n = length/self.spacing
npts = int(math.floor(n))
# use floor of npts to set distance between > spacing
delta = (c2-c1)/(1.0*npts)
##spacing = length/floor(npts)
vertList = []
for i in range(npts):
vertList.append((c1+i*delta).tolist())
vertList.append(pt2.tolist())
return vertList
def setDVerts(self, entries, event=None):
if not hasattr(self, 'ifd2'):
self.changeDVerts()
lb = self.ifd2.entryByName['datsLC']['widget'].lb
if lb.curselection() == (): return
atName = lb.get(lb.curselection())
ind = int(lb.curselection()[0])
for h in self.hats:
for b in h.hbonds:
ats = b.donAt.parent.atoms.get(lambda x, atName=atName: x.name==atName)
if ats is None or len(ats) == 0:
if b.hAt is not None: at = b.hAt
else: at = b.donAt
else:
at = ats[0]
b.spVert1 = at
self.hasGeom = 0
self.showAllHBonds()
def setAVerts(self, entries, event=None):
if not hasattr(self, 'ifd2'):
self.changeDVerts()
lb = self.ifd2.entryByName['aatsLC']['widget'].lb
if lb.curselection() == (): return
atName = lb.get(lb.curselection())
ind = int(lb.curselection()[0])
for h in self.hats:
for b in h.hbonds:
ats = b.accAt.parent.atoms.get(lambda x, atName=atName: x.name==atName)
if ats is None or len(ats) == 0:
at = b.accAt
else:
at = ats[0]
b.spVert2 = at
self.hasGeom = 0
self.showAllHBonds()
def changeDVerts(self, event=None):
#for all residues in hbonds, pick new donorAttachment
# and new acceptorAttachment
entries = []
ns = ['N','C','O','CA','reset']
for n in ns:
entries.append((n, None))
if hasattr(self, 'form2'):
self.form2.root.tkraise()
return
ifd2 = self.ifd2=InputFormDescr(title = 'Set Anchor Atoms')
ifd2.append({'name': 'datsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': entries,
'mode': 'single',
'title': 'Donor Anchor',
'command': CallBackFunction(self.setDVerts, entries),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
#'lbpackcfg':{'fill':'both', 'expand':1},
'width': 30},
},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd2.append({'name': 'aatsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': entries,
'mode': 'single',
'title': 'Acceptor Anchor',
'command': CallBackFunction(self.setAVerts, entries),
'lbwcfg':{'height':5,
'selectforeground': 'red',
#'lbpackcfg':{'fill':'both', 'expand':1},
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd2.append({'name':'doneBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Done',
'command': self.closeChangeDVertLC},
'gridcfg':{'sticky':'wens'}})
self.form2 = self.vf.getUserInput(self.ifd2, modal=0, blocking=0)
self.form2.root.protocol('WM_DELETE_WINDOW',self.closeChangeDVertLC)
def closeChangeDVertLC(self, event=None):
if hasattr(self, 'ifd2'):
delattr(self, 'ifd2')
if hasattr(self, 'form2'):
self.form2.destroy()
delattr(self, 'form2')
def showAllHBonds(self, event=None):
if not self.hasGeom:
verts = []
for at in self.hats:
for b in at.hbonds:
if hasattr(b, 'visible') and not b.visible: continue
if hasattr(b, 'spVert1'):
pt1 = getTransformedCoords(b.spVert1)
#verts.append(getTransformedCoords(b.spVert1))
#verts.append(b.spVert1.coords)
elif b.hAt is not None:
pt1 = getTransformedCoords(b.hAt)
#verts.append(getTransformedCoords(b.hAt))
#verts.append(b.hAt.coords)
else:
pt1 = getTransformedCoords(b.donAt)
#verts.append(getTransformedCoords(b.donAt))
#verts.append(b.donAt.coords)
if hasattr(b, 'spVert2'):
#verts.extend(self.interpolate(verts[-1],
verts.extend(self.interpolate(pt1,
getTransformedCoords(b.spVert2)))
else:
#verts.extend(self.interpolate(verts[-1],
verts.extend(self.interpolate(pt1,
getTransformedCoords(b.accAt)))
self.verts = verts
self.hasGeom = 1
self.geom.Set(vertices = self.verts, radii = self.radii,
tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def guiCallback(self):
#showHbonds
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
sel = self.vf.getSelection()
#put a selector here
if len(sel):
ats = sel.findType(Atom)
apply(self.doitWrapper, (ats,), {})
class DisplayHBondsAsSpheres(DisplayHBonds):
"""This class allows user to visualize pre-existing HydrogenBonds between
atoms in viewer as small spheres
\nPackage : Pmv
\nModule : hbondCommands
\nClass : DisplayHBondsAsSpheres
\nCommand : displayHBSpheres
\nSynopsis:\n
None <--- displayHBSpheres(nodes, **kw)
"""
def initGeom(self):
from DejaVu.IndexedPolylines import IndexedPolylines
#from DejaVu.Labels import Labels
self.quality = 4
self.spheres = self.geom = Spheres('hbondSpheres',
materials=((0,1,0),), shape=(0,3),
radii=0.1, quality=4, pickable=0, inheritMaterial=0, protected=True)
geoms = [self.spheres]
self.masterGeom = Geom('HbondsAsSpheresGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
if self.vf.hasGui:
miscGeom = self.vf.GUI.miscGeom
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
for item in geoms:
self.vf.GUI.VIEWER.AddObject(item, parent=self.masterGeom)
self.hasGeom = 0
self.spacing = .40
self.radii = 0.1
self.verts = []
def __call__(self, nodes, **kw):
"""None <- displayHBSpheres(nodes, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
apply(self.doitWrapper, (ats,), kw)
def update(self, event=None):
#as spheres
self.radii = self.radii_esw.get()
self.spacing = self.spacing_esw.get()
self.hasGeom = 0
self.showAllHBonds()
def color_cb(self, colors):
from DejaVu import colorTool
self.geom.Set(materials = (colors[:3],), tagModified=False)
self.vf.GUI.VIEWER.Redraw()
col = colorTool.TkColor(colors[:3])
self.quality_sl.config(troughcolor = col)
def getIfd(self, atNames):
#print 'in spheres getIfd'
if not hasattr(self, 'ifd'):
ifd = self.ifd=InputFormDescr(title = 'Show Hydrogen Bonds as Spheres')
ifd.append({'name': 'hbondLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': str(len(atNames)) + ' Atoms in hbonds:\n(1=visible, 0 not visible)'},
'gridcfg':{'sticky': 'wens', 'columnspan':2}})
ifd.append({'name': 'atsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': atNames,
'mode': 'multiple',
'title': '',
'command': CallBackFunction(self.showHBondLC, atNames),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'row':2,'column':0, 'columnspan':2}})
ifd.append( {'name':'spacing',
'widgetType': ExtendedSliderWidget,
'wcfg':{'label':'spacing',
'minval':.01, 'maxval':1.0,
'immediate':1,
'init':.4,
'width':150,
'command':self.update,
'sliderType':'float',
'entrypackcfg':{'side':'bottom'}},
'gridcfg':{'sticky':'wens'}})
ifd.append( {'name':'radii',
'widgetType': ExtendedSliderWidget,
'wcfg':{'label':'radii',
'minval':.01, 'maxval':1.0,
'immediate':1,
'init':.1,
'width':150,
'command':self.update,
'sliderType':'float',
'entrypackcfg':{'side':'bottom'}},
'gridcfg':{'sticky':'wens','row':-1, 'column':1}})
ifd.append( {'name':'quality',
'widgetType': Tkinter.Scale,
'wcfg':{'label':'quality',
'troughcolor':'green',
'from_':2, 'to_':20,
'orient':'horizontal',
'length':'2i',
'command':self.updateQuality },
'gridcfg':{'sticky':'wens'}})
ifd.append({'name':'changeColorBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Choose color',
'relief':'flat',
'command': self.changeColor},
'gridcfg':{'sticky':'wes', 'row':-1, 'column':1}})
ifd.append({'name':'changeVertsBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Set anchors',
'command': self.changeDVerts},
'gridcfg':{'sticky':'wens'}})
ifd.append({'name':'closeBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Dismiss',
'command': self.dismiss_cb},
'gridcfg':{'sticky':'wens', 'row':-1, 'column':1}})
def setUpWidgets(self, atNames):
if not hasattr(self, 'ifd'):
self.getIfd(atNames)
self.radii_esw = self.ifd.entryByName['radii']['widget']
self.spacing_esw = self.ifd.entryByName['spacing']['widget']
self.quality_sl= self.ifd.entryByName['quality']['widget']
self.quality_sl.set(self.quality)
self.lb = self.ifd.entryByName['atsLC']['widget'].lb
def updateQuality(self, event=None):
self.quality = self.quality_sl.get()
self.geom.Set(quality=self.quality, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
DisplayHBondsAsSpheresGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'As Spheres',
'menuCascadeName': 'Display'}
DisplayHBondsAsSpheresGUI = CommandGUI()
DisplayHBondsAsSpheresGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'As Spheres', cascadeName = 'Display')
class DisplayHBondsAsCylinders(DisplayHBonds):
"""This class allows user to visualize pre-existing HydrogenBonds between
atoms in viewer as cylinders
\nPackage : Pmv
\nModule : hbondCommands
\nClass : DisplayHBondsAsCylinders
\nCommand : displayHBCylinders
\nSynopsis:\n
None <- displayHBCylinders(nodes, **kw)
"""
def initGeom(self):
self.cylinders = self.geom = Cylinders('hbondCylinders',
quality=40, culling=GL.GL_NONE, radii=(0.2),
materials=((0,1,0),), pickable=0, inheritMaterial=0)
#DejaVu.Cylinders overwrites kw cull so have to reset it here
self.cylinders.culling = GL.GL_NONE
geoms = [self.cylinders]
miscGeom = self.vf.GUI.miscGeom
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.masterGeom = Geom('HbondsAsCylindersGeoms',shape=(0,0),
pickable=0, protected=True)
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
for item in geoms:
self.vf.GUI.VIEWER.AddObject(item, parent=self.masterGeom)
self.hasGeom = 0
self.radii = 0.2
self.length = 1.0
self.oldlength = 1.0
self.verts = []
self.faces = []
def __call__(self, nodes, **kw):
"""None <- displayHBCylinders(nodes, **kw) """
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
nodes =self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
ats = nodes.findType(Atom)
apply(self.doitWrapper, (ats,), kw)
def getIfd(self, atNames):
#cylinders
if not hasattr(self, 'ifd'):
ifd = self.ifd = InputFormDescr(title='Show Hydrogen Bonds as Cylinders')
ifd.append({'name': 'hbondLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': str(len(atNames)) + ' Atoms in hbonds:\n(1=visible, 0 not visible)'},
'gridcfg':{'sticky': 'wens', 'columnspan':2}})
ifd.append({'name': 'atsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': atNames,
'mode': 'multiple',
'title': '',
'command': CallBackFunction(self.showHBondLC, atNames),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'row':2,'column':0, 'columnspan':2}})
ifd.append( {'name':'radii',
'widgetType': ExtendedSliderWidget,
'wcfg':{'label':'radii',
'minval':.01, 'maxval':1.0,
'immediate':1,
'init':.2,
'width':250,
'command':self.update,
'sliderType':'float',
'entrypackcfg':{'side':'right'}},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd.append( {'name':'length',
'widgetType': ExtendedSliderWidget,
'wcfg':{'label':'length',
'minval':.01, 'maxval':5.0,
'immediate':1,
'init':1.0,
'width':250,
'command':self.update,
'sliderType':'float',
'entrypackcfg':{'side':'right'}},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd.append({'name':'changeVertsBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Set anchors',
'command': self.changeDVerts},
'gridcfg':{'sticky':'wens'}})
ifd.append({'name':'changeColorBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Change color',
'command': self.changeColor},
'gridcfg':{'sticky':'wes', 'row':-1, 'column':1}})
ifd.append({'name':'closeBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Dismiss',
'command': self.dismiss_cb},
'gridcfg':{'sticky':'wens','columnspan':2 }})
#ifd.append({'name':'changeVertsBut',
#'widgetType':Tkinter.Button,
#'wcfg': { 'text':'Set anchors',
#'command': self.changeDVerts},
#'gridcfg':{'sticky':'wens'}})
def setUpWidgets(self, atNames):
if not hasattr(self, 'ifd'):
self.getIfd(atNames)
self.radii_esw = self.ifd.entryByName['radii']['widget']
self.length_esw = self.ifd.entryByName['length']['widget']
self.lb = self.ifd.entryByName['atsLC']['widget'].lb
def update(self, event=None):
#as cylinders
self.radii = self.radii_esw.get()
self.oldlength = self.length
self.length = self.length_esw.get()
self.hasGeom = 0
self.showAllHBonds()
def adjustVerts(self, v1, v2, length):
#each end needs to be changed by length/2.
#eg if length = 1.1, change each end by .05
if length==self.oldlength:
return (v1, v2)
vec = Numeric.array(v2) - Numeric.array(v1)
vec_len = math.sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2)
alpha = (length-1.)/2. #(.5-1)/2.-> -.25% or (1.5 -1.)/2. ->+.25%
#delta v1 is v1 - alpha*vec_len
#delta v2 is v2 + alpha*vec_len
delta = alpha*vec_len
return Numeric.array(v1-delta*vec).astype('f'), Numeric.array(v2+delta*vec).astype('f')
def showAllHBonds(self, event=None):
if not self.hasGeom:
verts = []
faces = []
ct = 0
for at in self.hats:
for b in at.hbonds:
if hasattr(b, 'visible') and not b.visible: continue
if hasattr(b, 'spVert1'):
pt1 = getTransformedCoords(b.spVert1)
elif b.hAt is not None:
pt1 = getTransformedCoords(b.hAt)
else:
pt1 = getTransformedCoords(b.donAt)
if hasattr(b, 'spVert2'):
#verts.extend(self.interpolate(verts[-1],
at2 = b.spVert2
else:
at2 = b.accAt
pt2 = getTransformedCoords(at2)
#verts.extend([pt1, pt2])
verts.extend(self.adjustVerts(pt1, pt2, self.length))
faces.append((ct, ct+1))
ct = ct + 2
#reset oldlength here, after recalc all hbond verts
self.oldlength = self.length
self.verts = verts
self.faces = faces
self.hasGeom = 1
self.cylinders.Set(vertices=self.verts, radii=self.radii,
faces=self.faces, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
DisplayHBondsAsCylindersGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'As Cylinders',
'menuCascadeName': 'Display'}
DisplayHBondsAsCylindersGUI = CommandGUI()
DisplayHBondsAsCylindersGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'As Cylinders', cascadeName = 'Display')
class ExtrudeHydrogenBonds(MVCommand):
"""This class allows user to visualize pre-existing HydrogenBonds between
atoms in viewer using extruded geometries
\nPackage : Pmv
\nModule : hbondCommands
\nClass : ExtrudeHydrogenBonds
\nCommand : extrudeHBonds
\nSynopsis:\n
None <- extrudeHBonds(nodes, shape2D=None, capsFlag=0, **kw)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
self.flag = self.flag | self.objArgOnly
def onAddCmdToViewer(self):
self.spacing = 0.4
self.geoms = []
self.color = (0,1,1)
# Create a ColorChooser.
self.palette = ColorChooser(commands=self.color_cb,
exitFunction = self.hidePalette_cb)
# pack
self.palette.pack(fill='both', expand=1)
# hide it
self.palette.hide()
#self.palette.exit()
def hidePalette_cb(self, event=None):
self.palette.hide()
def __call__(self, nodes, shape2D=None, capsFlag=0,**kw):
"""
None <- extrudeHBonds(nodes, shape2D=None, capsFlag=0, **kw)
"""
if type(nodes) is StringType:
self.nodeLogString = "'"+nodes+"'"
if shape2D==None:
shape2D = Circle2D(radius=0.1)
nodes = self.vf.expandNodes(nodes)
if not len(nodes): return 'ERROR'
nodes = nodes.findType(Atom)
kw['capsFlag'] = capsFlag
apply(self.doitWrapper, (nodes, shape2D), kw)
def interpolate(self, pt1, pt2):
length = dist(pt1, pt2)
c1 = Numeric.array(pt1)
c2 = Numeric.array(pt2)
delta = (c2-c1)/(3.0)
vertList = []
for i in range(3):
vertList.append((c1+i*delta).tolist())
vertList.append(pt2)
return vertList
def updateDisplay(self):
self.geoms = []
atNames = []
for b in self.hbonds:
accAtCoords = getTransformedCoords(b.accAt)
dAtCoords = getTransformedCoords(b.donAt)
if b.hAt is not None:
hAtCoords = getTransformedCoords(b.hAt)
name = b.hAt.full_name()
else:
name = b.donAt.full_name()
if not hasattr(b, 'spline'):
#make one
if b.hAt is not None:
#name = b.hAt.full_name()
coords = self.interpolate(hAtCoords, accAtCoords)
#coords = self.interpolate(b.hAt.coords, b.accAt.coords)
else:
#name = b.donAt.full_name()
coords = self.interpolate(dAtCoords, accAtCoords)
#coords = self.interpolate(b.donAt.coords, b.accAt.coords)
nStr = name + ' 1'
atNames.append((nStr,None))
b.spline = SplineObject(coords, name = name,
nbchords = 4, interp = 'interpolation',
continuity= 2, closed=0)
smooth = b.spline.smooth
else:
nStr = name + ' %d'%b.g.visible
atNames.append((nStr,None))
if hasattr(b,'exVert1'):
name = b.exVert1.full_name()
coords1= b.exVert1.coords
elif b.hAt is not None:
name = b.hAt.full_name()
coords1= hAtCoords
else:
name = b.donAt.full_name()
coords1= dAtCoords
if hasattr(b,'exVert2'):
coords2= b.exVert2.coords
else:
coords2= accAtCoords
coords = self.interpolate(coords1, coords2)
b.spline = SplineObject(coords, name = name,
nbchords = 4, interp = 'interpolation',
continuity= 2, closed=0)
smooth = b.spline.smooth
if hasattr(b, 'g'):
self.vf.GUI.VIEWER.RemoveObject(b.g)
name = b.spline.name[-8:]+'_hbond'
b.g = GleExtrude(name=name, visible=1,
inheritMaterial=0,
culling=GL.GL_NONE,
materials = (self.color,))
self.vf.GUI.VIEWER.AddObject(b.g)
b.g.culling = GL.GL_NONE
self.geoms.append(b.g)
ctlAtmsInSel = AtomSet([b.donAt, b.accAt])
ctlAtms = AtomSet([b.donAt, b.accAt])
b.g.spline = (b.spline, ctlAtmsInSel, ctlAtms)
# need to get new contourPoints and new contourNormals
b.g.shape2D = self.shape
contpts = Numeric.array(b.g.shape2D.contpts)
contourPoints = contpts[:,:2]
contnorm = Numeric.array(b.g.shape2D.contnorm)
contourNormals = contnorm[:,:2]
b.g.Set(trace3D = Numeric.array((b.spline.smooth),'f'),
shape2D = self.shape,
contourUp = (0.,0.,1.),
inheritMaterial=0,
materials = (self.color,), visible=1,
capsFlag=self.capsFlag, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
return atNames
def doit(self, nodes, shape2D, capsFlag = 0):
#extrude
self.shape = shape2D
self.capsFlag = capsFlag
hats = AtomSet(nodes.get(lambda x: hasattr(x, 'hbonds')))
hbonds = []
for h in hats:
for b in h.hbonds:
if h == b.donAt:
b.visible = 1
hbonds.append(b)
self.hbonds = hbonds
atNames = self.updateDisplay()
if not hasattr(self, 'ifd2'):
ifd = self.ifd2=InputFormDescr(title = 'Show Extruded Hydrogen Bonds')
ifd.append({'name': 'hbondLabel',
'widgetType': Tkinter.Label,
'wcfg':{'text': str(len(atNames)) + ' Atoms in hbonds:\n(1=visible, 0 not visible)'},
'gridcfg':{'sticky': 'wens', 'columnspan':2}})
ifd.append({'name': 'atsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': atNames,
'mode': 'single',
'title': '',
'command': CallBackFunction(self.showHBondLC, atNames),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'row':2,'column':0, 'columnspan':2}})
ifd.append({'name':'changeColorBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Choose color',
'command': self.changeColor},
'gridcfg':{'sticky':'wes'}})
ifd.append({'name':'changeVertsBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Set anchors',
'command': self.changeDVerts},
'gridcfg':{'sticky':'wens','row':-1,'column':1}})
ifd.append({'name':'closeBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Dismiss',
'command': self.dismiss_cb},
'gridcfg':{'sticky':'wens','columnspan':2}})
self.form = self.vf.getUserInput(ifd, modal=0, blocking=0,
width=350, height=290)
self.form.root.protocol('WM_DELETE_WINDOW',self.dismiss_cb)
self.lb = self.ifd2.entryByName['atsLC']['widget'].lb
def updateExtrusion_cb(self, event=1):
#REDO DISPLAY HERE!!
self.updateDisplay()
def changeDVerts(self, event=None):
#for all residues in hbonds, pick new donorAttachment
# and new acceptorAttachment
entries = []
ns = ['N','C','O','CA','reset']
for n in ns:
entries.append((n, None))
ifd3 = self.ifd3=InputFormDescr(title = 'Set Anchor Atoms')
ifd3.append({'name': 'datsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': entries,
'mode': 'single',
'title': 'Donor Anchor',
'command': CallBackFunction(self.setDVerts, entries),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd3.append({'name': 'aatsLC',
'widgetType':ListChooser,
'wcfg':{
'entries': entries,
'mode': 'single',
'title': 'Acceptor Anchor',
'command': CallBackFunction(self.setAVerts, entries),
'lbwcfg':{'height':5,
'selectforeground': 'red',
'exportselection': 0,
'width': 30},
},
'gridcfg':{'sticky':'wens', 'columnspan':2}})
ifd3.append({'name':'acceptBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Update extrusion',
'command': self.updateExtrusion_cb},
'gridcfg':{'sticky':'wens'}})
ifd3.append({'name':'doneBut',
'widgetType':Tkinter.Button,
'wcfg': { 'text':'Done',
'command': self.closeChangeDVertLC},
'gridcfg':{'sticky':'wens'}})
self.form3 = self.vf.getUserInput(self.ifd3, modal=0, blocking=0)
self.form3.root.protocol('WM_DELETE_WINDOW',self.closeChangeDVertLC)
def setDVerts(self, entries, event=None):
if not hasattr(self, 'ifd3'):
self.changeDVerts()
lb = self.ifd3.entryByName['datsLC']['widget'].lb
if lb.curselection() == (): return
atName = lb.get(lb.curselection())
ind = int(lb.curselection()[0])
for b in self.hbonds:
ats = b.donAt.parent.atoms.get(lambda x, atName=atName: x.name==atName)
if ats is None:
if b.hAt is not None: at = b.hAt
else: at = b.donAt
else:
at = ats[0]
b.exVert1 = at
#REDO DISPLAY HERE!!
#self.updateDisplay()
def setAVerts(self, entries, event=None):
if not hasattr(self, 'ifd3'):
self.changeDVerts()
lb = self.ifd3.entryByName['aatsLC']['widget'].lb
if lb.curselection() == (): return
atName = lb.get(lb.curselection())
ind = int(lb.curselection()[0])
for b in self.hbonds:
ats = b.accAt.parent.atoms.get(lambda x, atName=atName: x.name==atName)
if ats is None:
at = b.accAt
else:
at = ats[0]
b.exVert2 = at
#REDO DISPLAY HERE!!
#self.updateDisplay()
def closeChangeDVertLC(self, event=None):
if hasattr(self, 'ifd3'):
delattr(self, 'ifd3')
if hasattr(self, 'form3'):
self.form3.destroy()
def dismiss_cb(self, event=None, **kw):
#extrudeHbonds
for g in self.geoms:
g.Set(visible=0, tagModified=False)
self.vf.GUI.VIEWER.Redraw()
if hasattr(self, 'ifd2'):
delattr(self, 'ifd2')
if hasattr(self, 'form3'):
self.form3.destroy()
delattr(self, 'form3')
if hasattr(self, 'form'):
self.form.destroy()
delattr(self, 'form')
if hasattr(self, 'palette'):
self.palette.hide()
#self.palette.exit()
def color_cb(self, colors):
self.color = colors[:3]
for g in self.geoms:
g.Set(materials = (self.color,), inheritMaterial=0,
tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def changeColor(self, event=None):
#col = self.palette.display(callback=self.color_cb, modal=1)
if not hasattr(self, 'palette') or not self.palette.master.winfo_exists():
self.palette = ColorChooser(commands=self.color_cb,
exitFunction = self.hidePalette_cb)
# pack
self.palette.pack(fill='both', expand=1)
#??rh WHY hide it??
#self.palette.hide()
if not self.palette.master.winfo_ismapped():
self.palette.master.deiconify()
def showHBondLC(self, atName, event=None):
#toggle on and off displaying the hbond
#find the bond and Set its visible field
#CHANGE ENTRY HERE!!!!
for n in self.lb.curselection():
#n in ('0','1','2')
entry = self.lb.get(n)
name = entry[:-2]
#at = self.vf.Mols.NodesFromName(name)[0]
#at = ats[0]
ats = self.vf.Mols.NodesFromName(name)
#to deal with two atoms with the exact same name:
if len(ats)>1:
for a in ats:
if hasattr(a, 'hbonds'):
at = a
break
b = at.hbonds[0]
b.g.Set(visible = not(b.g.visible), tagModified=False)
if b.g.visible:
entry = name + ' 1'
else:
entry = name + ' 0'
self.lb.delete(n)
self.lb.insert(n, entry)
self.vf.GUI.VIEWER.Redraw()
def guiCallback(self):
# Write a shape chooser method that should be reused in
# secondaryStructureCommands, CATrace commands, and splineCommands.
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
idf = InputFormDescr(title='Extrude Spline')
# List Chooser for the shape to extrude
entries = [('rectangle',None),('circle',None),
('ellipse',None),
('square',None),('triangle',None)
]
idf.append({'name':'shape',
'widgetType':ListChooser,
'defaultValue':'circle',
'wcfg':{'entries': entries,
'lbwcfg':{'height':5,'exportselection':0},
'title':'Choose a shape to extrude'},
'gridcfg':{'sticky':'wens'}
})
typeshape = self.vf.getUserInput(idf)
if typeshape == {} or typeshape['shape'] == []: return
########################################################
# Shape is a Rectangle
if typeshape['shape'][0]=='rectangle':
idf = InputFormDescr(title ="Rectangle size :")
idf.append( {'name': 'width',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Width',
'minval':0.05,'maxval':3.0 ,
'init':1.2,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append( {'name': 'height',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Height',
'minval':0.05,'maxval':3.0 ,
'init':0.4,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
#idf.append({'name':'frontcap',
#'widgetType':Tkinter.Checkbutton,
#'defaultValue':1,'type':float,
#'wcfg':{'text':'front cap',
#'state': 'disabled',
#'variable': Tkinter.IntVar()},
#'gridcfg':{'sticky':'we'}})
idf.append({'name':'caps',
'widgetType':Tkinter.Checkbutton,
'defaultValue':1,
'wcfg':{'text':'Caps',
'variable': Tkinter.IntVar()},
'gridcfg':{'sticky':'we','row':-1}})
val = self.vf.getUserInput(idf)
if val:
shape = Rectangle2DDupRectangle2D(width = val['width'],
height = val['height'],
vertDup=1, firstDup=1)
capsFlag = val['caps']
# Shape is a Circle:
elif typeshape['shape'][0]=='circle':
idf = InputFormDescr(title="Circle size :")
idf.append( {'name': 'radius',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Radius',
'minval':0.05,'maxval':3.0 ,
'init':0.2,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append({'name':'caps',
'widgetType':Tkinter.Checkbutton,
'defaultValue':1,
'wcfg':{'text':'Caps',
'variable': Tkinter.IntVar()},
'gridcfg':{'sticky':'we'}})
val = self.vf.getUserInput(idf)
if val:
shape = Circle2D(radius=val['radius'], firstDup = 1)
capsFlag = val['caps']
# Shape is an Ellipse
elif typeshape['shape'][0]=='ellipse':
idf = InputFormDescr(title="Ellipse demi grand Axis and demi small axis :")
idf.append( {'name': 'grand',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'demiGrandAxis',
'minval':0.05,'maxval':3.0 ,
'init':0.5,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append( {'name': 'small',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'demiSmallAxis',
'minval':0.05,'maxval':3.0 ,
'init':0.2,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append({'name':'caps',
'widgetType':Tkinter.Checkbutton,
'defaultValue':1,
'wcfg':{'text':'Caps ',
'variable': Tkinter.IntVar()},
'gridcfg':{'sticky':'we','row':-1}})
val = self.vf.getUserInput(idf)
if val:
shape = Ellipse2D(demiGrandAxis= val['grand'],
demiSmallAxis=val['small'], firstDup=1)
capsFlag = val['caps']
# Shape is a Square:
elif typeshape['shape'][0]=='square':
idf = InputFormDescr(title="Square size :")
idf.append( {'name': 'sidelength',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Length of side:',
'minval':0.05,'maxval':3.0 ,
'init':0.5,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append({'name':'caps',
'widgetType':Tkinter.Checkbutton,
'defaultValue':1,
'wcfg':{'text':'Caps',
'variable': Tkinter.IntVar()},
'gridcfg':{'sticky':'we'}})
val = self.vf.getUserInput(idf)
if val:
shape = Square2D(side=val['sidelength'], firstDup=1, vertDup=1)
capsFlag = val['caps']
# Shape is a Triangle:
elif typeshape['shape'][0]=='triangle':
idf = InputFormDescr(title="Triangle size :")
idf.append( {'name': 'sidelength',
'widgetType':ExtendedSliderWidget,
'wcfg':{'label': 'Length of side: ',
'minval':0.05,'maxval':3.0 ,
'init':0.5,
'labelsCursorFormat':'%1.2f',
'sliderType':'float',
'entrywcfg':{'width':4},
'entrypackcfg':{'side':'right'}},
'gridcfg':{'columnspan':2,'sticky':'we'}
})
idf.append({'name':'caps',
'widgetType':Tkinter.Checkbutton,
'defaultValue':1,
'wcfg':{'text':'Caps',
'variable': Tkinter.IntVar()},
'gridcfg':{'sticky':'we'}})
val = self.vf.getUserInput(idf)
if val:
shape = Triangle2D(side=val['sidelength'], firstDup=1,
vertDup=1)
capsFlag = val['caps']
else: return
if val:
nodes = self.vf.getSelection()
if not len(nodes): return 'ERROR'
nodes = nodes.findType(Atom)
self.doitWrapper(nodes, shape, capsFlag = capsFlag)
ExtrudeHydrogenBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'As Extruded Shapes',
'menuCascadeName': 'Display'}
ExtrudeHydrogenBondsGUI = CommandGUI()
ExtrudeHydrogenBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'As Extruded Shapes', cascadeName = 'Display')
class WriteAssemblyHBonds(MVCommand):
"""Command to write a file specifying >1 chain with hydrogen bonds. Chains which are hydrogen-bonded are written in one pdb file. They may or may not be part of the same molecule.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : WriteAssemblyHBonds
\nCommand : writeAssemblyHB
\nSynopsis:\n
None <--- writeAssemblyHB(filename, nodes, **kw)
\nRequired Arguments:\n
filename --- name of the hbond file\n
nodes --- TreeNodeSet holding the current selection
"""
def onAddCmdToViewer(self):
self.PdbWriter = PdbWriter()
def __call__(self, filename, nodes, **kw):
"""None <--- writeAssemblyHB(filename, nodes, **kw)
\nfilename --- name of the hbond file
\nnodes --- TreeNodeSet holding the current selection """
apply(self.doitWrapper, (filename, nodes,), kw)
def fixIDS(self, chains):
idList = chains.id
ifd = self.ifd = InputFormDescr(title = "Set unique chain ids")
ent_varDict = self.ent_varDict = {}
cb_varDict = self.cb_varDict = {}
self.nStrs = []
self.entStrs = []
self.chains = chains
ifd.append({'name':'Lab1',
'widgetType':Tkinter.Label,
'text':'Current',
'gridcfg':{'sticky':'we'}})
ifd.append({'name':'Lab2',
'widgetType':Tkinter.Label,
'text':'New',
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
for ch in chains:
idList = chains.id
ct = idList.count(ch.id)
if ct!=1:
for i in range(ct-1):
ind = idList.index(ch.id)
idList[ind] = ch.id+str(i)
for i in range(len(chains)):
chid = idList[i]
ch = chains[i]
nStr = chid+'_lab'
self.nStrs.append(nStr)
entStr = chid+'_ent'
self.entStrs.append(entStr)
newEntVar = ent_varDict[ch] = Tkinter.StringVar()
newEntVar.set(ch.id)
newCbVar = cb_varDict[ch] = Tkinter.IntVar()
ifd.append({'name':nStr,
'widgetType':Tkinter.Label,
'text':ch.full_name(),
'gridcfg':{'sticky':'we'}})
ifd.append({'name':entStr,
'widgetType':Tkinter.Entry,
'wcfg':{ 'textvariable': newEntVar, },
'gridcfg':{'sticky':'we', 'row':-1, 'column':1}})
vals = self.vf.getUserInput(self.ifd, modal=0, blocking=1, okcancel=1)
if vals:
for i in range(len(chains)):
#CHECK for changes in id/name
ch = chains[i]
ll = ch.id
wl = strip(vals[self.entStrs[i]])
if ll!=wl:
print 'changed chain ', ch.full_name(), ' to ',
ch.id = wl[0]
ch.name = wl[0]
print ch.full_name()
def writeHYDBNDRecords(self, atoms, fptr):
for a in atoms:
if not hasattr(a, 'hbonds'): continue
for b in a.hbonds:
#only write a record if a is the donor
if b.donAt!=a: continue
#columns 1-6 + spaces for columns 7-12
s = 'HYDBND '
#columns 13-16 donor name
#strip off altloc + save it
nameStr, altLoc = self.PdbWriter.formatName(a)
s = s + nameStr
#column 17 donor altLoc indicator
if altLoc: s = s + altLoc
else: s = s + ' '
#columns 18-20 donor parent name (residue type)
#column 21 space + column 22 chain id
s = s + a.parent.type + ' ' + a.parent.parent.id
#columns 23-27 donor parent number
#column 27 insertion code
#column 28 space
s = s + '%5d' %int(a.parent.number) + ' '
# write the OPTIONAL hydrogen atom info
hAt = b.hAt
if hAt is None:
s = s + " "
else:
#columns 30-33 hydrogen atom name
nameStr, altLoc = self.PdbWriter.formatName(hAt)
s = s + nameStr
#column 34 hydrogen atom altLoc indicator
if altLoc: s = s + altLoc
else: s = s + ' '
#column 35 space + column 36 chain id
s = s + ' ' + hAt.parent.parent.id
#columns 37-41 hydrogen atom parent number
# nb: 42 would be insertion code then 43 a space
s = s + '%5d' %int(hAt.parent.number) + ' '
# write the acceptor atom info
acc = b.accAt
#columns 44-47 acceptor name
nameStr, altLoc = self.PdbWriter.formatName(acc)
s = s + nameStr
#column 48 acceptor altLoc indicator
if altLoc: s = s + altLoc
else: s = s + ' '
#columns 49-51 acceptor parent name (residue type)
#column 52 space + column 53 chain id
s = s + acc.parent.type + ' ' + acc.parent.parent.id
#columns 54-58 acceptor parent number
# nb: 59 would be insertion code
# ???? non implemented->
# 60-65 symmetry operator for 1st non-hyd. atom
s = s + '%5d' %int(acc.parent.number) + ' \n'
fptr.write(s)
def doit(self, filename, nodes):
#writeAssembly
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
nodes = nodes.findType(Atom)
hbats = nodes.get(lambda x: hasattr(x, 'hbonds'))
if hbats is None:
self.warningMsg('no atoms with hbonds specified')
return 'ERROR'
#CHECK FOR presence and uniqueness of chain ids
chains = nodes.parent.uniq().parent.uniq()
fptr = open(filename, 'w')
#to write:
self.writeHYDBNDRecords(nodes, fptr)
for ch in chains:
for at in ch.residues.atoms:
self.PdbWriter.write_atom(fptr, at)
try:
self.PdbWriter.write_TER(fptr, at)
except:
ostr =self.PdbWriter.defineTERRecord(at)
fptr.write(ostr)
fptr.close()
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
nodes = self.vf.getSelection()
if not len(nodes): return None
nodes = nodes.findType(Atom)
hbats = AtomSet(nodes.get(lambda x: hasattr(x, 'hbonds')))
if not hbats:
self.warningMsg('no atoms with hbonds specified')
return 'ERROR'
chains = nodes.parent.uniq().parent.uniq()
self.fixIDS(chains)
file = self.vf.askFileSave(types=[('pdb files', '*.pdb'),
('any', '*.*')], title="file to write hbonded chains\n(could be >1 molecule):")
if file is None: return
self.doitWrapper(file, nodes)
WriteAssemblyHBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Write Assembly with Hbonds',
'menuCascadeName': 'Assemblies'}
WriteAssemblyHBondsGUI = CommandGUI()
WriteAssemblyHBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'Write Hbonded Chains as 1 Mol', cascadeName='Assemblies')
class WriteIntermolHBonds(MVCommand):
"""Command to write files specifying intermolecular hydrogen bonds
\nPackage : Pmv
\nModule : hbondCommands
\nClass : WriteIntermolHBonds
\nCommand : writeIntermolHB
\nSynopsis:\n
None <- writeIntermolHB(filename, nodes, **kw)
\nRequired Arguments:\n
filename --- name of the hbond file\n
nodes --- TreeNodeSet holding the current selection
"""
def __call__(self, filename, nodes, **kw):
"""None <- writeIntermolHB(filename, nodes, **kw)
\nfilename --- name of the hbond file
\nnodes --- TreeNodeSet holding the current selection """
apply(self.doitWrapper, (filename, nodes,), kw)
def doit(self, filename, nodes):
#writeIntermolHBonds
nodes = self.vf.expandNodes(nodes)
if len(nodes)==0: return 'ERROR'
nodes = nodes.findType(Atom)
hbats = AtomSet(nodes.get(lambda x: hasattr(x, 'hbonds')))
if not hbats:
self.warningMsg('no atoms with hbonds specified')
return 'ERROR'
bnds = []
for at in hbats:
for b in at.hbonds:
if b.donAt.top!=b.accAt.top and b not in bnds:
bnds.append(b)
if not len(bnds):
self.warningMsg('no intermolecular hydrogen bonds in specified atoms')
return 'ERROR'
fptr = open(filename, 'w')
for b in bnds:
outstring = ''+b.donAt.full_name() + ',' + b.accAt.full_name()
if b.hAt is not None:
outstring = outstring + ',' + b.hAt.full_name()
outstring = outstring + '\n'
fptr.write(outstring)
fptr.close()
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
file = self.vf.askFileSave(types=[('hbnd files', '*.hbnd'),
('any', '*.*')], title="file to write intermolecular hbonds:")
if file is None: return
nodes = self.vf.getSelection()
if not len(nodes): return None
self.doitWrapper(file, nodes)
WriteIntermolHBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Write Intermolecular Hbonds',
'menuCascadeName': 'Assemblies'}
WriteIntermolHBondsGUI = CommandGUI()
WriteIntermolHBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'Write Intermolecular Hbonds', cascadeName='Assemblies')
class ReadIntermolHBonds(MVCommand):
"""Command to read files specifying intermolecular hydrogen bonds
\nPackage : Pmv
\nModule : hbondCommands
\nClass : ReadIntermolHBonds
\nCommand : readIntermolHB
\nSynopsis:\n
None <--- readIntermolHB(filename, nodes, **kw)
\nRequired Arguments:\n
filename --- name of the hbond file
"""
def __call__(self, filename, **kw):
"""None <--- readIntermolHB(filename, nodes, **kw)
\nfilename --- name of the hbond file"""
if not os.path.exists(filename):
raise IOError
apply(self.doitWrapper, (filename,), kw)
def doit(self, filename):
#read IntermolHBonds
fptr = open(filename, 'r')
allLines = fptr.readlines()
fptr.close()
ctr = 0
for line in allLines:
lList = split(line,',')
donAt = self.vf.Mols.NodesFromName(lList[0])
if donAt is None:
msg = donAt + ' not in mv.allAtoms'
self.warningMsg(msg)
return 'ERROR'
else:
donAt = donAt[0]
if len(lList)==2:
accAt = self.vf.Mols.NodesFromName(lList[1][:-1])
else:
accAt = self.vf.Mols.NodesFromName(lList[1])
if accAt is None:
msg = accAt + ' not in mv.allAtoms'
self.warningMsg(msg)
return 'ERROR'
else:
accAt = accAt[0]
if len(lList)==3:
#there is a newlinecharacter
hAt = self.vf.Mols.NodesFromName(lList[2][:-1])
if hAt is None:
msg = hAt + ' not in mv.allAtoms'
self.warningMsg(msg)
return 'ERROR'
else:
hAt = hAt[0]
else: hAt = None
#at this point build a hbond
newHB = HydrogenBond(donAt, accAt, hAt)
for at in [donAt, accAt]:
if hasattr(at, 'hbonds'):
at.hbonds.append(newHB)
else:
at.hbonds = [newHB]
if hAt is not None:
hAt.hbonds = [newHB]
ctr = ctr + 1
msg = 'built '+str(ctr) + ' intermolecular hydrogen bonds'
self.warningMsg(msg)
def guiCallback(self):
if not len(self.vf.Mols):
self.warningMsg('no molecules in viewer')
return
file = self.vf.askFileOpen(types=[('hbnd files', '*.hbnd'),
('any', '*.*')], title="intermolecular hbonds file:")
if file is None: return
apply(self.doitWrapper, (file,), {})
ReadIntermolHBondsGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Read Intermolecular Hbonds',
'menuCascadeName': 'Assemblies'}
ReadIntermolHBondsGUI = CommandGUI()
ReadIntermolHBondsGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'Read Intermolecular Hbonds', cascadeName='Assemblies')
class AddHBondCommandGUICommand(MVCommand, MVAtomICOM):
"""GUI command wrapper for AddHBondCommand which allows user to add hbonds between selected atoms. Hydrogen bonds are built assuming user picked hydrogen atom (or donor atom if there is no hydrogen atom) first followed by the acceptor atom.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : AddHBondCommandGUICommand
\nCommand : addHBondGC
\nSynopsis:\n
None<---addHBondGC(atoms)
\nRequired Arguments:\n
atoms --- atom(s)
"""
def __init__(self, func=None):
MVCommand.__init__(self, func)
MVAtomICOM.__init__(self)
self.atomList = AtomSet([])
self.undoAtList = AtomSet([])
self.save = None
def onRemoveObjectFromViewer(self, obj):
removeAts = AtomSet([])
for at in self.atomList:
if at in obj.allAtoms:
removeAts.append(at)
self.atomList = self.atomList - removeAts
removeAts = AtomSet([])
for at in self.undoAtList:
if at in obj.allAtoms:
removeAts.append(at)
self.undoAtList = self.undoAtList - removeAts
self.update()
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('setICOM'):
self.vf.loadCommand('interactiveCommands', 'setICOM', 'Pmv',
topCommand=0)
miscGeom = self.vf.GUI.miscGeom
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.masterGeom = Geom('addHBondGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
self.spheres = Spheres(name='addHBondSpheres', shape=(0,3),
inheritMaterial=0,
radii=0.2, quality=15,
materials = ((1.,1.,0.),), protected=True)
self.vf.GUI.VIEWER.AddObject(self.spheres, parent=self.masterGeom)
def __call__(self, atoms, **kw):
"""None<-addHBondGC(atoms)
\natoms : atom(s)"""
if type(atoms) is StringType:
self.nodeLogString = "'"+atoms+"'"
ats = self.vf.expandNodes(atoms)
if not len(ats): return 'ERROR'
return apply(self.doitWrapper, (ats,), kw)
def doit(self, ats):
#addHBondGC
#can only do it on first two picked
if len(ats)>2:
ats = ats[:2]
for at in ats:
#check for repeats of same atom
lenAts = len(self.atomList)
if lenAts and at==self.atomList[-1]:
continue
self.atomList.append(at)
self.undoAtList.append(at)
lenAts = len(self.atomList)
self.update()
#if only have one atom, there is nothing else to do
if lenAts<2: return
#now build hbonds between pairs of atoms
atSet = self.atomList
if lenAts%2!=0:
atSet = atSet[:-1]
#all pairs of atoms will be bonded
#so keep only the last one
self.atomList = atSet[-1:]
lenAts = lenAts -1
else:
self.atomList = AtomSet([])
newHB = self.vf.addHBond(atSet[0], atSet[1])
#to update display, need to call appropriate commands
geomList = [self.vf.showHBonds.lines, self.vf.hbondsAsSpheres.spheres]
cmdList = [self.vf.showHBonds, self.vf.hbondsAsSpheres]
#FIX THIS: extrude geoms are too slow
#if len(self.vf.extrudeHBonds.geoms):
#geomList.append(self.vf.extrudeHBonds.geoms[0])
#cmdList.append(self.vf.extrudeHBonds)
for i in range(len(geomList)):
geom = geomList[i]
cmd = cmdList[i]
hats = AtomSet(self.vf.allAtoms.get(lambda x: hasattr(x,'hbonds')))
if len(geom.vertexSet):
#first call dismiss_cb???
apply(cmd.dismiss_cb,(),{})
d = {}
d['topCommand']=0
#update a visible geometry here
apply(cmd,(hats,), d)
self.update()
def setupUndoAfter(self, ats, **kw):
lenUndoAts = len(self.undoAtList)
lenAts = len(ats)
if lenAts==1:
#after adding 1 self.atomList would be 1 or 0
if len(self.atomList)==1:
s = '0'
ustr='"c=self.addHBondGC;c.atomList=c.atomList[:'+s+'];c.undoAtList=c.undoAtList[:-1];c.update()"'
else:
ind = str(lenUndoAts - 2)
ustr = '"c=self.addHBondGC;nodes=self.expandNodes('+'\''+self.undoAtList[-2:].full_name()+'\''+'); self.removeHBondGC(nodes, topCommand=0);c.atomList=nodes[:1];c.undoAtList=c.undoAtList[:'+ind+'];c.update()"'
elif lenUndoAts>lenAts:
ustr='"c=self.addHBondGC;nodes=self.expandNodes('+'\''+ats.full_name()+'\''+');self.removeHBondGC(nodes, topCommand=0);c.undoAtList=c.undoAtList[:'+str(lenAts)+']"'
else:
ustr='"c=self.addHBondGC;nodes=self.expandNodes('+'\''+ats.full_name()+'\''+');self.removeHBondGC(nodes, topCommand=0);c.undoAtList=c.undoAtList[:0]"'
if len(self.atomList) and lenAts>1:
atStr = self.atomList.full_name()
estr = ';nodes=self.expandNodes('+'\''+self.atomList.full_name()+'\''+');c.atomList=nodes;c.update()"'
ustr = ustr + estr
self.undoCmds = "exec("+ustr+")"
def update(self, event=None):
if not len(self.atomList):
self.spheres.Set(vertices=[], tagModified=False)
self.vf.labelByExpression(self.atomList, negate=1, topCommand=0)
self.vf.GUI.VIEWER.Redraw()
return
self.lineVertices=[]
#each time have to recalculate lineVertices
for at in self.atomList:
c1 = getTransformedCoords(at)
self.lineVertices.append(tuple(c1))
self.spheres.Set(vertices=self.lineVertices, tagModified=False)
self.vf.labelByExpression(self.atomList,
function = 'lambda x: x.full_name()',
lambdaFunc = 1,
textcolor = 'yellow',
format = '', negate = 0,
location = 'Last', log = 0,
font = 'arial1.glf', only = 1,
topCommand=0)
#setting spheres doesn't trigger redraw so do it explicitly
self.vf.GUI.VIEWER.Redraw()
def guiCallback(self, event=None):
self.save = self.vf.ICmdCaller.commands.value["Shift_L"]
self.vf.setICOM(self, modifier="Shift_L", topCommand=0)
def startICOM(self):
self.vf.setIcomLevel( Atom )
AddHBondGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Add Hydrogen Bonds',
'menuCascadeName': 'Edit'}
AddHBondCommandGUICommandGUI=CommandGUI()
AddHBondCommandGUICommandGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds', 'Add Hydrogen Bonds', cascadeName='Edit')
class AddHBondCommand(MVCommand):
"""AddHBondCommand allows user to add hydrogen bonds between pairs of atoms.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : AddHBondCommand
\nCommand : addHBond
\nSynopsis:\n
None<---addHBond(atom1, atom2)
\nRequired Arguments:\n
atom1 --- first atom\n
atom2 --- second atom
"""
def setupUndoBefore(self, atom1, atom2):
self.addUndoCall((atom1.full_name(),atom2.full_name()),{'topCommand':0},
self.vf.removeHBond.name)
def undo(self, atom1, atom2, **kw):
self.vf.removeHBond(atom1, atom2, topCommand=0)
def __call__(self, atom1, atom2, **kw):
"""None<-addHBond(atom1, atom2)
\natom1 --- first atom
\natom2 --- second atom """
ats = self.vf.expandNodes(atom1)
if not len(ats): return 'ERROR'
at1 = ats[0]
ats = self.vf.expandNodes(atom2)
if not len(ats): return 'ERROR'
at2 = ats[0]
#check that at1 and at2 are not already in an hbond
if hasattr(at1, 'hbonds') and hasattr(at2, 'hbonds'):
for b in at1.hbonds:
if b.donAt==at2 or b.hAt==at2 or b.accAt==at2:
return 'ERROR'
for b in at2.hbonds:
if b.donAt==at2 or b.hAt==at2 or b.accAt==at2:
return 'ERROR'
return apply(self.doitWrapper, (at1, at2), kw)
def doit(self, at1, at2):
#addHBond
#this assumes atoms are picked in order
#from donor to acceptor
donAt = at1
accAt = at1
if at1.element=='H':
hAt = at1
accAt = at2
elif at2.element=='H':
hAt = at2
accAt = at1
else:
hAt = None
if hAt is not None :
b = hAt.bonds[0]
donAt = b.atom1
if id(donAt)==id(hAt):
donAt = b.atom2
newHB = HydrogenBond( donAt, accAt, hAt=hAt)
if not hasattr(accAt, 'hbonds'):
accAt.hbonds=[]
if not hasattr(donAt, 'hbonds'):
donAt.hbonds=[]
accAt.hbonds.append(newHB)
donAt.hbonds.append(newHB)
#hydrogens can have only 1 hbond
if hAt is not None :
hAt.hbonds = [newHB]
return newHB
class RemoveHBondCommandGUICommand(MVCommand, MVBondICOM):
"""RemoveHBondCommandGUICommand allows user to remove hbonds between
picked atoms.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : RemoveHBondCommandGUICommand
\nCommand : removeHBondGC
\nSynopsis:\n
None <- removeHBondGC(atoms, **kw)
\nRequired Arguments:\n
atoms: atoms to remove hbonds between
"""
def onAddCmdToViewer(self):
if not self.vf.commands.has_key('setICOM'):
self.vf.loadCommand('interactiveCommands', 'setICOM', 'Pmv',
topCommand=0)
hbond_geoms = check_hbond_geoms(self.vf.GUI)
self.masterGeom = Geom('removeBondGeoms',shape=(0,0),
pickable=0, protected=True)
self.masterGeom.isScalable = 0
self.vf.GUI.VIEWER.AddObject(self.masterGeom, parent=hbond_geoms)
self.spheres = Spheres(name='removeBondSpheres', shape=(0,3),
inheritMaterial=0,
radii=0.2, quality=15,
materials = ((1.,0.,0.),), protected=True)
self.vf.GUI.VIEWER.AddObject(self.spheres, parent=self.masterGeom)
def __init__(self, func = None):
MVCommand.__init__(self, func)
MVBondICOM.__init__(self)
self.pickLevel = 'parts'
self.undoBondList = []
self.save = None
def guiCallback(self):
self.save = self.vf.ICmdCaller.commands.value["Shift_L"]
self.vf.setICOM(self, modifier="Shift_L", topCommand = 0)
self.vf.setIcomLevel(Atom)
def stop(self):
self.done_cb()
def getObjects(self, pick):
for o, val in pick.hits.items(): ###loop over geometries
primInd = map(lambda x: x[0], val)
g = o.mol.geomContainer
if g.geomPickToBonds.has_key(o.name):
func = g.geomPickToBonds[o.name]
if func: return func(o, primInd)
else:
l = []
bonds = g.atoms[o.name].bonds[0]
if not len(bonds): return BondSet()
for i in range(len(primInd)):
l.append(bonds[int(primInd[i])])
return BondSet(l)
def dismiss(self):
self.vf.setICOM(self.save, modifier="Shift_L", topCommand = 0)
self.save = None
self.done_cb()
def done_cb(self):
pass
def __call__(self, atoms, **kw):
"""None <- removeHBondGC(atoms, **kw)
atoms: atoms to remove hbonds between
"""
if type(atoms) is StringType:
self.nodeLogString = "'"+atoms+"'"
ats = self.vf.expandNodes(atoms)
if not len(ats): return 'ERROR'
apply(self.doitWrapper, (ats,), kw)
def doit(self, ats):
#removeHBondGC
hats = AtomSet(ats.get(lambda x: hasattr(x, 'hbonds')))
if not len(hats): return 'ERROR'
for at in hats:
if not hasattr(at, 'hbonds'):
continue
if not len(at.hbonds):
delattr(at, 'hbonds')
continue
for hbnd in at.hbonds:
if at==hbnd.donAt:
if hbnd.accAt in hats:
self.vf.removeHBond(at, hbnd.accAt)
elif at==hbnd.accAt:
if hbnd.donAt in hats:
self.vf.removeHBond(hbnd.donAt, at)
elif hbnd.hAt in hats:
self.vf.removeHBond(hbnd.hAt, at)
else:
#in this case at is hydrogen atom of hbond
if hbnd.accAt in hats:
self.vf.removeHBond(at, hbnd.accAt)
#FIX THIS: update the geoms as above in addHBonds
#to update display, need to call appropriate commands
geomList = [self.vf.showHBonds.lines, self.vf.hbondsAsSpheres.spheres]
cmdList = [self.vf.showHBonds, self.vf.hbondsAsSpheres]
#FIX THIS: extrude is too slow
#if len(self.vf.extrudeHBonds.geoms):
#geomList.append(self.vf.extrudeHBonds.geoms[0])
#cmdList.append(self.vf.extrudeHBonds)
for i in range(len(geomList)):
geom = geomList[i]
cmd = cmdList[i]
hats = AtomSet(self.vf.allAtoms.get(lambda x: hasattr(x,'hbonds')))
if len(geom.vertexSet):
#first call dismiss_cb???
apply(cmd.dismiss_cb,(),{})
d = {}
d['topCommand']=0
#update visible geometry here
apply(cmd,(hats,),d)
def setupUndoAfter(self, ats, **kw):
lenUndoAts = len(self.undoAtList)
lenAts = len(ats)
if lenAts==1:
#after removing 1 self.atomList would be 1 or 0
if len(self.atomList)==1:
s = '0'
ustr='"c=self.removeHBondGC;c.atomList=c.atomList[:'+s+'];c.undoAtList=c.undoAtList[:-1];c.update()"'
else:
ind = str(lenUndoAts - 2)
ustr = '"c=self.removeHBondGC;nodes=self.expandNodes('+'\''+self.undoAtList[-2:].full_name()+'\''+'); self.addHBondGC(nodes, topCommand=0);c.atomList=nodes[:1];c.undoAtList=c.undoAtList[:'+ind+'];c.update()"'
elif lenUndoAts>lenAts:
ustr='"c=self.removeHBondGC;nodes=self.expandNodes('+'\''+ats.full_name()+'\''+');self.addHBondGC(nodes, topCommand=0);c.undoAtList=c.undoAtList[:'+str(lenAts)+']"'
else:
ustr='"c=self.removeHBondGC;nodes=self.expandNodes('+'\''+ats.full_name()+'\''+');self.addHBondGC(nodes, topCommand=0);c.undoAtList=c.undoAtList[:0]"'
if len(self.atomList) and lenAts>1:
atStr = self.atomList.full_name()
estr = ';nodes=self.expandNodes('+'\''+self.atomList.full_name()+'\''+');c.atomList=nodes;c.update()"'
ustr = ustr + estr
self.undoCmds = "exec("+ustr+")"
RemoveHBondGuiDescr = {'widgetType':'Menu',
'menuBarName':'menuRoot',
'menuButtonName':'Hydrogen Bonds',
'menuEntryLabel':'Remove Hydrogen Bond',
'menuCascadeName': 'Edit'}
RemoveHBondCommandGUICommandGUI=CommandGUI()
RemoveHBondCommandGUICommandGUI.addMenuCommand('menuRoot', 'Hydrogen Bonds',
'Remove Hydrogen Bonds', cascadeName='Edit')
class RemoveHBondCommand(MVCommand):
"""RemoveHBondCommand allows user to remove hydrogen bonds between specified
atoms.
\nPackage : Pmv
\nModule : hbondCommands
\nClass : RemoveHBondCommand
\nCommand : removeHBond
\nSynopsis:\n
None<-removeHBond(atom1, accAt)
\nRequired Arguments:\n
atom1 --- donAt or hAt of bond\n
accAt --- accAt of bond
"""
def setupUndoBefore(self, atom1, atom2):
self.addUndoCall((atom1.full_name(),atom2.full_name()),{'topCommand':0},
self.vf.addHBond.name)
def __call__(self, atom1, accAt, **kw):
"""None<-removeHBond(atom1, accAt)
\natom1 --- donAt or hAt of bond
\naccAt --- accAt of bond"""
ats = self.vf.expandNodes(atom1)
if not len(ats): return 'ERROR'
at1 = ats[0]
ats = self.vf.expandNodes(accAt)
if not len(ats): return 'ERROR'
accAt = ats[0]
return apply(self.doitWrapper, (at1, accAt), kw)
def doit(self, atom1, accAt):
b = None
for hb in atom1.hbonds:
if hb.accAt == accAt:
#found the bond to remove
b = hb
#if no bond exists between these atoms, return error
if b is None:
return 'ERROR'
#only remove one bond here
accAt.hbonds.remove(b)
if not len(accAt.hbonds):
delattr(accAt,'hbonds')
hAt = b.hAt
if hAt is not None:
donAt = b.donAt
hAt.hbonds.remove(b)
delattr(hAt,'hbonds')
donAt.hbonds.remove(b)
if not len(donAt.hbonds):
delattr(donAt,'hbonds')
else:
#in this case, atom1 was the donAt
atom1.hbonds.remove(b)
if not len(atom1.hbonds):
delattr(atom1,'hbonds')
del b
return
commandList=[
{'name':'getHBDonors','cmd':GetHydrogenBondDonors(), 'gui':None},
{'name':'getHBAcceptors','cmd':GetHydrogenBondAcceptors(), 'gui':None},
{'name':'getHBondEnergies','cmd':GetHydrogenBondEnergies(), 'gui': None},
{'name':'showHBDA','cmd':ShowHBDonorsAcceptors(),
'gui':ShowHBDonorsAcceptorsGUI},
{'name':'showHBonds','cmd':ShowHydrogenBonds(), 'gui':ShowHydrogenBondsGUI},
{'name':'buildHBondsGC','cmd':BuildHydrogenBondsGUICommand(),
'gui': BuildHydrogenBondsGUICommandGUI},
{'name':'buildHBonds','cmd':BuildHydrogenBonds(), 'gui': None},
{'name':'addHBondHsGC','cmd':AddHBondHydrogensGUICommand(),
'gui': AddHBondHydrogensGUICommandGUI},
{'name':'addHBondHs','cmd':AddHBondHydrogens(), 'gui': None},
{'name':'hbondsAsSpheres','cmd':DisplayHBondsAsSpheres(),
'gui':DisplayHBondsAsSpheresGUI},
{'name':'hbondsAsCylinders','cmd':DisplayHBondsAsCylinders(),
'gui':DisplayHBondsAsCylindersGUI},
{'name':'extrudeHBonds','cmd':ExtrudeHydrogenBonds(), 'gui':ExtrudeHydrogenBondsGUI},
{'name':'addHBondGC','cmd':AddHBondCommandGUICommand(),
'gui': AddHBondCommandGUICommandGUI},
{'name':'addHBond','cmd':AddHBondCommand(), 'gui': None},
{'name':'removeHBondGC','cmd':RemoveHBondCommandGUICommand(),
'gui': RemoveHBondCommandGUICommandGUI},
{'name':'removeHBond','cmd':RemoveHBondCommand(), 'gui': None},
{'name':'limitHBonds','cmd':LimitHydrogenBonds(), 'gui':LimitHydrogenBondsGUI},
{'name':'readIntermolHBonds','cmd':ReadIntermolHBonds(),
'gui':ReadIntermolHBondsGUI},
{'name':'writeIntermolHBonds','cmd':WriteIntermolHBonds(),
'gui':WriteIntermolHBondsGUI},
{'name':'writeHBondAssembly','cmd':WriteAssemblyHBonds(),
'gui':WriteAssemblyHBondsGUI},
]
def initModule(viewer):
for dict in commandList:
viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])
```
#### File: blender/test/PyRosetta-PMV.py
```python
import sys,os
MGL_ROOT=os.environ['MGL_ROOT']
sys.path[0]=(MGL_ROOT+'lib/python2.5/site-packages')
sys.path.append(MGL_ROOT+'lib/python2.5/site-packages/PIL')
sys.path.append(MGL_ROOT+'/MGLToolsPckgs')
from Pmv.moleculeViewer import EditAtomsEvent
import time
from mglutil import hostappli
####################blender specific###################
import Pmv.hostappInterface.pdb_blender as epmv
import Blender
from Blender import Window, Scene, Draw
self=epmv.start(debug=1)
sc=Blender.Scene.GetCurrent()
#########################################################
plugDir=hostappli.__path__[0]
with_pmv = True
rConf=1
pmv_state = 1
nDecoys=5
def pmv_show(pose,self):
from Pmv.moleculeViewer import EditAtomsEvent
global pmv_state
import time
#if not with_pmv: return
model = self.getMolFromName("test")
model.allAtoms.setConformation(1)
coord = {}
print pose.n_residue(),len(model.chains.residues)
for resi in range(1, pose.n_residue()+1):
res = pose.residue(resi)
resn = pose.pdb_info().number(resi)
#print resi,res.natoms(),len(model.chains.residues[resi-1].atoms)
k=0
for atomi in range(1, res.natoms()+1):
name = res.atom_name(atomi).strip()
if name != 'NV' :
a=model.chains.residues[resi-1].atoms[k]
pmv_name=a.name
k = k + 1
if name != pmv_name :
if name[1:] != pmv_name[:-1]:
print name,pmv_name
else :
coord[(resn, pmv_name)] = res.atom(atomi).xyz()
cood=res.atom(atomi).xyz()
a._coords[1]=[cood.x,cood.y,cood.z]
else :
coord[(resn, name)] = res.atom(atomi).xyz()
cood=res.atom(atomi).xyz()
a._coords[1]=[cood.x,cood.y,cood.z] #return coord
event = EditAtomsEvent('coords', model.allAtoms)
self.dispatchEvent(event)
#modEvent = ModificationEvent('edit','coords', mol.allAtoms)
#mol.geomContainer.updateGeoms(modEvent)
#PMV
#self.GUI.VIEWER.Redraw()
#time.sleep(.1)
#Blender
epmv.insertKeys(model.geomContainer.geoms['cpk'],1)
epmv.getCurrentScene().update()
Draw.Redraw()
Draw.Redraw(1)
Blender.Redraw()
def pmv_load(f):
if not with_pmv: return
mol=self.getMolFromName("test")
if mol is None :
self.readMolecule(f)
mol=self.Mols[0]
for i in range(nDecoys):
mol.allAtoms.addConformation(mol.allAtoms.coords[:])
#mol.name="tset"
print mol.name
#self.displaySticksAndBalls("test",log=1)
self.displayCPK("test:::",log=1)
self.colorAtomsUsingDG("test",log=1)
#cmd.show("cartoon", "decoy")
from rosetta import *
rosetta.init()
pose = Pose(plugDir+"/data/test_fragments.pdb")
dump_pdb(pose, plugDir+"/data/test.pdb")
pmv_load(plugDir+"/data/test.pdb")
pmv_show(pose,self)
scorefxn = core.scoring.ScoreFunction()
scorefxn.set_weight(core.scoring.fa_atr, 1.0)
scorefxn.set_weight(core.scoring.fa_rep, 1.0)
scorefxn.set_weight(core.scoring.hbond_sr_bb, 1.0)
scorefxn.set_weight(core.scoring.hbond_lr_bb, 1.0)
scorefxn.set_weight(core.scoring.hbond_bb_sc, 1.0)
scorefxn.set_weight(core.scoring.hbond_sc, 1.0)
#switch = SwitchResidueTypeSetMover("centroid")
#switch.apply(pose)
#scorefxn = create_score_function("score3")
import random, math, time
def perturb(new_pose,pose):
import random, math, time
res = random.randrange(1,11)
if random.randrange(0,2)==0:
new_pose.set_phi(res, pose.phi(res)+random.gauss(0, 25))
else:
new_pose.set_psi(res, pose.psi(res)+random.gauss(0, 25))
from rosetta.core.fragment import *
fragset = core.fragment.ConstantLengthFragSet(3)
fragset.read_fragment_file(plugDir+"/data/test3_fragments")
movemap = core.kinematics.MoveMap()
movemap.set_bb(True)
mover_3mer = ClassicFragmentMover(fragset,movemap)
log = open("log", 'w')
def fold(pose,self,scorefxn,perturb,mover_3mer,pmv_show):
import random, math, time
kt = 1
print "ok Fold"
low_pose = Pose()
low_score = scorefxn(pose)
new_pose = Pose()
maxit = 1000
start_time = time.time()
stat = {"E":0,"A":0,"R":0}
for it in range(0, maxit):
print "in the loop"
if it==maxit/2: pose.assign(low_pose)
score = scorefxn(pose)
new_pose.assign(pose)
if it<maxit/2: mover_3mer.apply(new_pose)
else: perturb(new_pose,pose)
new_score = scorefxn(new_pose)
delE = new_score-score
if delE<0:
score = new_score
pose.assign(new_pose)
action = "E"
else:
if random.random()<math.exp(-delE/kt):
score = new_score
pose.assign(new_pose)
action = "A"
else: action = "R"
if score<low_score:
low_score = score
low_pose.assign(pose)
print it,"\t",score,"\t",low_score,"\t",action
#log.write(str(score)+"\t"+str(low_score)+"\t"+str(action)+"\n")
stat[action] += 1
if action<>"R": pmv_show(pose,self)
duration = time.time()-start_time
print "took ",duration,"s\t",duration/float(maxit),"s/it"
#print "E:",stat["E"]/float(maxit),"\t","A:",stat["A"]/float(maxit),"\t","R:",stat["R"]/float(maxit)
print low_score
pmv_show(low_pose,self)
return low_pose
def angle(a):
return math.fmod(a,180)
"""
for i in range(0, 1):
pose2 = Pose()
pose2.assign(pose)
low_pose = fold(pose2)
print i,
for i in range(1,11):
log.write(str(angle(low_pose.phi(i)))+"\t"+str(angle(low_pose.psi(i)))+"\n")
import threading
def run(self):
thread = threading.Thread(target=fold, args=(pose,self,scorefxn,perturb,mover_3mer,pmv_show))
thread.setDaemon(1)
thread.start()
"""
import time
time.sleep(1.)
#fold(pose,self)
#import thread
#thread.start_new(fold, (pose,self))
#run(self)
fold(pose,self,scorefxn,perturb,mover_3mer,pmv_show)
```
#### File: hostappInterface/Chimera/chimeraAdaptor.py
```python
from Pmv.hostappInterface.epmvAdaptor import epmvAdaptor
from Pmv.hostappInterface.Chimera import chimeraHelper
#import Pmv.hostappInterface.pdb_blender as None #
class chimeraAdaptor(epmvAdaptor):
def __init__(self,mv=None,debug=0):
epmvAdaptor.__init__(self,mv,host='chimera',debug=debug)
self.soft = 'chimera'
self.helper = chimeraHelper
#scene and object helper function
self._getCurrentScene = chimeraHelper.getCurrentScene
self._addObjToGeom = chimeraHelper.addObjToGeom
self._host_update = None#None #.update
self._parseObjectName = None#None #.parseObjectName
self._getObjectName = None#None #.getObjectName
self._getObject = None#None #.getObject
self._addObjectToScene = chimeraHelper.addObjectToScene
self._toggleDisplay = None#None #.toggleDisplay
self._newEmpty = chimeraHelper.newEmpty
#camera and lighting
self._addCameraToScene = None#None #.addCameraToScene
self._addLampToScene = None#None #.addLampToScene
#display helper function
self._editLines = None#None #.editLines
self._createBaseSphere = None#None #.createBaseSphere
self._instancesAtomsSphere = None #.instancesAtomsSphere
self._Tube = None #.Tube
self._createsNmesh = chimeraHelper.createsNmesh
self._PointCloudObject = None #.PointCloudObject
#modify/update geom helper function
self._updateSphereMesh = None #.updateSphereMesh
self._updateSphereObj = None #.updateSphereObj
self._updateSphereObjs = None #.updateSphereObjs
self._updateTubeMesh = None #.updateTubeMesh
self._updateTubeObj = None #.updateTubeObj
self._updateMesh = chimeraHelper.updateMesh
#color helper function
self._changeColor = None #.changeColor
self._checkChangeMaterial = None #.checkChangeMaterial
self._changeSticksColor = None #.changeSticksColor
self._checkChangeStickMaterial = None #.checkChangeStickMaterial
#define the general function
self._progressBar = None#Blender.Window.DrawProgressBar
def _resetProgressBar(self,max):
pass
def _makeRibbon(self,name,coords,shape=None,spline=None,parent=None):
return None
"""sc=self._getCurrentScene()
if shape is None :
shape = sc.objects.new(self.helper.bezCircle(0.3,name+"Circle"))
if spline is None :
obSpline,spline = self.helper.spline(name,coords,extrude_obj=shape,scene=sc)
if parent is not None :
parent.makeParent([obSpline])
return obSpline"""
```
#### File: hostappInterface/cinema4d/helperC4D.py
```python
import c4d
import c4d.symbols as sy
#import c4d.documents
#import c4d.plugins
#from c4d import plugins
#from c4d import tools
#from c4d.gui import *
#from c4d.plugins import *
#standardmodule
import numpy
import numpy.oldnumeric as Numeric
import sys, os, os.path, struct, math, string
import types
import math
from math import *
from types import StringType, ListType
#this id can probably found in c4d.symbols
#TAG ID
POSEMIXER = 100001736
IK = 1019561
PYTAG = 1022749
Follow_PATH = 5699
LOOKATCAM = 1001001
SUNTAG=5678
#OBJECT ID
INSTANCE = 5126
BONE = 1019362
CYLINDER = 5170
CIRCLE = 5181
RECTANGLE = 5186
FOURSIDE = 5180
LOFTNURBS= 5107
SWEEPNURBS=5118
TEXT = 5178
CLONER = 1018544
MOINSTANCE = 1018957
ATOMARRAY = 1001002
METABALLS = 5125
LIGHT = 5102
CAMERA = 5103
#PARAMS ID
PRIM_SPHERE_RAD = 1110
#MATERIAL ATTRIB
LAYER=1011123
GRADIANT=1011100
FUSION = 1011109
#COMMAND ID
OPTIMIZE = 14039
VERBOSE=0
DEBUG=0
#MGLTOOLS module
import MolKit
from MolKit.molecule import Atom, AtomSet, BondSet, Molecule , MoleculeSet
from MolKit.protein import Protein, ProteinSet, Residue, Chain, ResidueSet,ResidueSetSelector
from MolKit.stringSelector import CompoundStringSelector
from MolKit.tree import TreeNode, TreeNodeSet
from MolKit.molecule import Molecule, Atom
from MolKit.protein import Residue
#PMV module
from Pmv.moleculeViewer import MoleculeViewer
from Pmv.displayCommands import BindGeomToMolecularFragment
from Pmv.trajectoryCommands import PlayTrajectoryCommand
#Pmv Color Palette
from Pmv.pmvPalettes import AtomElements
from Pmv.pmvPalettes import DavidGoodsell, DavidGoodsellSortedKeys
from Pmv.pmvPalettes import RasmolAmino, RasmolAminoSortedKeys
from Pmv.pmvPalettes import Shapely
from Pmv.pmvPalettes import SecondaryStructureType
from Pmv.pmvPalettes import DnaElements
#computation
#from Pmv.amberCommands import Amber94Config, CurrentAmber94
from Pmv.hostappInterface import comput_util as C
from Pmv.hostappInterface import cinema4d as epmvc4d
plugDir=epmvc4d.__path__[0]
SSShapes={ 'Heli':FOURSIDE,
'Shee':RECTANGLE,
'Coil':CIRCLE,
'Turn':CIRCLE,
'Stra':RECTANGLE
}
SSColor={ 'Heli':(238,0,127),
'Shee':(243,241,14),
'Coil':(255,255,255),
'Turn':(60,26,100),
'Stra':(255,255,0)}
#NOTES
#[900] <-> SetName
AtmRadi = {"A":"1.7","N":"1.54","C":"1.7","CA":"1.7","O":"1.52","S":"1.85","H":"1.2","P" : "1.04"}
DGatomIds=['ASPOD1','ASPOD2','GLUOE1','GLUOE2', 'SERHG',
'THRHG1','TYROH','TYRHH',
'LYSNZ','LYSHZ1','LYSHZ2','LYSHZ3','ARGNE','ARGNH1','ARGNH2',
'ARGHH11','ARGHH12','ARGHH21','ARGHH22','ARGHE','GLNHE21',
'GLNHE22','GLNHE2',
'ASNHD2','ASNHD21', 'ASNHD22','HISHD1','HISHE2' ,
'CYSHG', 'HN']
def lookupDGFunc(atom):
assert isinstance(atom, Atom)
if atom.name in ['HN']:
atom.atomId = atom.name
else:
atom.atomId=atom.parent.type+atom.name
if atom.atomId not in DGatomIds:
atom.atomId=atom.element
if atom.atomId not in AtmRadi.keys() : atom.atomId="A"
return atom.atomId
ResidueSelector=ResidueSetSelector()
def start(debug=0):
if VERBOSE : print "start ePMV - debug ",debug
mv = MoleculeViewer(logMode = 'unique', customizer=None, master=None,title='pmv', withShell= 0,verbose=False, gui = False)
mv.addCommand(BindGeomToMolecularFragment(), 'bindGeomToMolecularFragment', None)
mv.browseCommands('trajectoryCommands',commands=['openTrajectory'],log=0,package='Pmv')
#mv.browseCommands('amberCommands',package='Pmv')
mv.addCommand(PlayTrajectoryCommand(),'playTrajectory',None)
mv.embedInto('c4d',debug=debug)
mv.userpref['Read molecules as']['value']='conformations'
#DEBUG=debug
return mv
def reset_ePMV(mv, debug=0):
#need to restore the logEvent sytem for the right session
if VERBOSE : print "reset epmv debug",debug,mv
mv.embedInto('c4d',debug=debug)
def progressBar(progress,label):
#the progessbar use the StatusSetBar
c4d.StatusSetText(label)
c4d.StatusSetBar(int(progress*100.))
def resetProgressBar(value):
c4d.StatusClear()
def compareSel(currentSel,molSelDic):
for selname in molSelDic.keys():
if VERBOSE : print "The compareSelection ",currentSel,molSelDic[selname][3]
#if currentSel[-1] == ';' : currentSel=currentSel[0:-1]
if currentSel == molSelDic[selname] : return selname
def parseObjectName(o):
#problem if "_" exist the molecule name
if type(o) == str : name=o
else : name=o.GetName()
tmp=name.split("_")
if len(tmp) == 1 : #no "_" so not cpk (S_) or ball (B_) stick (T_) or Mesh (Mesh_)
return ""
else :
if tmp[0] == "S" or tmp[0] == "B" : #balls or cpk
hiearchy=tmp[1].split(":") #B_MOL:CHAIN:RESIDUE:ATOMS
return hiearchy
return ""
def parseName(o):
if type(o) == str : name=o
else : name=o.GetName()
tmp=name.split("_")
if len(tmp) == 1 : #molname
hiearchy=name.split(":")
if len(hiearchy) == 1 : return [name,""]
else : return hiearchy
else :
hiearchy=tmp[1].split(":") #B_MOL:CHAIN:RESIDUE:ATOMS
return hiearchy
#def get_editor_object_camera(doc):
# bd = doc.get_render_basedraw()
# cp = bd.get_scene_camera(doc)
# if cp is None: cp = bd.get_editor_camera()
# return cp
def getCurrentScene():
return c4d.documents.GetActiveDocument()
def update():
#getCurrentScene().GeSyncMessage(c4d.MULTIMSG_UP)
getCurrentScene().Message(c4d.MULTIMSG_UP)
c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_ANIMATION)
c4d.DrawViews(c4d.DA_NO_THREAD|c4d.DA_FORCEFULLREDRAW)
updateAppli = update
def getObjectName(o):
return o.GetName()
def getObject(name):
obj=None
if type(name) != str : return name
try :
obj=getCurrentScene().SearchObject(name)
except :
obj=None
return obj
def deleteObject(obj):
sc = getCurrentScene()
try :
print obj.GetName()
sc.SetActiveObject(obj)
c4d.CallCommand(100004787) #delete the obj
except:
print "problem deleting ", obj
def newEmpty(name,location=None,parentCenter=None,display=0,visible=0):
empty=c4d.BaseObject(c4d.Onull)
empty.SetName(name)
empty[1000] = display
empty[1001] = 1.0
if location != None :
if parentCenter != None :
location = location - parentCenter
empty.SetPos(c4dv(location))
return empty
def newInstance(name,object,location=None,c4dmatrice=None,matrice=None):
instance = c4d.BaseObject(INSTANCE)
instance[1001]=iMe[atN[0]]
instance.SetName(n+"_"+fullname)#.replace(":","_")
if location != None :
instance.SetPos(c4dv(location))
if c4dmatrice !=None :
#type of matre
instance.SetMg(c4dmatrice)
if matrice != None:
mx = matrix2c4dMat(matrice)
instance.SetMg(mx)
return instance
def setObjectMatrix(object,matrice,c4dmatrice=None):
if c4dmatrice !=None :
#type of matre
object.SetMg(c4dmatrice)
else :
mx = matrix2c4dMat(matrice,transpose=False)
object.SetMg(mx)
def concatObjectMatrix(object,matrice,c4dmatrice=None,local=True):
#local or global?
cmg = object.GetMg()
cml = object.GetMl()
if c4dmatrice !=None :
#type of matrice
if local :
object.SetMl(cml*c4dmatrice)
else :
object.SetMg(cmg*c4dmatrice)
else :
mx = matrix2c4dMat(matrice,transpose=False)
if local :
object.SetMl(cml*mx)
else :
object.SetMg(cmg*mx)
def getPosUntilRoot(obj):
stop = False
parent = obj.GetUp()
pos=c4d.Vector(0.,0.,0.)
while not stop :
pos = pos + parent.GetPos()
parent = parent.GetUp()
if parent is None :
stop = True
return pos
def addObjectToScene(doc,obj,parent=None,centerRoot=True,rePos=None):
#doc.start_undo()
if getObject(obj.GetName()) == None:
if parent != None :
if type(parent) == str : parent = getObject(parent)
doc.InsertObject(obj,parent=parent)
if centerRoot :
currentPos = obj.GetPos()
if rePos != None :
parentPos = c4dv(rePos)
else :
parentPos = getPosUntilRoot(obj)#parent.GetPos()
obj.SetPos(currentPos-parentPos)
else : doc.InsertObject(obj)
#add undo support
#doc.add_undo(c4d.UNDO_NEW, obj)
#doc.end_undo()
def AddObject(obj,parent=None,centerRoot=True,rePos=None):
doc = getCurrentScene()
#doc.start_undo()
if parent != None :
if type(parent) == str : parent = getObject(parent)
doc.InsertObject(obj,parent=parent)
if centerRoot :
currentPos = obj.GetPos()
if rePos != None :
parentPos = c4dv(rePos)
else :
parentPos = getPosUntilRoot(obj)#parent.GetPos()
obj.SetPos(currentPos-parentPos)
else : doc.InsertObject(obj)
def addObjToGeom(obj,geom):
if type(obj) == list or type(obj) == tuple:
if len(obj) > 2: geom.obj=obj
elif len(obj) == 1: geom.obj=obj[0]
elif len(obj) == 2:
geom.mesh=obj[1]
geom.obj=obj[0]
else : geom.obj=obj
def makeHierarchy(listObj,listName, makeTagIK=False):
for i,name in enumerate(listName) :
o = getObject(listObj[name])
if makeTagIK :
o.MakeTag(IK)
if i < len(listObj)-1 :
child = getObject(listObj[listName[i+1]])
child.InsertUnder(o)
def addIKTag(object):
object.MakeTag(IK)
def makeAtomHierarchy(res,parent,useIK=False):
doc = getCurrentScene()
backbone = res.backbone()
sidechain = res.sidechain()
for i,atm in enumerate(backbone):
rePos = None
prev_atom = None
at_center = atm.coords
at_obj = newEmpty(atm.full_name(),location=at_center)
bond_obj = newEmpty(atm.full_name()+"_bond")
if useIK :
addIKTag(at_obj)
addIKTag(bond_obj)
if i > 0 : prev_atom = backbone[i-1]
if prev_atom != None:
if VERBOSE : print "hierarchy backbone ",atm.name, prev_atom.name
rePos = prev_atom.coords
oparent = getObject(prev_atom.full_name()+"_bond")
if VERBOSE : print oparent.GetName()
addObjectToScene(doc,at_obj,parent=oparent,centerRoot=True,rePos=rePos)
else :
if VERBOSE : print "first atom", atm.name
addObjectToScene(doc,at_obj,parent=parent,centerRoot=True,rePos=rePos)
addObjectToScene(doc,bond_obj,parent=at_obj,centerRoot=False)
if atm.name == 'CA' :
#add the sidechain child of CA
side_obj = newEmpty(atm.full_name()+"_sidechain")
addObjectToScene(doc,side_obj,parent=at_obj,centerRoot=False)
for j,satm in enumerate(sidechain):
sat_center = satm.coords
sat_obj = newEmpty(satm.full_name(),location=sat_center)
sbond_obj = newEmpty(satm.full_name()+"_sbond")
addObjectToScene(doc,sat_obj,parent=side_obj,centerRoot=True,rePos=at_center)
addObjectToScene(doc,sbond_obj,parent=side_obj,centerRoot=False)
if useIK :
return bond_obj
else :
return parent
def makeResHierarchy(res,parent,useIK=False):
sc = getCurrentScene()
res_center = res.atoms.get("CA").coords[0]#or averagePosition of the residues?
res_obj = newEmpty(res.full_name(),location=res_center)
bond_obj = newEmpty(res.full_name()+"_bond")
rePos = None
prev_res = res.getPrevious()
if useIK :
addIKTag(res_obj)
if prev_res != None and useIK :
rePos = prev_res.atoms.get("CA").coords[0]
oparent = getObject(prev_res.full_name())
addObjectToScene(sc,res_obj,parent=oparent,centerRoot=True,rePos=rePos)
else :
addObjectToScene(sc,res_obj,parent=parent,centerRoot=True,rePos=rePos)
addObjectToScene(sc,bond_obj,parent=res_obj,centerRoot=False)
#mol.geomContainer.masterGeom.res_obj[res.name]=util.getObjectName(res_obj)
return res_obj
def addCameraToScene(name,Type,focal,center,sc):
cam = c4d.BaseObject(CAMERA)
cam.SetName(name)
cam.SetPos(c4dv(center))
cam[1001] = 1 #0:perspective, 1 :parrallel
cam[1000] = float(focal) #parrallel zoom
cam[1006] = 2*float(focal)#perspective focal
#rotation?
cam[904,1000] = pi/2.
addObjectToScene(sc,cam,centerRoot=False)
def addLampToScene(name,Type,rgb,dist,energy,soft,shadow,center,sc):
#type of light 0 :omni, 1:spot,2:squarespot,3:infinite,4:parralel,
#5:parrallel spot,6:square parral spot 8:area
#light sun type is an infinite light with a sun tag type
dicType={'Area':0,'Sun':3}
lamp = c4d.BaseObject(LIGHT)
lamp.SetName(name)
lamp.SetPos(c4dv(center))
lamp[904,1000] = pi/2.
lamp[90000]= c4d.Vector(float(rgb[0]), float(rgb[1]), float(rgb[2]))#color
lamp[90001]= float(energy) #intensity
lamp[90002]= dicType[Type] #type
if shadow : lampe[90003]=1 #soft shadow map
if Type == "Sun":
suntag = lamp.MakeTag(SUNTAG)
addObjectToScene(sc,lamp,centerRoot=False)
"""
lampe.setDist(dist)
lampe.setSoftness(soft)
"""
def reparent(obj,parent):
obj.InsertUnder(parent)
def setInstance(name,object,location=None,c4dmatrice=None,matrice=None):
instance = c4d.BaseObject(INSTANCE)
instance[1001]=object
instance.SetName(name)#.replace(":","_")
if location != None :
instance.SetPos(c4dv(location))
if c4dmatrice !=None :
#type of matre
instance.SetMg(c4dmatrice)
if matrice != None:
mx = matrix2c4dMat(matrice)
instance.SetMl(mx)
p = instance.GetPos()
instance.SetPos(c4d.Vector(p.y,p.z,p.x))
return instance
def translateObj(obj,position,use_parent=True):
if len(position) == 1 : c = position[0]
else : c = position
#print "upadteObj"
newPos=c4dv(c)
if use_parent :
parentPos = getPosUntilRoot(obj)#parent.GetPos()
newPos = newPos - parentPos
obj.SetPos(newPos)
else :
pmx = obj.GetMg()
mx = c4d.Matrix()
mx.off = pmx.off + c4dv(position)
obj.SetMg(mx)
def scaleObj(obj,sc):
if type(sc) is float :
sc = [sc,sc,sc]
obj.SetScale(c4dv(sc))
def rotateObj(obj,rot):
#take radians, give degrees
obj[sy.ID_BASEOBJECT_ROTATION, sy.VECTOR_X]=float(rot[0])
obj[sy.ID_BASEOBJECT_ROTATION, sy.VECTOR_Y]=float(rot[1])
obj[sy.ID_BASEOBJECT_ROTATION, sy.VECTOR_Z]=float(rot[2])
def toggleDisplay(obj,display):
if display : obj.SetEditorMode(c4d.MODE_UNDEF)
else : obj.SetEditorMode(c4d.MODE_OFF)
if display : obj.SetRenderMode(c4d.MODE_UNDEF)
else : obj.SetRenderMode(c4d.MODE_OFF)
if display : obj[906]=1
else : obj[906]=0
def findatmParentHierarchie(atm,indice,hiera):
#fix the problem where mol name have an "_"
if indice == "S" : n='cpk'
else : n='balls'
mol=atm.getParentOfType(Protein)
hierarchy=parseObjectName(indice+"_"+atm.full_name())
if hiera == 'perRes' :
parent = getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
elif hiera == 'perAtom' :
if atm1.name in backbone :
parent = getObject(atm.full_name()+"_bond")
else :
parent = getObject(atm.full_name()+"_sbond")
else :
ch = atm.getParentOfType(Chain)
parent=getObject(mol.geomContainer.masterGeom.chains_obj[ch.name+"_"+n])
return parent
#####################MATERIALS FUNCTION########################
def addMaterial(name,color):
import c4d
import c4d.documents
doc = c4d.documents.GetActiveDocument()
# create standard material
__mat = doc.SearchMaterial(name)
if VERBOSE : print name,color
if __mat != None :
return __mat
else :
__mat = c4d.BaseMaterial(c4d.Mmaterial)
# set the default color
__mat[2100] = c4d.Vector(float(color[0]),float(color[1]),float(color[2]))
__mat[900] = name
# insert the material into the current document
doc.InsertMaterial(__mat)
return __mat
def assignMaterial (mat, object):
#getMatTexture
texture = object.GetTag(c4d.Ttexture)
if texture is None:
texture = object.MakeTag(c4d.Ttexture)
#check the mat?
if type(mat) is string:
mat=getCurrentScene().SearchMaterial(mat)
if mat is not None :
texture[1010] = mat
def createDejaVuColorMat():
Mat=[]
from DejaVu.colors import *
for col in cnames:
Mat.append(addMaterial(col,eval(col)))
return Mat
def retrieveColorMat(color):
doc = c4d.documents.GetActiveDocument()
from DejaVu.colors import *
for col in cnames:
if color == eval(col) :
return doc.SearchMaterial(col)
return None
def create_layers_material(name):
import c4d
import c4d.documents
# create standard material
__mat = c4d.BaseMaterial(c4d.Mmaterial)
__mat[2100] = c4d.Vector(0.,0.,0.)
__mat[900] = name
__mat[8000]= c4d.BaseList2D(LAYER)
def create_loft_material(doc=None,name='loft'):
if doc == None : doc= c4d.documents.GetActiveDocument()
#c4d.CallCommand(300000109,110)
GradMat=doc.SearchMaterial('loft')
if GradMat == None :
#c4d.documents.load_file(plugDir+'/LoftGradientMaterial1.c4d')
bd=c4d.documents.MergeDocument(doc,plugDir+'/LoftGradientMaterial1.c4d',
loadflags=c4d.SCENEFILTER_MATERIALS|c4d.SCENEFILTER_MERGESCENE)
GradMat=doc.SearchMaterial('loft')
#c4d.CallCommand(300000109,110)-> preset material n110 in the demo version
#GradMat
GradMat[2004]=0#refletion turn off
GradMat[2003]=0#refletion turn off
GradMat[8000][1001]=2001 #type 2d-V
mat=GradMat.GetClone()
mat[900]=name
#grad=mat[8000][1007]
#grad.delete_all_knots()
#mat[8000][1007]=grad
doc.InsertMaterial(mat)
#mat = create_gradiant_material(doc=doc,name=name)
return mat
def create_gradiant_material(doc=None,name='grad'):
if doc == None : doc= c4d.documents.GetActiveDocument()
mat = c4d.BaseMaterial(c4d.Mmaterial)
mat[900]=name
#grad = c4d.Gradient()
shader = c4d.BaseList2D(GRADIANT)
mat[8000]= shader
#mat[8000][1007] = grad
mat[2004]=0#refletion turn off
mat[2003]=0#refletion turn off
mat[8000][1001]=2001 #type 2d-V
doc.InsertMaterial(mat)
return mat
def create_sticks_materials(doc=None):
sticks_materials={}
if doc == None : doc= c4d.documents.GetActiveDocument()
#c4d.CallCommand(300000109,110)
# GradMat=doc.SearchMaterial('loft')#'loft'
# if GradMat == None :
# #c4d.documents.load_file(plugDir+'/LoftGradientMaterial1.c4d')
# bd=c4d.documents.MergeDocument(doc,plugDir+'/LoftGradientMaterial1.c4d',loadflags=c4d.SCENEFILTER_MATERIALS|c4d.SCENEFILTER_MERGESCENE)
# GradMat=doc.SearchMaterial('loft')
# GradMat[2004]=0#refletion turn off
# GradMat[2003]=0#refletion turn off
# GradMat[8000][1001]=2001 #type 2d-V
#GradMat = create_gradiant_material(doc=doc,name="grad")
# create standard material
i=0
j=0
atms=AtmRadi.keys()
for i in range(len(atms)):
for j in range(len(atms)):
if (atms[i][0]+atms[j][0]) not in sticks_materials.keys():
mat=doc.SearchMaterial(atms[i][0]+atms[j][0])
if mat == None :
mat=create_gradiant_material(doc=doc,name=atms[i][0]+atms[j][0])
sticks_materials[atms[i][0]+atms[j][0]]=mat
return sticks_materials
#material prset 57,70...110 is a gradient thus should be able to get it, and copy it t=c4d.CallCommand(300000109,110)
def create_SS_materials(doc=None):
import c4d
import c4d.documents
SS_materials={}
if doc == None : doc= c4d.documents.GetActiveDocument()
# create standard material
for i,ss in enumerate(SecondaryStructureType.keys()):
mat=doc.SearchMaterial(ss[0:4])
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
colorMaterial(mat,SecondaryStructureType[ss])
mat[900] = ss[0:4]#name ?
doc.InsertMaterial(mat)
SS_materials[ss[0:4]]=mat
return SS_materials
def create_DNAbase_materials(doc=None):
if doc == None : doc= c4d.documents.GetActiveDocument()
Residus_materials={}
for i,res in enumerate(DnaElements.keys()):
mat=doc.SearchMaterial(res)
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
col=(DnaElements[res])
mat[2100] = c4d.Vector(col[0],col[1],col[2])
mat[900] = res
doc.InsertMaterial(mat)
Residus_materials[res]=mat
return Residus_materials
def create_Residus_materials(doc=None):
import c4d
import c4d.documents
import random
Residus_materials={}
if doc == None : doc= c4d.documents.GetActiveDocument()
# create standard material
for i,res in enumerate(ResidueSelector.r_keyD.keys()):
random.seed(i)
mat=doc.SearchMaterial(res)
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
mat[2100] = c4d.Vector(random.random(),random.random(),random.random())
mat[900] = res
doc.InsertMaterial(mat)
Residus_materials[res]=mat
mat=doc.SearchMaterial("hetatm")
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
mat[2100] = c4d.Vector(random.random(),random.random(),random.random())
mat[900] = "hetatm"
doc.InsertMaterial(mat)
Residus_materials["hetatm"]=mat
return Residus_materials
def create_Atoms_materials(doc=None):
import c4d
import c4d.documents
Atoms_materials={}
if doc == None : doc= c4d.documents.GetActiveDocument()
for i,atms in enumerate(AtomElements.keys()):
mat=doc.SearchMaterial(atms)
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
col=(AtomElements[atms])
mat[2100] = c4d.Vector(col[0],col[1],col[2])
mat[900] = atms
doc.InsertMaterial(mat)
Atoms_materials[atms]=mat
for i,atms in enumerate(DavidGoodsell.keys()):
mat=doc.SearchMaterial(atms)
if mat == None :
mat=c4d.BaseMaterial(c4d.Mmaterial)
col=(DavidGoodsell[atms])
mat[2100] = c4d.Vector(col[0],col[1],col[2])
mat[900] = atms
doc.InsertMaterial(mat)
Atoms_materials[atms]=mat
return Atoms_materials
#Material={}
#Material["atoms"]=create_Atoms_materials()
#Material["residus"]=create_Atoms_materials()
#Material["ss"]=create_Atoms_materials()
def getMaterials():
Material={}
Material["atoms"]=create_Atoms_materials()
Material["residus"]=create_Residus_materials()
Material["ss"]=create_SS_materials()
Material["sticks"]=create_sticks_materials()
Material["dna"]=create_DNAbase_materials()
#Material["loft"]=create_loft_material()
return Material
def getMaterialListe():
Material=getMaterials()
matlist=[]
matlist.extend(Material["atoms"].keys())
matlist.extend(Material["residus"].keys())
matlist.extend(Material["ss"].keys())
matlist.extend(Material["sticks"].keys())
return matlist
def makeLabels(mol,selection,):
pass
#self.labelByProperty("1CRN:A:CYS3", textcolor='white', log=0, format=None,
# only=False, location='Center', negate=False,
#font='arial1.glf', properties=['name'])
def updateRTSpline(spline,selectedPoint,distance = 2.0,DistanceBumping = 1.85):
#from Graham code
#print "before loop"
nb_points = spline.GetPointCount()
for j in xrange(selectedPoint,nb_points-1):
leaderB = spline.GetPointAll(j)
myPos = spline.GetPointAll(j+1)
deltaB = myPos-leaderB
newPosB = leaderB + deltaB*distance/deltaB.len()
newPosA = c4d.Vector(0.,0.,0.)
k = j
while k >=0 :
leaderA = spline.GetPointAll(k)
deltaA = myPos-leaderA;
if ( deltaA.len() <= DistanceBumping and deltaA.len() >0):
newPosA = ((DistanceBumping-deltaA.len())*deltaA/deltaA.len());
newPos = newPosB + newPosA
spline.SetPoint(j+1,newPos)
k=k-1
jC = selectedPoint;
while jC >0 :
leaderBC = spline.GetPointAll(jC);
myPosC = spline.GetPointAll(jC-1);
deltaC = myPosC-leaderBC;
newPosBC = leaderBC + deltaC*distance/deltaC.len();
newPosAC = c4d.Vector(0.,0.0,0.)
k = jC
while k < nb_points :
leaderAC = spline.GetPointAll(k)
deltaAC = myPosC-leaderAC;
if ( deltaAC.len() <= DistanceBumping and deltaAC.len() >0.):
newPosAC = ((DistanceBumping-deltaAC.len())*deltaAC/deltaAC.len());
newPosC = newPosBC + newPosAC
spline.SetPoint(jC-1,newPosC)
k=k+1
jC=jC-1
def updateCoordFromObj(mv,sel,debug=True):
#get what is display
#get position object and assign coord to atoms...(c4d conformation number...or just use some constraint like avoid collision...but seems that it will be slow)
#print mv.Mols
#print mv.molDispl
for s in sel :
#print s.GetName()
if s.GetType() == c4d.Ospline :
#print "ok Spline"
select = s.GetSelectedPoints()#mode=P_BASESELECT)#GetPointAllAllelection();
#print nb_points
selected = select.get_all(s.GetPointCount()) # 0 uns | 1 selected
#print selected
#assume one point selected ?
selectedPoint = selected.index(1)
updateRTSpline(s,selectedPoint)
elif s.GetType() == c4d.Onull :
#print "ok null"
#molname or molname:chainname or molname:chain_ss ...
hi = parseName(s.GetName())
#print "parsed ",hi
molname = hi[0]
chname = hi[1]
#mg = s.GetMg()
#should work with chain level and local matrix
#mg = ml = s.get_ml()
#print molname
#print mg
#print ml
if hasattr(mv,'energy'): #ok need to compute energy
#first update obj position: need mat_transfo_inv attributes at the mollevel
#compute matrix inverse of actual position (should be the receptor...)
if hasattr(mv.energy,'amber'):
#first update obj position: need mat_transfo_inv attributes at the mollevel
mol = mv.energy.mol
if mol.name == molname :
if mv.minimize == True:
amb = mv.Amber94Config[mv.energy.name][0]
updateMolAtomCoord(mol,index=mol.cconformationIndex)
#mol.allAtoms.setConformation(mol.cconformationIndex)
#from Pmv import amberCommands
#amberCommands.Amber94Config = {}
#amberCommands.CurrentAmber94 = {}
#amb_ins = Amber94(atoms, prmfile=filename)
mv.setup_Amber94(mol.name+":",mv.energy.name,mol.prname,indice=mol.cconformationIndex)
mv.minimize_Amber94(mv.energy.name, dfpred=10.0, callback_freq='10', callback=1, drms=1e-06, maxIter=100., log=0)
#mv.md_Amber94(mv.energy.name, 349, callback=1, filename='0', log=0, callback_freq=10)
#print "time"
#import time
#time.sleep(1.)
#mol.allAtoms.setConformation(0)
#mv.minimize = False
else :
rec = mv.energy.current_scorer.mol1
lig = mv.energy.current_scorer.mol2
if rec.name == molname or lig.name == molname:
updateMolAtomCoord(rec,rec.cconformationIndex)
updateMolAtomCoord(lig,lig.cconformationIndex)
if hasattr(mv,'art'):
if not mv.art.frame_counter % mv.art.nrg_calcul_rate:
get_nrg_score(mv.energy)
else :
get_nrg_score(mv.energy)
# if debug :
# matx = matrix2c4dMat(mat)
# imatx = matrix2c4dMat(rec.mat_transfo_inv)
# sr = getObject('sphere_rec')
# sr.SetMg(matx)
# sl = getObject('sphere_lig')
# sl.SetMg(imatx)
#update atom coord for dedicated conformation (add or setConf)
#then compute some energie!
def Cylinder(name,radius=1.,length=1.,res=0, pos = [0.,0.,0.]):
QualitySph={"0":16,"1":3,"2":4,"3":8,"4":16,"5":32}
baseCyl = c4d.BaseObject(CYLINDER)
baseCyl[5000] = radius
baseCyl[5005] = length
if str(res) not in QualitySph.keys():
baseCyl[sy.PRIM_CYLINDER_SEG] = res
else :
baseCyl[sy.PRIM_CYLINDER_SEG] = QualitySph[str(res)]
#sy.PRIM_CYLINDER_HSUB
baseCyl.MakeTag(c4d.Tphong)
#addObjectToScene(getCurrentScene(),baseCyl)
return baseCyl
def Sphere(name,radius=1.0,res=0):
QualitySph={"0":6,"1":4,"2":5,"3":6,"4":8,"5":16}
baseSphere = c4d.BaseObject(c4d.Osphere)
baseSphere[PRIM_SPHERE_RAD] = radius
baseSphere[1111]=QualitySph[str(res)]
baseSphere.MakeTag(c4d.Tphong)
#addObjectToScene(getCurrentScene(),baseSphere)
return baseSphere
def updateSphereMesh(geom,quality=0,cpkRad=0.0,scale=1.,radius=0):
AtmRadi = {"A":1.7,"N":"1.54","C":"1.85","O":"1.39","S":"1.85","H":"1.2","P" : "1.7"}
if DEBUG : print geom.mesh
for name in geom.mesh.keys() :
scaleFactor=float(cpkRad)+float(AtmRadi[name])*float(scale)
if float(cpkRad) > 0. :
scaleFactor = float(cpkRad)*float(scale)
#print cpkRad,scale,scaleFactor
#print geom.mesh[name],geom.mesh[name].GetName()
mesh=geom.mesh[name].GetDown()
#print "updateSphere",mesh.GetName()
#mesh[PRIM_SPHERE_RAD]=scaleFactor
#print mesh[905]
mesh[905]=c4d.Vector(float(scaleFactor),float(scaleFactor),float(scaleFactor))
#mesh[name][905]=c4d.Vector(float(scaleFactor),float(scaleFactor),float(scaleFactor))
mesh.Message(c4d.MSG_UPDATE)
#pass
def createBaseSphere(name="BaseMesh",quality=0,cpkRad=0.,scale=1.,
radius=None,mat=None,parent=None):
QualitySph={"0":6,"1":4,"2":5,"3":6,"4":8,"5":16}
#AtmRadi = {"N":"1.54","C":"1.7","O":"1.52","S":"1.85","H":"1.2"}
AtmRadi = {"A":1.7,"N":1.54,"C":1.85,"P":1.7,"O":1.39,"S":1.85,"H":1.2}
iMe={}
baseparent=newEmpty(name)
addObjectToScene(getCurrentScene(),baseparent,parent=parent)
toggleDisplay(baseparent,False)
baseShape = newEmpty(name+"_shape")
addObjectToScene(getCurrentScene(),baseShape,parent=baseparent)
baseSphere = c4d.BaseObject(c4d.Osphere)
baseSphere[PRIM_SPHERE_RAD] = 1.
baseSphere[1111]=QualitySph[str(quality)]
baseSphere.MakeTag(c4d.Tphong)
baseSphere.SetName(name+"_sphere")
addObjectToScene(getCurrentScene(),baseSphere,parent=baseShape)
if mat == None : mat=create_Atoms_materials()
for atn in AtmRadi.keys():
#when we create we dont want to scale, just take the radius
atparent=newEmpty(name+"_"+atn)
scaleFactor=float(cpkRad)+float(AtmRadi[atn])*float(scale)
scaleFactor=rad=AtmRadi[atn]
if float(cpkRad) > 0. :
scaleFactor=cpkRad
#iMe[atn]=c4d.BaseObject(c4d.Osphere)
iMe[atn] = c4d.BaseObject(INSTANCE)
iMe[atn][1001] = baseShape
iMe[atn].SetName(atn+"_"+name)
#iMe[atn].SetRenderMode(c4d.MODE_OFF)
#quality - > resolution
#iMe[atn][1111]=QualitySph[str(quality)]
if radius == None : iMe[atn][905]=c4d.Vector(float(scaleFactor),float(scaleFactor),float(scaleFactor))#[PRIM_SPHERE_RAD] = scaleFactor#1.#float(rad)
else : iMe[atn][905]=c4d.Vector(float(scaleFactor),float(scaleFactor),float(scaleFactor))#[PRIM_SPHERE_RAD] = scaleFactor#1.#float(radius)
#iMe[atn][905]=c4d.Vector(float(scaleFactor),float(scaleFactor),float(scaleFactor))
#iMe[atn].MakeTag(c4d.Tphong)
addObjectToScene(getCurrentScene(),atparent,parent=baseparent)
addObjectToScene(getCurrentScene(),iMe[atn],parent=atparent)
iMe[atn]=atparent
#texture = iMe[atn].MakeTag(c4d.Ttexture)
#texture[1010] = mat[atn]
return iMe
def updateSphereObj(obj,coord):
updateObjectPos(obj,coord)
def updateSphereObjs(g):
if not hasattr(g,'obj') : return
newcoords=g.getVertices()
#print "upadteObjSpheres"
for i,o in enumerate(g.obj):
c=newcoords[i]
#o=getObject(nameo)
newPos=c4dv(c)#.Vector(float(c[2]),float(c[1]),float(c[0]))
parentPos = getPosUntilRoot(o)#parent.GetPos()
o.SetPos(newPos-parentPos)
def updateObjectPos(object,position):
if len(position) == 1 : c = position[0]
else : c = position
#print "upadteObj"
newPos=c4dv(c)
parentPos = getPosUntilRoot(object)#parent.GetPos()
object.SetPos(newPos-parentPos)
def clonesAtomsSphere(name,x,iMe,doc,mat=None,scale=1.0,Res=32,R=None,join=0):
spher=[]
k=0
n='S'
AtmRadi = {"A":1.7,"N":1.54,"C":1.7,"P":1.7,"O":1.52,"S":1.85,"H":1.2}
if scale == 0.0 : scale = 1.0
if mat == None : mat=create_Atoms_materials()
if name.find('balls') != (-1) : n='B'
for j in range(len(x)): spher.append(None)
for j in range(len(x)):
#at=res.atoms[j]
at=x[j]
atN=at.name
#print atN
fullname = at.full_name()
#print fullname
atC=at._coords[0]
spher[j] = iMe[atN[0]].GetClone()
spher[j].SetName(n+"_"+fullname)#.replace(":","_"))
spher[j].SetPos(c4d.Vector(float(atC[2]),float(atC[1]),float(atC[0])))
spher[j][905]=c4d.Vector(float(scale),float(scale),float(scale))
#
#print atN[0]
#print mat[atN[0]]
texture = spher[j].MakeTag(c4d.Ttexture)
texture[1010] = mat[atN[0]]
k=k+1
return spher
def instancesSphere(name,centers,radii,meshsphere,colors,scene,parent=None):
sphs=[]
mat = None
if len(colors) == 1:
mat = retrieveColorMat(colors[0])
if mat == None:
mat = addMaterial('mat_'+name,colors[0])
for i in range(len(centers)):
sphs.append(c4d.BaseObject(INSTANCE))
sphs[i][1001]=meshsphere
sphs[i].SetName(name+str(i))
sphs[i].SetPos(c4dv(centers[i]))
#sphs[i].SetPos(c4d.Vector(float(centers[i][0]),float(centers[i][1]),float(centers[i][2])))
sphs[i][905]=c4d.Vector(float(radii[i]),float(radii[i]),float(radii[i]))
texture = sphs[i].MakeTag(c4d.Ttexture)
if mat == None : mat = addMaterial("matsp"+str(i),colors[i])
texture[1010] = mat#mat[bl.retrieveColorName(sphColors[i])]
addObjectToScene(scene,sphs[i],parent=parent)
return sphs
def instancesAtomsSphere(name,x,iMe,doc,mat=None,scale=1.0,Res=32,
R=None,join=0,geom=None,dialog=None,pb=False):
#radius made via baseMesh...
#except for balls, need to scale?#by default : 0.3?
sphers=[]
k=0
n='S'
AtmRadi = {"A":1.7,"N":1.54,"C":1.7,"P":1.7,"O":1.52,"S":1.85,"H":1.2}
if R == None : R = 0.
if scale == 0.0 : scale = 1.0
if mat == None : mat=create_Atoms_materials()
if name.find('balls') != (-1) : n='B'
if geom is not None:
coords=geom.getVertices()
else :
coords=x.coords
hiera = 'default'
mol = x[0].getParentOfType(Protein)
molname = name.split("_")[0]
if VERBOSE : print "molname ", molname,mol
Spline = getObject("spline"+molname)
for c in mol.chains:
spher=[]
oneparent = True
atoms = c.residues.atoms
parent=findatmParentHierarchie(atoms[0],n,hiera)
#print "finded",parent
for j in xrange(len(atoms.coords)):
#at=res.atoms[j]
at=atoms[j]
radius = at.radius
scaleFactor=float(R)+float(radius)*float(scale)
atN=at.name
#print atN
if atN[0] not in AtmRadi.keys(): atN="A"
fullname = at.full_name()
#print fullname
atC=at.coords#at._coords[0]
spher.append( c4d.BaseObject(INSTANCE) )
spher[j][1001]=iMe[atN[0]]
#spher[j][1001]=1
spher[j].SetName(n+"_"+fullname)#.replace(":","_")
sc = iMe[atN[0]][905].x #radius of parent mesh
#if sc != scaleFactor :
if n=='B' :
scale = 1.
spher[j][905]=c4d.Vector(float((1/sc)*scale),float((1/sc)*scale),float((1/sc)*scale))
#
if atN in ["CA","N","C"] and Spline != None and n == 'S':
pos= float(((j*1.) / Spline.GetPointCount()))
path=spher[j].MakeTag(Follow_PATH)
path[1001] = Spline
path[1000] = 1
path[1003] = pos
else : spher[j].SetPos(c4dv(atC))
texture = spher[j].MakeTag(c4d.Ttexture)
texture[1010] = mat[atN[0]]
p = findatmParentHierarchie(at,n,hiera)
#print "dinded",p
if parent != p :
cp = p
oneparent = False
parent = p
else :
cp = parent
#print "parent",cp
addObjectToScene(getCurrentScene(),spher[j],parent=cp)
toggleDisplay(spher[j],False)
k=k+1
if pb :
progressBar(j/len(coords)," cpk ")
#dialog.bc[c4d.gui.BFM_STATUSBAR_PROGRESS] = j/len(coords)
#dialog.bc[c4d.gui.BFM_STATUSBAR_PROGRESSFULLSIZE] = True
#c4d.StatusSetBar(j/len(coords))
update()
sphers.extend(spher)
if pb :
resetProgressBar(0)
return sphers
def spheresMesh(name,x,mat=None,scale=1.0,Res=32,R=None,join=0):
if scale == 0.0 : scale =1.
scale = scale *2.
spher=[]
if Res == 0 : Res = 10.
else : Res = Res *5.
k=0
if mat == None : mat=create_Atoms_materials()
#print len(x)
for j in range(len(x)): spher.append(None)
for j in range(len(x)):
#at=res.atoms[j]
at=x[j]
atN=at.name
#print atN
fullname = at.full_name()
#print fullname
atC=at._coords[0]
#if R !=None : rad=R
#elif AtmRadi.has_key(atN[0]) : rad=AtmRadi[atN[0]]
#else : rad=AtmRadi['H']
#print at.vdwRadius
rad=at.vdwRadius
#print rad
spher[j] = c4d.BaseObject(c4d.Osphere)
spher[j].SetName(fullname.replace(":","_"))
spher[j][PRIM_SPHERE_RAD] = float(rad)*float(scale)
spher[j].SetPos(c4d.Vector(float(atC[0]),float(atC[1]),float(atC[2])))
spher[j].MakeTag(c4d.Tphong)
# create a texture tag on the PDBgeometry object
#texture = spher[j].MakeTag(c4d.Ttexture)
#create the dedicayed material
#print mat[atN[0]]
#texture[1010] = mat[atN[0]]
#spher.append(me)
k=k+1
return spher
def display_CPK(mol,sel,display,needRedraw=False,quality=0,cpkRad=0.0,scaleFactor=1.0,useTree="default",dialog=None):
sc = getCurrentScene()
g = mol.geomContainer.geoms['cpk']
#print g
#name=selection+"_cpk"
#select=self.select(selection,negate=False, only=True, xor=False, log=0,
# intersect=False)
#print name,select
#sel=select.findType(Atom)
if not hasattr(g,"obj"): #if no mesh have to create it for evey atms
name=mol.name+"_cpk"
#print name
mesh=createBaseSphere(name="base_cpk",quality=quality,cpkRad=cpkRad,
scale=scaleFactor,parent=mol.geomContainer.masterGeom.obj)
ob=instancesAtomsSphere(name,mol.allAtoms,mesh,sc,scale=scaleFactor,
Res=quality,join=0,dialog=dialog)
addObjToGeom([ob,mesh],g)
for i,o in enumerate(ob):
# if dialog != None :
# dialog.bc[c4d.gui.BFM_STATUSBAR_PROGRESS] = j/len(coords)
# #dialog.bc[c4d.gui.BFM_STATUSBAR_PROGRESSFULLSIZE] = True
# dialog.set(dialog._progess,float(i/len(ob)))#dialog.bc)
# getCurrentScene().Message(c4d.MULTIMSG_UP)
# c4d.draw_views(c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_ANIMATION)
parent=mol.geomContainer.masterGeom.obj
hierarchy=parseObjectName(o)
if hierarchy != "" :
if useTree == 'perRes' :
parent = getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
elif useTree == 'perAtom' :
parent = getObject(o.GetName().split("_")[1])
else :
parent = getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_cpk"])
addObjectToScene(sc,o,parent=parent)
toggleDisplay(o,False) #True per default
#elif hasattr(g,"obj") and display :
#updateSphereMesh(g,quality=quality,cpkRad=cpkRad,scale=scaleFactor)
#if needRedraw : updateSphereObj(g)
#if hasattr(g,"obj"):
else :
updateSphereMesh(g,quality=quality,cpkRad=cpkRad,scale=scaleFactor)
atoms=sel#findType(Atom) already done
for atms in atoms:
nameo = "S_"+atms.full_name()
o=getObject(nameo)#Blender.Object.Get (nameo)
if o != None :
toggleDisplay(o,display)
if needRedraw : updateObjectPos(o,atms.coords)
def getStickProperties(coord1,coord2):
x1 = float(coord1[0])
y1 = float(coord1[1])
z1 = float(coord1[2])
x2 = float(coord2[0])
y2 = float(coord2[1])
z2 = float(coord2[2])
laenge = math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2))
wsz = atan2((y1-y2), (z1-z2))
wz = acos((x1-x2)/laenge)
offset=c4d.Vector(float(z1+z2)/2,float(y1+y2)/2,float(x1+x2)/2)
v_2=c4d.Vector(float(z1-z2),float(y1-y2),float(x1-x2))
v_2.Normalize()
v_1=c4d.Vector(float(1.),float(0.),float(2.))
v_3=c4d.Vector.Cross(v_1,v_2)
v_3.Normalize()
v_1=c4d.Vector.Cross(v_2,v_3)
v_1.Normalize()
#from mglutil.math import rotax
#pmx=rotax.rotVectToVect([1.,0.,0.], [float(z1-z2),float(y1-y2),float(x1-x2)], i=None)
mx=c4d.Matrix(offset,v_1, v_2, v_3)
#mx=c4d.Matrix(c4d.Vector(float(pmx[0][0]),float(pmx[0][1]),float(pmx[0][2]),float(pmx[0][3])),
#print laenge
return laenge,mx
def instancesCylinder(name,points,faces,radii,mesh,colors,scene,parent=None):
cyls=[]
mat = None
if len(colors) == 1:
mat = retrieveColorMat(colors[0])
if mat == None:
mat = addMaterial('mat_'+name,colors[0])
for i in range(len(faces)):
laenge,mx=getStickProperties(points[faces[i][0]],points[faces[i][1]])
cyls.append(c4d.BaseObject(INSTANCE))
cyls[i][1001]=mesh
cyls[i].SetName(name+str(i))
#orient and scale
if DEBUG : print name+str(i)
cyls[i].SetMg(mx)
cyls[i][905]=c4d.Vector(float(radii[i]),float(radii[i]),float(radii[i]))
cyls[i][905,1001]=float(laenge)
texture = cyls[i].MakeTag(c4d.Ttexture)
if mat == None : mat = addMaterial("matcyl"+str(i),colors[i])
texture[1010] = mat#mat[bl.retrieveColorName(sphColors[i])]
addObjectToScene(scene,cyls[i],parent=parent)
if DEBUG : print "ok"
return cyls
def updateTubeMesh(geom,cradius=1.0,quality=0):
mesh=geom.mesh.GetDown()#should be the cylinder
#mesh[5000]=cradius
cradius = cradius*1/0.2
mesh[905]=c4d.Vector(float(cradius),1.,float(cradius))
mesh.Message(c4d.MSG_UPDATE)
#pass
def updateTubeObjs(g,bicyl=False):
#problem when ds slection....
if not hasattr(g,'obj') : return
newpoints=g.getVertices()
newfaces=g.getFaces()
#print "upadteObjSpheres"
for i,o in enumerate(g.obj):
laenge,mx=getStickProperties(newpoints[newfaces[i][0]],newpoints[newfaces[i][1]])
o.SetMl(mx)
o[905,1001]=float(laenge)
parentPos = getPosUntilRoot(o)#parent.GetPos()
currentPos = o.GetPos()
o.SetPos(currentPos - parentPos)
def updateTubeObj(atm1,atm2,bicyl=False):
c0=numpy.array(atm1.coords)
c1=numpy.array(atm2.coords)
if bicyl :
vect = c1 - c0
name1="T_"+atm1.full_name()+"_"+atm2.name
name2="T_"+atm2.full_name()+"_"+atm1.name
o=getObject(name1)
updateOneSctick(o,c0,(c0+(vect/2.)))
o=getObject(name2)
updateOneSctick(o,(c0+(vect/2.)),c1)
else :
name="T_"+atm1.name+str(atm1.number)+"_"+atm2.name+str(atm2.number)
o=getObject(name)
updateOneSctick(o,c0,c1)
def updateOneSctick(o,coord1,coord2):
laenge,mx=getStickProperties(coord1,coord2)
o.SetMl(mx)
o[905,1001]=float(laenge)
parentPos = getPosUntilRoot(o)#parent.GetPos()
currentPos = o.GetPos()
o.SetPos(currentPos - parentPos)
def changeR(txt):
rname = txt[0:3]
rnum = txt[3:]
if rname not in ResidueSetSelector.r_keyD.keys() :
rname=rname.replace(" ","")
return rname[1]+rnum
else :
r1n=ResidueSetSelector.r_keyD[rname]
return r1n+rnum
def biStick(atm1,atm2,hiera,instance):
#again name problem.....
#need to add the molecule name
mol=atm1.getParentOfType(Protein)
stick=[]
c0=numpy.array(atm1.coords)
c1=numpy.array(atm2.coords)
vect = c1 - c0
n1=atm1.full_name().split(":")
n2=atm2.full_name().split(":")
name1="T_"+mol.name+"_"+n1[1]+"_"+changeR(n1[2])+"_"+n1[3]+"_"+atm2.name
name2="T_"+mol.name+"_"+n2[1]+"_"+changeR(n2[2])+"_"+n2[3]+"_"+atm1.name
# name1="T_"+n1[1]+"_"+n1[2]+"_"+n1[3]+"_"+atm2.name
# name2="T_"+n2[1]+"_"+n2[2]+"_"+n2[3]+"_"+atm1.name
#name1="T_"+atm1.full_name()+"_"+atm2.name
#name2="T_"+atm2.full_name()+"_"+atm1.name
laenge,mx=getStickProperties(c0,(c0+(vect/2.)))
stick.append(c4d.BaseObject(INSTANCE))
stick[0][1001]=instance
stick[0].SetMg(mx)
stick[0][905,1001]=float(laenge)
stick[0].SetName(name1)
texture=stick[0].MakeTag(c4d.Ttexture)
mat=getCurrentScene().SearchMaterial(atm1.name[0])
if mat == None :
mat = addMaterial(atm1.name[0],[0.,0.,0.])
texture[1010]=mat
laenge,mx=getStickProperties((c0+(vect/2.)),c1)
stick.append(c4d.BaseObject(INSTANCE))
stick[1][1001]=instance
stick[1].SetMg(mx)
stick[1][905,1001]=float(laenge)
stick[1].SetName(name2)
texture=stick[1].MakeTag(c4d.Ttexture)
mat=getCurrentScene().SearchMaterial(atm2.name[0])
if mat == None :
mat = addMaterial(atm2.name[0],[0.,0.,0.])
texture[1010]=mat
#parent=getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_balls"])
parent = findatmParentHierarchie(atm1,'B',hiera)
addObjectToScene(getCurrentScene(),stick[0],parent=parent)
addObjectToScene(getCurrentScene(),stick[1],parent=parent)
return stick
def Tube(set,atms,points,faces,doc,mat=None,res=32,size=0.25,sc=1.,join=0,
instance=None,hiera = 'perRes',bicyl=False,pb=False):
sticks=[]
bonds, atnobnd = set.bonds
if instance == None:
mol = atms[0].top
parent=newEmpty(mol.name+"_b_sticks")
addObjectToScene(getCurrentScene(),parent,parent=mol.geomContainer.masterGeom.obj)
toggleDisplay(parent,False)
instance=newEmpty(mol.name+"_b_sticks_shape")
addObjectToScene(getCurrentScene(),instance,parent=parent)
cyl=c4d.BaseObject(CYLINDER)
cyl.SetName(mol.name+"_b_sticks_o")
cyl[5000]= 0.2 #radius
cyl[5005]= 1. #lenght
cyl[5008]= res #subdivision
cyl.MakeTag(c4d.Tphong)
addObjectToScene(getCurrentScene(),cyl,parent=instance)
for i,bond in enumerate(bonds):
if bicyl :
sticks.extend(biStick(bond.atom1,bond.atom2,hiera,instance))
else :
#have to make one cylinder / bonds
#and put the gradiant mat on it
pass
if pb :
progressBar(i/len(bonds)," sticks ")
if pb :
resetProgressBar(0)
return [sticks,instance]
def oldTube(set,atms,points,faces,doc,mat=None,res=32,size=0.25,sc=1.,join=0,instance=None,hiera = 'perRes'):
bonds, atnobnd = set.bonds
backbone = ['N', 'CA', 'C', 'O']
stick=[]
tube=[]
#size=size*2.
#coord1=x[0].atms[x[0].atms.CApos()].xyz() #x.xyz()[i].split()
#coord2=x[1].atms[x[1].atms.CApos()].xyz() #x.xyz()[i+1].split()
#print len(points)
#print len(faces)
#print len(atms)
atm1=bonds[0].atom1#[faces[0][0]]
atm2=bonds[0].atom2#[faces[0][1]]
#name="T_"+atm1.name+str(atm1.number)+"_"+atm2.name+str(atm2.number)
name="T_"+atm1.full_name()+"_"+atm2.name
mol=atm1.getParentOfType(Protein)
laenge,mx=getStickProperties(points[faces[0][0]],points[faces[0][1]])
if mat == None : mat=create_sticks_materials()
if instance == None :
stick.append(c4d.BaseObject(CYLINDER))#(res, size, laenge/sc) #1. CAtrace, 0.25 regular |sc=1 CATrace, 2 regular
stick[0].SetMg(mx)
stick[0][5005]=laenge/sc#size
stick[0][5000]=size#radius
stick[0][5008]=res#resolution
stick[0][5006]=2#heght segment
else :
stick.append(c4d.BaseObject(INSTANCE))
stick[0][1001]=instance
stick[0].SetMg(mx)
stick[0][905,1001]=float(laenge)
texture=stick[0].MakeTag(c4d.Ttexture)
#print atms[faces[0][0]].name[0]+atms[faces[0][1]].name[0]
name1=atms[faces[0][0]].name[0]
name2=atms[faces[0][1]].name[0]
if name1 not in AtmRadi.keys(): name1="A"
if name2 not in AtmRadi.keys(): name2="A"
texture[1010]=mat[name1+name2]
stick[0].SetName(name)
#stick[0].SetPos(c4d.Vector(float(z1+z2)/2,float(y1+y2)/2,float(x1+x2)/2))
#stick[0].set_rot(c4d.Vector(float(wz),float(0),float(wsz)))
#stick[0][904,1000] = wz #RY/RH
#stick[0][904,1002] = wsz #RZ/RB
stick[0].MakeTag(c4d.Tphong)
hierarchy=parseObjectName("B_"+atm1.full_name())
#parent=getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_balls"])
if hiera == 'perRes' :
parent = getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
elif hiera == 'perAtom' :
if atm1.name in backbone :
parent = getObject(atm1.full_name()+"_bond")
else :
parent = getObject(atm1.full_name()+"_sbond")
else :
parent=getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_balls"])
addObjectToScene(doc,stick[0],parent=parent)
for i in range(1,len(faces)):
atm1=bonds[i].atom1#[faces[i][0]]
atm2=bonds[i].atom2#[faces[i][1]]
#name="T_"+atm1.name+str(atm1.number)+"_"+atm2.name+str(atm2.number)
name="T_"+atm1.full_name()+"_"+atm2.name
laenge,mx=getStickProperties(points[faces[i][0]],points[faces[i][1]])
if instance == None :
stick.append(c4d.BaseObject(CYLINDER))#(res, size, laenge/sc) #1. CAtrace, 0.25 regular |sc=1 CATrace, 2 regular
stick[i].SetMl(mx)
stick[i][5005]=laenge/sc#radius
stick[i][5000]=size#height/size
stick[i][5008]=res#resolution rotation segment
stick[i][5006]=2#heght segment
else :
stick.append(c4d.BaseObject(INSTANCE))
stick[i][1001]=instance
stick[i].SetMl(mx)
stick[i][905,1001]=float(laenge)
texture=stick[i].MakeTag(c4d.Ttexture)
#print i,i+1
name1=atms[faces[i][0]].name[0]
name2=atms[faces[i][1]].name[0]
if name1 not in AtmRadi.keys(): name1="A"
if name2 not in AtmRadi.keys(): name2="A"
if i < len(atms) :
#print name1+name2
texture[1010]=mat[name1+name2]
else :
texture[1010]=mat[name1+name2]
stick[i].SetName(name)
#stick[i].SetPos(c4d.Vector(float(z1+z2)/2,float(y1+y2)/2,float(x1+x2)/2))
#stick[i].set_rot(c4d.Vector(float(wz),float(0.),float(wsz)))
stick[i].SetMl(mx)
stick[i].MakeTag(c4d.Tphong)
hierarchy=parseObjectName("B_"+atm1.full_name())
#parent=getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_balls"])
if hiera == 'perRes' :
parent = getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
elif hiera == 'perAtom' :
if atm1.name in backbone :
parent = getObject(atm1.full_name()+"_bond")
else :
parent = getObject(atm1.full_name()+"_sbond")
else :
parent=getObject(mol.geomContainer.masterGeom.chains_obj[hierarchy[1]+"_balls"])
addObjectToScene(doc,stick[i],parent=parent)
#if join==1 :
# stick[0].join(stick[1:])
# for ind in range(1,len(stick)):
#obj[0].join([obj[ind]])
# scn.unlink(stick[ind])
#obj[0].setName(name)
return [stick]
def c4dv(points):
return c4d.Vector(float(points[2]),float(points[1]),float(points[0]))
#return c4d.Vector(float(points[0]),float(points[1]),float(points[2]))
def vc4d(v):
return [v.z,v.y,v.x]
def getCoordinateMatrix(pos,direction):
offset=pos
v_2=direction
v_2.Normalize()
v_1=c4d.Vector(float(1.),float(0.),float(0.))
v_3=c4d.Vector.Cross(v_1,v_2)
v_3.Normalize()
v_1=c4d.Vector.Cross(v_2,v_3)
v_1.Normalize()
#from mglutil.math import rotax
#pmx=rotax.rotVectToVect([1.,0.,0.], [float(z1-z2),float(y1-y2),float(x1-x2)], i=None)
return c4d.Matrix(offset,v_1, v_2, v_3)
def getCoordinateMatrixBis(pos,v1,v2):
offset=c4dv(pos)
v_2=c4dv(v2)
v_1=c4dv(v1)
v_3=c4d.Vector.Cross(v_1,v_2)
v_3.Normalize()
#from mglutil.math import rotax
#pmx=rotax.rotVectToVect([1.,0.,0.], [float(z1-z2),float(y1-y2),float(x1-x2)], i=None)
return c4d.Matrix(offset,v_1, v_2, v_3)
def loftnurbs(name,mat=None):
loft=c4d.BaseObject(LOFTNURBS)
loft[1008]=0 #adaptive UV false
loft.SetName(name)
loft.MakeTag(c4d.Tphong)
texture = loft.MakeTag(c4d.Ttexture)
texture[1004]=6 #UVW Mapping
#create the dedicayed material
if mat == None :
texture[1010] = create_loft_material(name='mat_'+name)
else : texture[1010] = mat
return loft
def sweepnurbs(name,mat=None):
loft=c4d.BaseObject(SWEEPNURBS)
loft.SetName(name)
loft.MakeTag(c4d.Tphong)
texture = loft.MakeTag(c4d.Ttexture)
#create the dedicayed material
if mat == None :
texture[1010] = create_loft_material(name='mat_'+name)
else : texture[1010] = mat
return loft
def addShapeToNurb(loft,shape,position=-1):
list_shape=loft.GetChilds()
shape.insert_after(list_shape[position])
#def createShapes2D()
# sh=c4d.BaseObject(dshape)
def spline(name, points,close=0,type=1,scene=None,parent=None):
spline=c4d.BaseObject(c4d.Ospline)
spline[1000]=type
spline[1002]=close
spline.SetName(name)
spline.ResizeObject(int(len(points)))
for i,p in enumerate(points):
spline.SetPoint(i, c4dv(p))
if scene != None :
addObjectToScene(scene,spline,parent=parent)
return spline,None
def update_spline(name,new_points):
spline=getCurrentScene().SearchObject(name)
if spline is None : return False
spline.ResizeObject(int(len(new_points)))
for i,p in enumerate(new_points):
spline.SetPoint(i, c4dv(p))
return True
def createShapes2Dspline(doc=None,parent=None):
circle=c4d.BaseObject(CIRCLE)
circle[2012]=float(0.3)
circle[2300]=1
if doc : addObjectToScene(doc,circle,parent=parent )
rectangle=c4d.BaseObject(RECTANGLE)
rectangle[2060]=float(2.2)
rectangle[2061]=float(0.7)
rectangle[2300]=1
if doc : addObjectToScene(doc,rectangle,parent=parent )
fourside=c4d.BaseObject(FOURSIDE)
fourside[2121]=float(2.5)
fourside[2122]=float(0.9)
fourside[2300]=1
if doc : addObjectToScene(doc,fourside,parent=parent )
shape2D={}
pts=[[0,0,0],[0,1,0],[0,1,1],[0,0,1]]
#helixshape
helixshape=fourside.get_real_spline()#spline('helix',pts,close=1,type=2)#AKIMA
helixshape.SetName('helix')
shape2D['Heli']=helixshape
#sheetshape
sheetshape=rectangle.get_real_spline()#spline('sheet',pts,close=1,type=0)#LINEAR
sheetshape.SetName('sheet')
shape2D['Shee']=sheetshape
#strandshape
strandshape=sheetshape.GetClone()
strandshape.SetName('strand')
shape2D['Stra']=strandshape
#coilshape
coilshape=circle.get_real_spline()#spline('coil',pts,close=1,type=4)#BEZIER
coilshape.SetName('coil')
shape2D['Coil']=coilshape
#turnshape
turnshape=coilshape.GetClone()
turnshape.SetName('turn')
shape2D['Turn']=turnshape
if doc :
for o in shape2D.values() :
addObjectToScene(doc,o,parent=parent )
return shape2D,[circle,rectangle,fourside,helixshape,sheetshape,strandshape,coilshape,turnshape]
def Circle(name, rad=1.):
circle=c4d.BaseObject(CIRCLE)
circle.SetName(name)
circle[2012]=float(rad)
circle[2300]=0
return circle
def createShapes2D(doc=None,parent=None):
if doc is None :
doc = getCurrentScene()
shape2D={}
circle=c4d.BaseObject(CIRCLE)
circle[2012]=float(0.3)
circle[2300]=0
circle.SetName('Circle1')
circle2=circle.GetClone()
circle2.SetName('Circle2')
coil=c4d.BaseObject(c4d.Onull)
coil.SetName('coil')
turn=c4d.BaseObject(c4d.Onull)
turn.SetName('turn')
shape2D['Coil']=coil
shape2D['Turn']=turn
addObjectToScene(doc,coil,parent=parent )
addObjectToScene(doc,circle,parent=coil )
addObjectToScene(doc,turn,parent=parent )
addObjectToScene(doc,circle2,parent=turn )
rectangle=c4d.BaseObject(RECTANGLE)
rectangle[2060]=float(2.2)
rectangle[2061]=float(0.7)
rectangle[2300]=0
rectangle.SetName('Rectangle1')
rectangle2=rectangle.GetClone()
rectangle2.SetName('Rectangle2')
stra=c4d.BaseObject(c4d.Onull)
stra.SetName('stra')
shee=c4d.BaseObject(c4d.Onull)
shee.SetName('shee')
shape2D['Stra']=stra
shape2D['Shee']=shee
addObjectToScene(doc,stra,parent=parent )
addObjectToScene(doc,rectangle,parent=stra )
addObjectToScene(doc,shee,parent=parent )
addObjectToScene(doc,rectangle2,parent=shee )
fourside=c4d.BaseObject(FOURSIDE)
fourside[2121]=float(2.5)
fourside[2122]=float(0.9)
fourside[2300]=0
heli=c4d.BaseObject(c4d.Onull)
heli.SetName('heli')
shape2D['Heli']=heli
addObjectToScene(doc,heli,parent=parent )
addObjectToScene(doc,fourside,parent=heli)
return shape2D,[circle,rectangle,fourside]
def getShapes2D():
shape2D={}
shape2D['Coil']=getObject('coil')
shape2D['Turn']=getObject('turn')
shape2D['Heli']=getObject('heli')
shape2D['Stra']=getObject('stra')
return shape2D
def morph2dObject(name,objsrc,target):
obj=objsrc.GetClone()
obj.SetName(name)
mixer=obj.MakeTag(POSEMIXER)
mixer[1001]=objsrc #the default pose
#for i,sh in enumerate(shape2D) :
# mixer[3002,1000+int(i)]=shape2D[sh]
mixer[3002,1000]=target#shape2D[sh] target 1
return obj
def c4dSpecialRibon(name,points,dshape=CIRCLE,shape2dlist=None,mat=None):
#if loft == None : loft=loftnurbs('loft',mat=mat)
shape=[]
pos=c4d.Vector(float(points[0][2]),float(points[0][1]),float(points[0][0]))
direction=c4d.Vector(float(points[0][2]-points[1][2]),float(points[0][1]-points[1][1]),float(points[0][0]-points[1][0]))
mx=getCoordinateMatrix(pos,direction)
if shape2dlist : shape.append(morph2dObject(dshape+str(0),shape2dlist[dshape],shape2dlist['Heli']))
else :
shape.append(c4d.BaseObject(dshape))
if dshape == CIRCLE :
shape[0][2012]=float(0.3)
#shape[0][2300]=1
if dshape == RECTANGLE :
shape[0][2060]=float(0.3*4.)
shape[0][2061]=float(0.3*3.)
#shape[0][2300]=1
if dshape == FOURSIDE:
shape[0][2121]=float(0.3*4.)
shape[0][2122]=float(0.1)
#shape[0][2300]=0
shape[0].SetMg(mx)
if len(points)==2: return shape
i=1
while i < (len(points)-1):
#print i
pos=c4d.Vector(float(points[i][2]),float(points[i][1]),float(points[i][0]))
direction=c4d.Vector(float(points[i-1][2]-points[i+1][2]),float(points[i-1][1]-points[i+1][1]),float(points[i-1][0]-points[i+1][0]))
mx=getCoordinateMatrix(pos,direction)
if shape2dlist : shape.append(morph2dObject(dshape+str(i),shape2dlist[dshape],shape2dlist['Heli']))
else :
shape.append(c4d.BaseObject(dshape))
if dshape == CIRCLE :
shape[i][2012]=float(0.3)
shape[i][2300]=2
if dshape == RECTANGLE :
shape[i][2060]=float(0.3*4.)
shape[i][2061]=float(0.3*3.)
shape[i][2300]=2
if dshape == FOURSIDE:
shape[i][2121]=float(0.3*4.)
shape[i][2122]=float(0.1)
shape[i][2300]=2
shape[i].SetMg(mx)
i=i+1
pos=c4d.Vector(float(points[i][2]),float(points[i][1]),float(points[i][0]))
direction=c4d.Vector(float(points[i-1][2]-points[i][2]),float(points[i-1][1]-points[i][1]),float(points[i-1][0]-points[i][0]))
mx=getCoordinateMatrix(pos,direction)
if shape2dlist : shape.append(morph2dObject(dshape+str(i),shape2dlist[dshape],shape2dlist['Heli']))
else :
shape.append(c4d.BaseObject(dshape))
if dshape == CIRCLE :
shape[i][2012]=float(0.3)
shape[i][2300]=2
if dshape == RECTANGLE :
shape[i][2060]=float(0.3*4.)
shape[i][2061]=float(0.3*3.)
shape[i][2300]=2
if dshape == FOURSIDE:
shape[i][2121]=float(0.3*4.)
shape[i][2122]=float(0.1)
shape[i][2300]=2
shape[i].SetMg(mx)
return shape
def c4dSecondaryLofts(name,matrices,dshape=CIRCLE,mat=None):
#if loft == None : loft=loftnurbs('loft',mat=mat)
shape=[]
i=0
while i < (len(matrices)):
#pos=c4d.Vector(float(points[i][2]),float(points[i][1]),float(points[i][0]))
#direction=c4d.Vector(float(points[i-1][2]-points[i+1][2]),float(points[i-1][1]-points[i+1][1]),float(points[i-1][0]-points[i+1][0]))
mx=getCoordinateMatrixBis(matrices[i][2],matrices[i][0],matrices[i][1])
#mx=getCoordinateMatrix(pos,direction)
shape.append(c4d.BaseObject(dshape))
shape[i].SetMg(mx)
if dshape == CIRCLE :
shape[i][2012]=float(0.3)
shape[i][2300]=0
if dshape == RECTANGLE :
shape[i][2060]=float(2.2)
shape[i][2061]=float(0.7)
shape[i][2300]=0
if dshape == FOURSIDE:
shape[i][2121]=float(2.5)
shape[i][2122]=float(0.9)
shape[i][2300]=0
i=i+1
return shape
def instanceShape(ssname,shape2D):
#if shape2D=None : shape2D=createShapes2D()
shape=c4d.BaseObject(INSTANCE)
shape[1001]=shape2D[ssname[:4]]
shape.SetName(ssname[:4])
return shape
def makeShape(dshape,ssname):
shape=c4d.BaseObject(dshape)
if dshape == CIRCLE :
shape[2012]=float(0.3)
shape[2300]=0
shape.SetName(ssname[:4])
if dshape == RECTANGLE :
shape[2060]=float(2.2)
shape[2061]=float(0.7)
shape[2300]=0
shape.SetName(ssname[:4])
if dshape == FOURSIDE:
shape[2121]=float(2.5)
shape[2122]=float(0.9)
shape[2300]=0
shape.SetName(ssname[:4])
return shape
def c4dSecondaryLoftsSp(name,atoms,dshape=CIRCLE,mat=None,shape2dmorph=None,shapes2d=None,instance=False):
#print "ok build loft shape"
#if loft == None : loft=loftnurbs('loft',mat=mat)
shape=[]
prev=None
ssSet=atoms[0].parent.parent.secondarystructureset
molname=atoms[0].full_name().split(":")[0]
chname= atoms[0].full_name().split(":")[1]
i=0
iK=0
#get The pmv-extruder
sheet=atoms[0].parent.secondarystructure.sheet2D
matrices=sheet.matrixTransfo
if mat == None : mat = c4d.documents.GetActiveDocument().SearchMaterial('mat_loft'+molname+'_'+chname)
while i < (len(atoms)):
ssname=atoms[i].parent.secondarystructure.name
dshape=SSShapes[ssname[:4]]#ssname[:4]
#print ssname,dshape
#pos=c4d.Vector(float(points[i][2]),float(points[i][1]),float(points[i][0]))
#direction=c4d.Vector(float(points[i-1][2]-points[i+1][2]),float(points[i-1][1]-points[i+1][1]),float(points[i-1][0]-points[i+1][0]))
mx=getCoordinateMatrixBis(matrices[i][2],matrices[i][0],matrices[i][1])
#mx=getCoordinateMatrix(pos,direction)
#iK=iK+1
if shape2dmorph :
shape.append(morph2dObject(dshape+str(i),shape2dmorph[dshape],shape2dmorph['Heli']))
shape[-1].SetMg(mx)
else :
#print str(prev),ssname
if prev != None: #end of loop
if ssname[:4] != prev[:4]:
if not instance : shape.append(makeShape(SSShapes[prev[:4]],prev))
else : shape.append(instanceShape(prev,shapes2d))
shape[-1].SetMg(mx)
if not instance : shape.append(makeShape(dshape,ssname))
else : shape.append(instanceShape(ssname,shapes2d))
shape[-1].SetMg(mx)
prev=ssname
i=i+1
if mat != None:
prev=None
#i=(len(shape))
i=0
while i < (len(shape)):
ssname=shape[i].GetName()
#print ssname
pos=1-((((i)*100.)/len(shape))/100.0)
if pos < 0 : pos = 0.
#print pos
#change the material knote according ss color / cf atom color...
#col=atoms[i].colors['secondarystructure']
col=c4dColor(SSColor[ssname])
nc=c4d.Vector(col[0],col[1],col[2])
ncp=c4d.Vector(0,0,0)
if prev != None :
pcol=c4dColor(SSColor[prev])
ncp=c4d.Vector(pcol[0],pcol[1],pcol[2])
#print col
#print ssname[:4]
#print prev
if ssname != prev : #new ss
grad=mat[8000][1007]
#iK=iK+1
nK=grad.GetKnotCount()
#print "knot count ",nK,iK
if iK >= nK :
#print "insert ",pos,nK
#print "grad.insert_knot(c4d.Vector("+str(col[0])+str(col[1])+str(col[2])+"), 1.0, "+str(pos)+",0.5)"
if prev != None :
grad.InsertKnot(ncp, 1.0, pos+0.01,0.5)
iK=iK+1
grad.InsertKnot(nc, 1.0, pos-0.01,0.5)
#grad.insert_knot(ncp, 1.0, pos+0.1,0.5)
iK=iK+1
else :
#print "set ",iK,pos
if prev != None :grad.SetKnot(iK-1,ncp,1.0,pos,0.5)
grad.SetKnot(iK,nc,1.0,pos,0.5)
mat[8000][1007]=grad
prev=ssname
mat.Message(c4d.MSG_UPDATE)
i=i+1
#mx=getCoordinateMatrixBis(matrices[i][2],matrices[i][0],matrices[i][1])
#if shape2dlist : shape.append(morph2dObject(dshape+str(i),shape2dlist[shape],shape2dlist['Heli']))
return shape
def LoftOnSpline(name,chain,atoms,Spline=None,dshape=CIRCLE,mat=None,
shape2dmorph=None,shapes2d=None,instance=False):
#print "ok build loft/spline"
molname = atoms[0].full_name().split(":")[0]
chname = atoms[0].full_name().split(":")[1]
#we first need the spline
#if loft == None : loft=loftnurbs('loft',mat=mat)
shape=[]
prev=None
#mol = atoms[0].top
ssSet=chain.secondarystructureset#atoms[0].parent.parent.secondarystructureset
i=0
iK=0
#get The pmv-extruder
sheet=chain.residues[0].secondarystructure.sheet2D
matrices=sheet.matrixTransfo
ca=atoms.get('CA')
o =atoms.get('O')
if Spline is None :
parent=atoms[0].parent.parent.parent.geomContainer.masterGeom.chains_obj[chname]
Spline,ospline = spline(name+'spline',ca.coords)#
addObjectToScene(getCurrentScene(),Spline,parent=parent)
#loftname = 'loft'+mol.name+'_'+ch.name
#matloftname = 'mat_loft'+mol.name+'_'+ch.name
if mat == None :
mat = c4d.documents.GetActiveDocument().SearchMaterial('mat_loft'+molname+'_'+chname)
if mat is not None :
if DEBUG : print "ok find mat"
#if mat == None :
# mat = create_loft_material(name='mat_loft'+molname+'_'+chname)
if DEBUG : print "CA",len(ca)
while i < (len(ca)):
pos= float(((i*1.) / len(ca)))
#print str(pos)+" %"
#print atoms[i],atoms[i].parent,hasattr(atoms[i].parent,'secondarystructure')
if hasattr(ca[i].parent,'secondarystructure') : ssname=ca[i].parent.secondarystructure.name
else : ssname="Coil"
dshape=SSShapes[ssname[:4]]#ssname[:4]
#mx =getCoordinateMatrixBis(matrices[i][2],matrices[i][0],matrices[i][1])
#have to place the shape on the spline
if shape2dmorph :
shape.append(morph2dObject(dshape+str(i),shape2dmorph[dshape],shape2dmorph['Heli']))
path=shape[i].MakeTag(Follow_PATH)
path[1001] = Spline
path[1000] = 0#tangantial
path[1003] = pos
path[1007] = 2#1 axe
#shape[-1].SetMg(mx)
else :
#print str(prev),ssname
#if prev != None: #end of loop
# if ssname[:4] != prev[:4]: #newSS need transition
# if not instance : shape.append(makeShape(SSShapes[prev[:4]],prev))
# else : shape.append(instanceShape(prev,shapes2d))
# #shape[-1].SetMg(mx)
# path=shape[-1].MakeTag(Follow_PATH)
# path[1001] = Spline
# path[1000] = 1
# path[1003] = pos
if not instance : shape.append(makeShape(dshape,ssname))
else : shape.append(instanceShape(ssname,shapes2d))
path=shape[i].MakeTag(Follow_PATH)
path[1001] = Spline
path[1000] = 0
path[1003] = pos
path[1007] = 2#1
#shape[-1].SetMg(mx)
if i >=1 :
laenge,mx=getStickProperties(ca[i].coords,ca[i-1].coords)
#if i > len(o) : laenge,mx=getStickProperties(ca[i].coords,o[i-1].coords)
#else :laenge,mx=getStickProperties(ca[i].coords,o[i].coords)
shape[i].SetMg(mx)
prev=ssname
i=i+1
laenge,mx=getStickProperties(ca[0].coords,ca[1].coords)
#laenge,mx=getStickProperties(ca[0].coords,o[0].coords)
shape[0].SetMg(mx)
if False :#(mat != None):
prev=None
#i=(len(shape))
i=0
while i < (len(shape)):
ssname=shape[i].GetName()
#print ssname
pos=1-((((i)*100.)/len(shape))/100.0)
if pos < 0 : pos = 0.
#print pos
#change the material knote according ss color / cf atom color...
#col=atoms[i].colors['secondarystructure']
col=c4dColor(SSColor[ssname])
nc=c4d.Vector(col[0],col[1],col[2])
ncp=c4d.Vector(0,0,0)
if prev != None :
pcol=c4dColor(SSColor[prev])
ncp=c4d.Vector(pcol[0],pcol[1],pcol[2])
#print col
#print ssname[:4]
#print prev
if ssname != prev : #new ss
grad=mat[8000][1007]
#iK=iK+1
nK=grad.GetKnotCount()
#print "knot count ",nK,iK
if iK >= nK :
#print "insert ",pos,nK
#print "grad.insert_knot(c4d.Vector("+str(col[0])+str(col[1])+str(col[2])+"), 1.0, "+str(pos)+",0.5)"
if prev != None :
grad.InsertKnot(ncp, 1.0, pos+0.01,0.5)
iK=iK+1
grad.InsertKnot(nc, 1.0, pos-0.01,0.5)
#grad.insert_knot(ncp, 1.0, pos+0.1,0.5)
iK=iK+1
else :
#print "set ",iK,pos
if prev != None :grad.SetKnot(iK-1,ncp,1.0,pos,0.5)
grad.SetKnot(iK,nc,1.0,pos,0.5)
mat[8000][1007]=grad
prev=ssname
mat.Message(c4d.MSG_UPDATE)
i=i+1
#mx=getCoordinateMatrixBis(matrices[i][2],matrices[i][0],matrices[i][1])
#if shape2dlist : shape.append(morph2dObject(dshape+str(i),shape2dlist[shape],shape2dlist['Heli']))
return shape
def update_2dsheet(shapes,builder,loft):
dicSS={'C':'Coil','T' : 'Turn', 'H':'Heli','E':'Stra','P':'Coil'}
shape2D=getShapes2D()
for i,ss in enumerate(builder):
if shapes[i].GetName() != dicSS[ss]:
shapes[i][1001]=shape2D[dicSS[ss]]#ref object
shapes[i].SetName(dicSS[ss])
texture = loft.GetTags()[0]
mat=texture[1010]
grad=mat[8000][1007]
grad.delete_all_knots()
mat[8000][1007]=grad
prev=None
i = 0
iK = 0
while i < (len(shapes)):
ssname=shapes[i].GetName()
#print ssname
pos=1-((((i)*100.)/len(shapes))/100.0)
if pos < 0 : pos = 0.
#print pos
#change the material knote according ss color / cf atom color...
#col=atoms[i].colors['secondarystructure']
col=c4dColor(SSColor[ssname])
nc=c4d.Vector(col[0],col[1],col[2])
ncp=c4d.Vector(0,0,0)
if prev != None :
pcol=c4dColor(SSColor[prev])
ncp=c4d.Vector(pcol[0],pcol[1],pcol[2])
#print col
#print ssname[:4]
#print prev
if ssname != prev : #new ss
grad=mat[8000][1007]
#iK=iK+1
nK=grad.get_knot_count()
#print "knot count ",nK,iK
if iK >= nK :
#print "insert ",pos,nK
#print "grad.insert_knot(c4d.Vector("+str(col[0])+str(col[1])+str(col[2])+"), 1.0, "+str(pos)+",0.5)"
if prev != None :
grad.insert_knot(ncp, 1.0, pos+0.01,0.5)
iK=iK+1
grad.insert_knot(nc, 1.0, pos-0.01,0.5)
#grad.insert_knot(ncp, 1.0, pos+0.1,0.5)
iK=iK+1
else :
#print "set ",iK,pos
if prev != None :grad.set_knot(iK-1,ncp,1.0,pos,0.5)
grad.set_knot(iK,nc,1.0,pos,0.5)
mat[8000][1007]=grad
prev=ssname
mat.Message(c4d.MSG_UPDATE)
i=i+1
def piecewiseLinearInterpOnIsovalue(x):
"""Piecewise linear interpretation on isovalue that is a function
blobbyness.
"""
import sys
X = [-3.0, -2.5, -2.0, -1.5, -1.3, -1.1, -0.9, -0.7, -0.5, -0.3, -0.1]
Y = [0.6565, 0.8000, 1.0018, 1.3345, 1.5703, 1.8554, 2.2705, 2.9382, 4.1485, 7.1852, 26.5335]
if x<X[0] or x>X[-1]:
print "WARNING: Fast approximation :blobbyness is out of range [-3.0, -0.1]"
return None
i = 0
while x > X[i]:
i +=1
x1 = X[i-1]
x2 = X[i]
dx = x2-x1
y1 = Y[i-1]
y2 = Y[i]
dy = y2-y1
return y1 + ((x-x1)/dx)*dy
def coarseMolSurface(mv,molFrag,XYZd,isovalue=7.0,resolution=-0.3,padding=0.0,name='CoarseMolSurface'):
"""
will create a DejaVu indexedPolygon of a coarse molecular surface, the function is build as the implemented node
in vision.
geom<- coarseMolSurface()
mv : the molecular viewer embeded
molFrag : the molkit node used to build the surface
XYZd : the dimension of the grid (X,Y,Z)
etc...
"""
from MolKit.molecule import Atom
atoms = molFrag.findType(Atom)
coords = atoms.coords
radii = atoms.vdwRadius
from UTpackages.UTblur import blur
import numpy.oldnumeric as Numeric
volarr, origin, span = blur.generateBlurmap(coords, radii, XYZd,resolution, padding = padding)
volarr.shape = (XYZd[0],XYZd[1],XYZd[2])
volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f')
#print volarr
weights = Numeric.ones(len(radii), typecode = "f")
h = {}
from Volume.Grid3D import Grid3DF
maskGrid = Grid3DF( volarr, origin, span , h)
h['amin'], h['amax'],h['amean'],h['arms']= maskGrid.stats()
#(self, grid3D, isovalue=None, calculatesignatures=None, verbosity=None)
from UTpackages.UTisocontour import isocontour
isocontour.setVerboseLevel(0)
data = maskGrid.data
origin = Numeric.array(maskGrid.origin).astype('f')
stepsize = Numeric.array(maskGrid.stepSize).astype('f')
# add 1 dimension for time steps amd 1 for multiple variables
if data.dtype.char!=Numeric.Float32:
#print 'converting from ', data.dtype.char
data = data.astype('f')#Numeric.Float32)
newgrid3D = Numeric.ascontiguousarray(Numeric.reshape( Numeric.transpose(data),(1, 1)+tuple(data.shape) ), data.dtype.char)
ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize)
isoc = isocontour.getContour3d(ndata, 0, 0, isovalue,isocontour.NO_COLOR_VARIABLE)
vert = Numeric.zeros((isoc.nvert,3)).astype('f')
norm = Numeric.zeros((isoc.nvert,3)).astype('f')
col = Numeric.zeros((isoc.nvert)).astype('f')
tri = Numeric.zeros((isoc.ntri,3)).astype('i')
isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)
#print "###VERT###"
#print vert
#print "###norm###"
#print norm
#print "###tri###"
#print tri
if maskGrid.crystal:
vert = maskGrid.crystal.toCartesian(vert)
from DejaVu.IndexedGeom import IndexedGeom
from DejaVu.IndexedPolygons import IndexedPolygons
g=IndexedPolygons(name=name)
inheritMaterial = None
g.Set(vertices=vert, faces=tri, materials=None,
tagModified=False,
vnormals=norm, inheritMaterial=inheritMaterial )
#g.fullName = name
#print "bind"
mv.bindGeomToMolecularFragment(g, atoms, log=0)
#print len(g.getVertices())
#print g
return g
#GeometryNode.textureManagement(self, image=image, textureCoordinates=textureCoordinates)
def makeLines(name,points,faces,parent=None):
rootLine = newEmpty(name)
addObjectToScene(getCurrentScene(),rootLine,parent=parent)
spline=c4d.BaseObject(c4d.Ospline)
#spline[1000]=type
#spline[1002]=close
spline.SetName(name+'mainchain')
spline.ResizeObject(int(len(points)))
cd4vertices = map(c4dv,points)
map(polygon.SetPoint,range(len(points)),cd4vertices)
#for i,p in enumerate(points):
# spline.SetPoint(i, c4dv(p))
addObjectToScene(getCurrentScene(),spline,parent=rootLine)
spline=c4d.BaseObject(c4d.Ospline)
#spline[1000]=type
#spline[1002]=close
spline.SetName(name+'sidechain')
spline.ResizeObject(int(len(points)))
for i,p in enumerate(points):
spline.SetPoint(i, c4dv(p))
addObjectToScene(getCurrentScene(),spline,parent=rootLine)
def updateLines(lines, chains=None):
#lines = getObject(name)
#if lines == None or chains == None:
#print lines,chains
parent = getObject(chains.full_name())
#print parent
bonds, atnobnd = chains.residues.atoms.bonds
indices = map(lambda x: (x.atom1._bndIndex_,
x.atom2._bndIndex_), bonds)
updatePoly(lines,vertices=chains.residues.atoms.coords,faces=indices)
def getCoordByAtomType(chain):
dic={}
#extract the different atomset by type
for i,atms in enumerate(AtomElements.keys()):
atomset = chain.residues.atoms.get(atms)
bonds, atnobnd = atomset.bonds
indices = map(lambda x: (x.atom1._bndIndex_,
x.atom2._bndIndex_), bonds)
dic[atms] = [atomset]
def stickballASmesh(molecules,atomSets):
bsms=[]
for mol, atms, in map(None, molecules, atomSets):
for ch in mol.chains:
parent = getObject(ch.full_name())
lines = getObject(ch.full_name()+'_bsm')
if lines == None :
lines=newEmpty(ch.full_name()+'_bsm')
addObjectToScene(getCurrentScene(),lines,parent=parent)
dic = getCoordByAtomType(ch)
for type in dic.keys():
bsm = createsNmesh(ch.full_name()+'_bsm'+type,dic[type][0],
None,dic[type][1])
bsms.append(bsm)
addObjectToScene(getCurrentScene(),bsm,parent=lines)
def editLines(molecules,atomSets):
for mol, atms, in map(None, molecules, atomSets):
#check if line exist
for ch in mol.chains:
parent = getObject(ch.full_name())
lines = getObject(ch.full_name()+'_line')
if lines == None :
bonds, atnobnd = ch.residues.atoms.bonds
indices = map(lambda x: (x.atom1._bndIndex_,
x.atom2._bndIndex_), bonds)
lines = createsNmesh(ch.full_name()+'_line',ch.residues.atoms.coords,
None,indices)
addObjectToScene(getCurrentScene(),lines[0] ,parent=parent)
mol.geomContainer.geoms[ch.full_name()+'_line'] = lines
else : #need to update
updateLines(lines, chains=ch)
def PointCloudObject(name,**kw):
#need to add the AtomArray modifier....
pointWidth = 0.1
if kw.has_key("pointWidth"):
pointWidth = float(kw["pointWidth"])
parent = c4d.BaseObject(ATOMARRAY)
parent.SetName(name+"ds")
parent[1000] = 0. #radius cylinder
parent[1001] = pointWidth #radius sphere
parent[1002] = 3 #subdivision
addObjectToScene(getCurrentScene(),parent,parent=kw["parent"])
if kw.has_key("materials"):
texture = parent.MakeTag(c4d.Ttexture)
texture[1010] = addMaterial("mat"+name,kw["materials"][0])
coords=kw['vertices']
nface = 0
if kw.has_key("faces"):
nface = len(kw['faces'])
visible = 1
if kw.has_key("visible"):
visible = kw['visible']
obj= c4d.PolygonObject(len(coords), nface)
obj.SetName(name)
cd4vertices = map(c4dv,coords)
map(obj.SetPoint,range(len(coords)),cd4vertices)
#for k,v in enumerate(coords) :
# obj.SetPoint(k, c4dv(v))
addObjectToScene(getCurrentScene(),obj,parent=parent)
toggleDisplay(parent,bool(visible))
return obj
def PolygonColorsObject(name,vertColors):
obj= c4d.PolygonObject(len(vertColors), len(vertColors)/2.)
obj.SetName(name+'_color')
cd4vertices = map(c4dv,vertColors)
map(obj.SetPoint,range(len(vertColors)),cd4vertices)
#for k,v in enumerate(vertColors) :
# obj.SetPoint(k, c4dv(v))
return obj
def updatePoly(polygon,faces=None,vertices=None):
if type(polygon) == str:
polygon = getObject(polygon)
if polygon == None : return
if vertices != None:
for k,v in enumerate(vertices) :
polygon.SetPoint(k, c4dv(v))
if faces != None:
for g in range(len(faces)):
A = int(faces[g][0])
B = int(faces[g][1])
if len(faces[g])==2 :
C = B
D = B
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C ))
elif len(faces[g])==3 :
C = int(faces[g][2])
D = C
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C ))
elif len(faces[g])==4 :
C = int(faces[g][2])
D = int(faces[g][3])
#print A
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C, D ))
polygon.Message(c4d.MSG_UPDATE)
def redoPoly(poly,vertices,faces,proxyCol=False,colors=None,parent=None,mol=None):
doc = getCurrentScene()
doc.SetActiveObject(poly)
name=poly.GetName()
texture = poly.GetTags()[0]
c4d.CallCommand(100004787) #delete the obj
obj=createsNmesh(name,vertices,None,faces,smooth=False,material=texture[1010],proxyCol=proxyCol)
addObjectToScene(doc,obj[0],parent=parent)
if proxyCol and colors!=None:
pObject=getObject(name+"_color")
doc.SetActiveObject(pObject)
c4d.CallCommand(100004787) #delete the obj
pObject=PolygonColorsObject(name,colors)
addObjectToScene(doc,pObject,parent=parent)
def reCreatePoly(poly,vertices,faces,proxyCol=False,colors=None,parent=None,mol=None):
doc = getCurrentScene()
doc.SetActiveObject(poly)
name=poly.GetName()
texture = poly.GetTags()[0]
c4d.CallCommand(100004787) #delete the obj
obj=createsNmesh(name,vertices,None,faces,smooth=False,material=texture[1010],proxyCol=proxyCol)
addObjectToScene(doc,obj[0],parent=parent)
if proxyCol and colors!=None:
pObject=getObject(name+"_color")
doc.SetActiveObject(pObject)
c4d.CallCommand(100004787) #delete the obj
pObject=PolygonColorsObject(name,colors)
addObjectToScene(doc,pObject,parent=parent)
"""def UVWColorTag(obj,vertColors):
uvw=obj.MakeTag(c4d.Tuvw)
obj= c4d.PolygonObject(len(vertColors), len(vertColors)/2.)
obj.SetName(name+'_color')
k=0
for v in vertColors :
print v
obj.SetPoint(k, c4d.Vector(float(v[0]), float(v[1]), float(v[2])))
k=k+1
return obj
"""
def updateMesh(g,proxyCol=False,parent=None,mol=None):
obj=g.obj
oldN=obj.GetPointCount()
vertices=g.getVertices()
faces=g.getFaces()
newN=len(vertices)
#if newN != oldN :
obj.ResizeObject(newN,len(faces))
updatePoly(obj,faces=faces,vertices=vertices)
if DEBUG : print "resize",len(vertices),len(faces)
sys.stderr.write('\nnb v %d f %d\n' % (len(vertices),len(faces)))
# k=0
# for v in vertices :
# #print v
# obj.SetPoint(k, c4d.Vector(float(v[2]), float(v[1]), float(v[0])))
# k=k+1
# for g in range(len(faces)):
# A = int(faces[g][0])
# B = int(faces[g][1])
# C = int(faces[g][2])
# if len(faces[g])==3 :
# D = C
# polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C))
# elif len(faces[g])==4 :
# D = int(faces[g][3])
# #print A
# obj.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C, D ))
#obj.Message(c4d.MSG_UPDATE)
def updateMeshProxy(g,proxyCol=False,parent=None,mol=None):
doc = getCurrentScene()
doc.SetActiveObject(g.obj)
name=g.obj.GetName()
texture = g.obj.GetTags()[0]
c4d.CallCommand(100004787) #delete the obj
vertices=g.getVertices()
faces=g.getFaces()
if DEBUG : print len(vertices),len(faces)
sys.stderr.write('\nnb v %d f %d\n' % (len(vertices),len(faces)))
#if proxyCol : o=PolygonColorsObject
obj=createsNmesh(name,vertices,None,faces,smooth=False,material=texture[1010],proxyCol=proxyCol)
addObjectToScene(doc,obj[0],parent=parent)
#obj.Message(c4d.MSG_UPDATE)
g.obj=obj[0]
# if proxyCol :
# colors=mol.geomContainer.getGeomColor(g.name)
# if hasattr(g,'color_obj'):
# pObject=g.color_obj#getObject(name+"_color")
# doc.SetActiveObject(pObject)
# c4d.CallCommand(100004787) #delete the obj
# pObject=PolygonColorsObject(name,colors)
# g.color_obj=pObject
# addObjectToScene(doc,pObject,parent=parent)
def c4df(face,g,polygon):
A = int(face[0])
B = int(face[1])
if len(face)==2 :
C = B
D = B
poly=c4d.CPolygon(A, B, C)
elif len(face)==3 :
C = int(face[2])
D = C
poly=c4d.CPolygon(A, B, C)
elif len(face)==4 :
C = int(face[2])
D = int(face[3])
poly=c4d.CPolygon(A, B, C, D)
polygon.SetPolygon(id=g, polygon=poly)
return [A,B,C,D]
def polygons(name,proxyCol=False,smooth=False,color=None, material=None, **kw):
import time
t1 = time.time()
vertices = kw["vertices"]
faces = kw["faces"]
normals = kw["normals"]
frontPolyMode='fill'
if kw.has_key("frontPolyMode"):
frontPolyMode = kw["frontPolyMode"]
if kw.has_key("shading") :
shading=kw["shading"]#'flat'
if frontPolyMode == "line" : #wire mode
material = getCurrentScene().SearchMaterial("wire")
if material == None:
material = addMaterial("wire",(0.5,0.5,0.5))
polygon = c4d.PolygonObject(len(vertices), len(faces))
polygon.SetName(name)
k=0
#map function is faster than the usual for loop
#what about the lambda?
cd4vertices = map(c4dv,vertices)
map(polygon.SetPoint,range(len(vertices)),cd4vertices)
#for v in vertices :
#print v
# polygon.SetPoint(k, c4dv(v))
#polygon.SetPoint(k, c4d.Vector(float(v[0]), float(v[1]), float(v[2])))
# k=k+1
#c4dfaces = map(c4df,faces,range(len(faces)),[polygon]*len(faces))
#map(polygon.SetPolygon,range(len(faces)),c4dfaces)
for g in range(len(faces)):
A = int(faces[g][0])
B = int(faces[g][1])
if len(faces[g])==2 :
C = B
D = B
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C))
elif len(faces[g])==3 :
C = int(faces[g][2])
D = C
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C))
elif len(faces[g])==4 :
C = int(faces[g][2])
D = int(faces[g][3])
#print A
polygon.SetPolygon(id=g, polygon=c4d.CPolygon( A, B, C, D ))
t2=time.time()
#print "time to create Mesh", (t2 - t1)
#sys.stderr.write('\ntime to create Mesh %f\n' % (t2-t1))
polygon.MakeTag(c4d.Tphong) #shading ?
# create a texture tag on the PDBgeometry object
if not proxyCol :
texture = polygon.MakeTag(c4d.Ttexture)
#create the dedicayed material
if material == None :
if name[:4] in SSShapes.keys() : texture[1010] = getCurrentScene().SearchMaterial(name[:4])
else : texture[1010] = addMaterial(name,color[0])
else : texture[1010] = material
polygon.Message(c4d.MSG_UPDATE)
return polygon
def createsNmesh(name,vertices,vnormals,faces,smooth=False,material=None,proxyCol=False,color=[[1,0,0],]):
PDBgeometry = polygons(name, vertices=vertices,normals=vnormals,faces=faces,material=material,color=color,smooth=smooth,proxyCol=proxyCol)
return [PDBgeometry]
def instancePolygon(name, matrices=None, mesh=None,parent=None):
if matrices == None : return None
if mesh == None : return None
instance = []
#print len(matrices)#4,4 mats
for i,mat in enumerate(matrices):
instance.append(c4d.BaseObject(INSTANCE))
instance[-1][1001]=mesh
instance[-1].SetName(name+str(i))
mx = matrix2c4dMat(mat)
instance[-1].SetMg(mx)
AddObject(instance[-1],parent=parent)
#instance[-1].MakeTag(c4d.Ttexture)
return instance
def colorMaterial(mat,col):
#mat input is a material name or a material object
#color input is three rgb value array
doc= c4d.documents.GetActiveDocument()
if type(mat)==str: mat = doc.SearchMaterial(mat)
mat[2100] = c4d.Vector(col[0],col[1],col[2])
def changeMaterialSchemColor(typeMat):
if typeMat == "ByAtom":
for atms in AtomElements.keys() : colorMaterial(atms,AtomElements[atms])
elif typeMat == "AtomsU" :
for atms in DavidGoodsell.keys() :colorMaterial(atms,DavidGoodsell[atms])
#if (atms == "P") or (atms == "A") or (atms == "CA"): colorMaterial(atms[0],AtomElements[atms])
#else :
#colorMaterial(atms,DavidGoodsell[atms])
elif typeMat == "ByResi":
for res in RasmolAmino.keys(): colorMaterial(res,RasmolAmino[res])
elif typeMat == "Residu":
for res in Shapely.keys(): colorMaterial(res,Shapely[res])
elif typeMat == "BySeco":
for ss in SecondaryStructureType.keys(): colorMaterial(ss[0:4],SecondaryStructureType[ss])
else : pass
def splitName(name):
if name[0] == "T" : #sticks name.. which is "T_"+chname+"_"+Resname+"_"+atomname+"_"+atm2.name\n'
#name1="T_"+mol.name+"_"+n1[1]+"_"+n1[2]+"_"+n1[3]+"_"+atm2.name
tmp=name.split("_")
return ["T",tmp[1],tmp[2],tmp[3][0:1],tmp[3][1:],tmp[4]]
else :
tmp=name.split(":")
indice=tmp[0].split("_")[0]
molname=tmp[0].split("_")[1]
chainname=tmp[1]
residuename=tmp[2][0:3]
residuenumber=tmp[2][3:]
atomname=tmp[3]
return [indice,molname,chainname,residuename,residuenumber,atomname]
def checkChangeMaterial(o,typeMat,atom=None,parent=None,color=None):
#print typeMat
#print "checkChangeMaterial"
doc= c4d.documents.GetActiveDocument()
Material=getMaterials()
matliste=getMaterialListe()
ss="Helix"
ssk=['Heli', 'Shee', 'Coil', 'Turn', 'Stra']
mol = None
ch = None
if atom != None :
res=atom.getParentOfType(Residue)
ch = atom.getParentOfType(Chain)
mol = atom.getParentOfType(Protein)
if hasattr(res,"secondarystructure") : ss=res.secondarystructure.name
#mats=o.getMaterials()
names=splitName(o.GetName())
#print names
texture = o.GetTags()[0]
#print texture
matname=texture[1010][900]
#print matname
changeMaterialSchemColor(typeMat)
if typeMat == "" or typeMat == "ByProp" : #color by color
if parent != None : requiredMatname = 'mat'+parent#.GetName() #exemple mat_molname_cpk
else : requiredMatname = 'mat'+o.GetName()#exemple mat_coil1a_molname
if typeMat == "ByProp": requiredMatname = 'mat'+o.GetName()#exemple mat_coil1a_molname
#print parent.name,o.name,requiredMatname
if matname != requiredMatname :
#print requiredMatname
rMat=doc.SearchMaterial(requiredMatname)
if rMat is None : rMat=addMaterial(requiredMatname,color)
else : colorMaterial(rMat,color)
texture[1010] = rMat#doc.SearchMaterial(requiredMatname)
else : colorMaterial(requiredMatname,color)
elif typeMat == "ByAtom" :
if matname not in AtmRadi.keys() : #switch to atom materials
texture[1010]=Material["atoms"][names[5][0]]
if typeMat == "AtomsU" :
#if matname not in AtmRadi.keys() : #switch to atom materials
texture[1010]=Material["atoms"][lookupDGFunc(atom)]
elif typeMat == "ByResi" or typeMat == "Residu":
if ch.ribbonType() == "NA":
if matname not in DnaElements.keys():
texture[1010]=Material["dna"]["D"+res.type]
elif matname not in ResidueSelector.r_keyD.keys() : #switch to residues materials
rname = res.type
if rname not in ResidueSelector.r_keyD.keys():
rname='hetatm'
texture[1010]=Material["residus"][rname]
elif typeMat == "BySeco" :
if matname not in ssk : #switch to ss materials
texture[1010]=Material["ss"][ss[0:4]]
elif typeMat == "ByChai" : #swith chain material
if matname is not ch.material.GetName() :
texture[1010]=ch.material
def checkChangeStickMaterial(o,typeMat,atoms,parent=None,color=None):
#print typeMat
#print "checkChangeMaterial"
doc=getCurrentScene()
Material=getMaterials()
ss="Helix"
ssk=['Heli', 'Shee', 'Coil', 'Turn', 'Stra']
res=atoms[0].getParentOfType(Residue)
ch=atoms[0].getParentOfType(Chain)
mol=atoms[0].getParentOfType(Protein)
if hasattr(res,"secondarystructure") : ss=res.secondarystructure.name
names=["T",mol.name,ch.name,res.name[0:3],res.name[:3],atoms[0].name[0]]
texture = o.GetTags()[1]
#print texture
matname=texture[1010][900]
#print matname
if typeMat == "" or typeMat == "ByProp": #color by color
if parent != None : requiredMatname = 'mat'+parent#.GetName() #exemple mat_molname_cpk
else : requiredMatname = 'mat'+o.GetName()#exemple mat_coil1a_molname
if typeMat == "ByProp": requiredMatname = 'mat'+o.GetName()#exemple mat_coil1a_molname
#print parent.name,o.name,requiredMatname
if matname != requiredMatname :
#print requiredMatname
rMat=doc.SearchMaterial(requiredMatname)
if rMat is None : rMat=addMaterial(requiredMatname,color)
else : colorMaterial(rMat,color)
texture[1010] = rMat#doc.SearchMaterial(requiredMatname)
else : colorMaterial(requiredMatname,color)
if typeMat == "ByAtom" or typeMat == "AtomsU" :
if matname not in Material["sticks"].keys() : #switch to atom materials
texture[1010]=Material["sticks"][atoms[0].name[0]+atoms[1].name[0]]
elif typeMat == "ByResi" :
if matname not in ResidueSelector.r_keyD.keys() : #switch to residues materials
#print matname, names[3],Material["residus"]
texture[1010]=Material["residus"][names[3]]
elif typeMat == "BySeco" :
if matname not in ssk : #switch to ss materials
texture[1010]=Material["ss"][ss[0:4]]
def blenderColor(col):
#blender color rgb range[0-1]
if max(col)<=1.0: col = map( lambda x: x*255, col)
return col
def c4dColor(col):
#c4d color rgb range[0-1]
if max(col)>1.0: col = map( lambda x: x/255., col)
return col
def changeColor(geom,colors,perVertex=False,proxyObject=None,doc=None,pb=False):
if DEBUG : print 'changeColor',len(colors)
if doc == None : doc = getCurrentScene()
if hasattr(geom,'obj'):obj=geom.obj
else : obj=geom
#verfify perVertex flag
unic=False
ncolor=c4dColor(colors[0])
if len(colors)==1 :
unic=True
if DEBUG : print "unic ",unic
ncolor = c4dColor(colors[0])
if proxyObject :
name = geom.obj.GetName()
proxy = getObject(name+"_color")
if hasattr(geom,'color_obj') :
proxy = getObject(geom.color_obj)
if proxy != None :
#print proxy,proxy.GetName()
#sys.stderr.write("%s",proxy.GetName())
if proxy.GetPointCount() != len(colors) and not unic:
doc.SetActiveObject(proxy)
c4d.CallCommand(100004787) #delete the obj
proxy = PolygonColorsObject(name,colors)
else :
proxy = PolygonColorsObject(name,colors)
if DEBUG : print proxy,proxy.GetName()
geom.color_obj = proxy
addObjectToScene(doc,proxy,parent=geom.mol.geomContainer.masterGeom.obj)
#print "not unic"
if len(colors) != obj.GetPointCount() and len(colors) == obj.GetPolygonCount(): perVertex=False
if len(colors) == obj.GetPointCount() and len(colors) != obj.GetPolygonCount(): perVertex=True
i=0
for g in (obj.GetAllPolygons()):#faces
if not unic and not perVertex : ncolor = c4dColor(colors[i])
else : ncolor = c4dColor(colors[0])
for j in [g.a,g.b,g.c,g.d]:#vertices
if not unic and perVertex : ncolor = c4dColor(colors[j])
if DEBUG :print ncolor
proxy.SetPoint(j, c4d.Vector(float(ncolor[0]), float(ncolor[1]), float(ncolor[2])))
#now how update the material tag of the object using C++ plugin??
proxy.Message(c4d.MSG_UPDATE)
#need to update but how: maybe number of selected object: if one create eerything/if two just update the values! in the doit function !
doc.SetActiveObject(obj)
#doc.set_active_object(proxyObject,c4d.SELECTION_ADD)
c4d.CallCommand(1023892)
else :
#print obj.get_tags()
#print ncolor
texture = obj.GetTags()[0] #should be the textureFlag
if DEBUG : print texture #only apply unic color
texture[1010][2100] = c4d.Vector((ncolor[0]),(ncolor[1]),(ncolor[2]))
def changeSticksColor(geom,colors,type=None,indice=0,perVertex=False,proxyObject=None,doc=None):
#need 2color per stick, will try material per selection.
#defeine sel1/sel2 of each tube, and call material from listMAterial
#print 'changeSticksColor',(colors)
#verfify perVertex flag
if hasattr(geom,'obj'):obj=geom.obj[indice]
else : obj=geom
#print colors
unic=False
#ncolor=colors[0]
if len(colors)==1 :
unic=True
#print unic
ncolor = c4dColor(colors[0])
texture = obj.GetTags()[1] #should be the textureFlag
#print texture[1010],texture[1010][900]
if texture[1010][8000] is None or texture[1010][900] in ResidueSelector.r_keyD.keys() or texture[1010][900].find("selection") != -1 or texture[1010][900] in SSShapes.keys() :
ncolor= c4dColor(colors[0])
texture[1010][2100] = c4d.Vector((ncolor[0]),(ncolor[1]),(ncolor[2]))
else :
grad=texture[1010][8000][1007]# = c4d.Vector((ncolor[0]),(ncolor[1]),(ncolor[2]))
ncolor = c4dColor(colors[0])
#print ncolor,obj.GetName()
grad.SetKnot(0,c4d.Vector((ncolor[0]),(ncolor[1]),(ncolor[2])),1.0,0.5,0.5)
ncolor = c4dColor(colors[1])
#print ncolor
grad.SetKnot(1,c4d.Vector((ncolor[0]),(ncolor[1]),(ncolor[2])),1.0,0.5,0.5) #col,bright,pos,bias
texture[1010][8000][1007]=grad
def changeObjColorMat(obj,color):
doc = getCurrentScene()
texture = obj.GetTags()[0]
matname=texture[1010][900]
rMat=doc.SearchMaterial(matname)
colorMaterial(rMat,color)
texture[1010] = rMat#doc.SearchMaterial(requiredMatname)
def armature(basename, x,scn=None,root=None):
bones=[]
mol = x[0].top
center = mol.getCenter()
if scn != None:
parent = c4d.BaseObject(c4d.Onull)
parent.SetName(basename)
addObjectToScene(scn,parent,parent=root)
for j in range(len(x)):
at=x[j]
atN=at.name
fullname = at.full_name()
atC=at._coords[0]
rad=at.vdwRadius
bones.append(c4d.BaseObject(BONE))
bones[j].SetName(fullname.replace(":","_"))
relativePos=Numeric.array(atC)
if j>0 :
patC=Numeric.array((x[j-1]._coords[0]))
for i in range(3):relativePos[i]=(atC[i]-patC[i])
else : #the first atom
#relative should be against the master
center=Numeric.array(center)
for i in range(3):relativePos[i]=(atC[i]-center[i])
bones[j].SetPos(c4dv(relativePos))
mx = c4d.Matrix()
mx.off = c4dv(atC)
bones[j].SetMg(mx)
if scn != None :
if j==0 : addObjectToScene(scn,bones[j],parent=parent)
else : addObjectToScene(scn,bones[j],parent=bones[j-1])
return parent
def metaballs(name,atoms,scn=None,root=None):
if scn == None:
scn = getCurrentScene()
parent = c4d.BaseObject(c4d.Onull)
parent.SetName(name)
addObjectToScene(scn,parent,parent=root)
mol = atoms[0].top
#copy of the cpk ?-> point cloud is nice too...
#create the metaball objects child of the null
meta=c4d.BaseObject(METABALLS)
addObjectToScene(scn,meta,parent=parent)
#change the metaball parameter
meta[1000]=9.0#Hull Value
meta[1001]=0.5#editor subdivision
meta[1002]=0.5#render subdivision
#coloring ?
return meta,parent
def box(name,center=[0.,0.,0.],size=[1.,1.,1.],cornerPoints=None,visible=1):
#import numpy
box=c4d.BaseObject(c4d.Ocube)#Object.New('Mesh',name)
box.SetName(name)
if cornerPoints != None :
for i in range(3):
size[i] = cornerPoints[1][i]-cornerPoints[0][i]
center=(numpy.array(cornerPoints[0])+numpy.array(cornerPoints[1]))/2.
box.SetPos(c4dv(center))
box[1100] = c4dv(size)
#aMat=addMaterial("wire")
texture = box.MakeTag(c4d.Ttexture)
mat = getCurrentScene().SearchMaterial("wire")
if mat == None:
texture[1010] = addMaterial("wire",(0.5,0.5,0.5))
texture[1010][2003] = 1 #transparancy
texture[1010][2401] = 0.80 #value
else :
texture[1010] = mat
return box
def getCornerPointCube(obj):
size = obj[1100]
center = obj.GetPos()
cornerPoints=[]
#lowCorner
lc = [center.x - size.x/2.,
center.y - size.y/2.,
center.z - size.z/2.]
uc = [center.x + size.x/2.,
center.y + size.y/2.,
center.z + size.z/2.]
cornerPoints=[[lc[2],lc[1],lc[0]],[uc[2],uc[1],uc[0]]]
return cornerPoints
def getFace(c4dface):
if c4dface.c == c4dface.d:
return [c4dface.a,c4dface.b,c4dface.c]
else :
return [c4dface.a,c4dface.b,c4dface.c,c4dface.d]
# faces = obj.GetAllPolygons()
# c4dvertices = obj.GetPointAll()
# vertices = map(vc4d,c4dvertices)
# c4dvnormals = obj.CreatePhongNormals()
# vnormals=vertices
# for i,f in enumerate(faces):
# #one face : 4 vertices
# for j in range(len(f)):
# vnormals[f[j]] = vc4d(c4dvnormals[(i*4)+j])
# return vnormals
def triangulate(poly):
#select poly
doc = getCurrentScene()
doc.SetActiveObject(poly)
c4d.CallCommand(14048)#triangulate
def makeEditable(object,copy=True):
doc = getCurrentScene()
#make a copy?
if copy:
clone = object.GetClone()
clone.SetName("clone")
doc.InsertObject(clone)
doc.SetActiveObject(clone)
c4d.CallCommand(12236)#make editable
clone.Message(c4d.MSG_UPDATE)
return clone
else :
doc.SetActiveObject(object)
c4d.CallCommand(12236)
return object
def DecomposeMesh(poly,edit=True,copy=True,tri=True,transform=True):
#make it editable
if edit :
poly = makeEditable(poly,copy=copy)
#triangulate
if tri:
triangulate(poly)
#get infos
c4dfaces = poly.GetAllPolygons()
faces = map(getFace,c4dfaces)
c4dvertices = poly.GetAllPoints()
vertices = map(vc4d,c4dvertices)
c4dvnormals = poly.CreatePhongNormals()
vnormals=vertices[:]
for i,f in enumerate(faces):
#one face : 4 vertices
for k,j in enumerate(f):
#print i,j,(i*4)+k
vnormals[j] = vc4d(c4dvnormals[(i*4)+k])
#remove the copy if its exist? or keep it ?
#need to apply the transformation
if transform :
from Pmv.hostappInterface import comput_util as C
c4dmat = poly.GetMg()
mat,imat = c4dMat2numpy(c4dmat)
vertices = C.ApplyMatrix(vertices,mat)
if edit and copy :
getCurrentScene().SetActiveObject(poly)
c4d.CallCommand(100004787) #delete the obj
return faces,vertices,vnormals
#################################################################################
def setupAmber(mv,name,mol,prmtopfile, type,add_Conf=True,debug = False):
if not hasattr(mv,'setup_Amber94'):
mv.browseCommands('amberCommands', package='Pmv')
from Pmv import amberCommands
amberCommands.Amber94Config = {}
amberCommands.CurrentAmber94 = {}
from Pmv.hostappInterface import comput_util as C
mv.energy = C.EnergyHandler(mv)
mv.energy.amber = True
mv.energy.mol = mol
mol.prname = prmtopfile
mv.energy.name=name
def doit():
c1 = mv.minimize_Amber94
c1(name, dfpred=10.0, callback_freq='10', callback=1, drms=1e-06, maxIter=10, log=0)
mv.energy.doit=doit
if add_Conf:
confNum = 1
# check number of conformations available
current_confNum = len(mol.allAtoms[0]._coords) -1
if current_confNum < confNum:
# we need to add conformation
for i in range((confNum - current_confNum)):
mol.allAtoms.addConformation(mol.allAtoms.coords)
# uses the conformation to store the transformed data
#mol.allAtoms.updateCoords(vt,ind=confNum)
# add arconformationIndex to top instance ( molecule)
mol.cconformationIndex = confNum
mv.setup_Amber94(mol.name+":",name,prmtopfile,indice=mol.cconformationIndex)
mv.minimize_Amber94(name, dfpred=10.0, callback_freq='10', callback=1, drms=1e-06, maxIter=100., log=0)
def cAD3Energies(mv,mols,atomset1,atomset2,add_Conf=False,debug = False):
from Pmv.hostappInterface import comput_util as C
mv.energy = C.EnergyHandler(mv)
mv.energy.add(atomset1,atomset2)#type=c_ad3Score by default
#mv.energy.add(atomset1,atomset2,type = "ad4Score")
if add_Conf:
confNum = 1
for mol in mols:
# check number of conformations available
current_confNum = len(mol.allAtoms[0]._coords) -1
#if current_confNum < confNum:
# we need to add conformation
#for i in range((confNum - current_confNum)):
mol.allAtoms.addConformation(mol.allAtoms.coords)
# uses the conformation to store the transformed data
#mol.allAtoms.updateCoords(vt,ind=confNum)
# add arconformationIndex to top instance ( molecule)
mol.cconformationIndex = len(mol.allAtoms[0]._coords) -1
if debug :
s1=c4d.BaseObject(c4d.Osphere)
s1.SetName("sphere_rec")
s1[PRIM_SPHERE_RAD]=2.
s2=c4d.BaseObject(c4d.Osphere)
s2.SetName("sphere_lig")
s2[PRIM_SPHERE_RAD]=2.
addObjectToScene(getCurrentScene(),s1)
addObjectToScene(getCurrentScene(),s2)
#label
label = newEmpty("label")
label.MakeTag(LOOKATCAM)
addObjectToScene(getCurrentScene(),label)
text1 = c4d.BaseObject(TEXT)
text1.SetName("score")
text1[2111] = "score : 0.00"
text1[2115] = 5.
text1[904,1000] = 3.14
text1[903,1001] = 4.
text2 = c4d.BaseObject(TEXT)
text2.SetName("el")
text2[2111] = "el : 0.00"
text2[2115] = 5.0
text2[904,1000] = 3.14
text3 = c4d.BaseObject(TEXT)
text3.SetName("hb")
text3[2111] = "hb : 0.00"
text3[2115] = 5.0
text3[904,1000] = 3.14
text3[903,1001] = -4.
text4 = c4d.BaseObject(TEXT)
text4.SetName("vw")
text4[2111] = "vw : 0.00"
text4[2115] = 5.0
text4[904,1000] = 3.14
text4[903,1001] = -8.
text5 = c4d.BaseObject(TEXT)
text5.SetName("so")
text5[2111] = "so : 0.00"
text5[2115] = 5.0
text5[904,1000] = 3.14
text5[903,1001] = -12.
addObjectToScene(getCurrentScene(),text1,parent=label)
addObjectToScene(getCurrentScene(),text2,parent=label)
addObjectToScene(getCurrentScene(),text3,parent=label)
addObjectToScene(getCurrentScene(),text4,parent=label)
addObjectToScene(getCurrentScene(),text5,parent=label)
#return energy
def get_nrg_score(energy,display=True):
#print "get_nrg_score"
status = energy.compute_energies()
#print status
if status is None: return
#print energy.current_scorer
#print energy.current_scorer.score
vf = energy.viewer
text = getObject("score")
if text != None :
text[2111] = "score :"+str(energy.current_scorer.score)[0:5]
for i,term in enumerate(['el','hb','vw','so']):
labelT = getObject(term)
labelT[2111] = term+" : "+str(energy.current_scorer.scores[i])[0:5]
#should make multi label for multi terms
# change color of ligand with using scorer energy
if display:
# change selection level to Atom
prev_select_level = vf.getSelLev()
vf.setSelectionLevel(Atom,log=0)
#
scorer = energy.current_scorer
atomSet = vf.expandNodes(scorer.mol2.name).findType(Atom) # we pick the ligand
property = scorer.prop
if hasattr(atomSet,scorer.prop):
mini = min(getattr(atomSet,scorer.prop))
#geomsToColor = vf.getAvailableGeoms(scorer.mol2)
vf.colorByProperty(atomSet,['cpk'],property,
mini=-1.0, maxi=1.0,
colormap='rgb256',log=1)
# get the geometries of colormap to be display
#if vf.colorMaps.has_key('rgb256'):
#cmg = vf.colorMaps['rgb256']
#from DejaVu.ColormapGui import ColorMapGUI
#if not isinstance(cmg,ColorMapGUI):
# cmg.read(self.colormap_file)
# self.vf.showCMGUI(cmap=cmg, topCommand=0)
# cmg = self.vf.colorMaps['rgb256']
# cmg.master.withdraw()
# create the color map legend
# cmg.createCML()
#cml = cmg.legend
#cml.Set(visible=True,unitsString='kcal/mol')
#if cml not in self.geom_without_pattern:
# self.geom_without_pattern.append(cml)
#################################################################################
def c4dMat2numpy(c4dmat,center=None):
"""a c4d matrice is
v1 X-Axis
v2 Y-Axis
v3 Z-Axis
off Position
a numpy matrice is a regular 4x4 matrice (3x3rot+trans)
"""
import numpy
import c4d
#print "ok convertMAtrix"
from numpy import matrix
from Pmv.hostappInterface import comput_util as C
#m = numpy.identity(4).astype('f')
#M=matrix(m)
euler = c4d.utils.MatrixToHPB(c4dmat) #heading,att,bank need to inverse y/z left/righ hand problem
#print "euler",euler
matr = numpy.array(C.eulerToMatrix([euler.x,euler.z,euler.y]))
#M[0:3,0:3]=matr
trans = c4dmat.off
#matr[3]= [trans.x,trans.z,trans.y,1.]
matr[:3,3] = vc4d(trans)
if center != None :
matr[3][0] = matr[3][0] - center[0]
matr[3][1] = matr[3][1] - center[1]
matr[3][2] = matr[3][2] - center[2]
M = matrix(matr)
#print M
IM = M.I
return numpy.array(M),numpy.array(IM)
def matrix2c4dMat(mat,transpose = True):
#Scale Problem, but shouldnt as I decompose???
import c4d
from Pmv.hostappInterface import comput_util as C
#why do I transpose ?? => fortran matrix ..
if transpose :
mat = Numeric.array(mat).transpose().reshape(16,)
else :
mat = Numeric.array(mat).reshape(16,)
r,t,s = C.Decompose4x4(mat)
#Order of euler angles: heading first, then attitude/pan, then bank
axis = C.ApplyMatrix(Numeric.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]]),r.reshape(4,4))
#r = numpy.identity(4).astype('f')
#M = matrix(matr)
#euler = C.matrixToEuler(mat[0:3,0:3])
#mx=c4d.tools.hpb_to_matrix(c4d.Vector(euler[0],euler[1]+(3.14/2),euler[2]), c4d.tools.ROT_HPB)
v_1 = c4dv(r.reshape(4,4)[2,:3])
v_2 = c4dv(r.reshape(4,4)[1,:3])
v_3 = c4dv(r.reshape(4,4)[0,:3])
offset = c4dv(t)
mx = c4d.Matrix(offset,v_1, v_2, v_3)
#mx.off = offset
return mx
def updateLigCoord(mol):
from Pmv.hostappInterface import comput_util as C
#fake update...reset coord to origin
mol.allAtoms.setConformation(0)
#get the transformation
name = mol.geomContainer.masterGeom.chains_obj[mol.chains[0].name]
mx = getObject(name).get_ml()
mat,imat = c4dMat2numpy(mx)
vt = C.transformedCoordinatesWithMatrice(mol,mat)
mol.allAtoms.updateCoords(vt,ind=mol.cconformationIndex)
#coords = mol.allAtoms.coords
#mol.allAtoms.updateCoords(coords,ind=mol.cconformationIndex)
mol.allAtoms.setConformation(0)
def updateMolAtomCoord(mol,index=-1):
#just need that cpk or the balls have been computed once..
#balls and cpk should be linked to have always same position
# let balls be dependant on cpk => contraints? or update
# the idea : spline/dynamic move link to cpl whihc control balls
# this should be the actual coordinate of the ligand
# what about the rc...
vt = []
sph = mol.geomContainer.geoms['cpk'].obj
for name in sph:
o = getObject(name)
pos=o.GetMg().off
vt.append([pos.x,pos.z,pos.y])
if index == -1 : index = 0
mol.allAtoms.updateCoords(vt,ind=index)
##############################AR METHODS#######################################
def ARstep(mv):
#from Pmv.hostappInterface import comput_util as C
mv.art.beforeRedraw()
#up(self,dialog)
for arcontext in mv.art.arcontext :
for pat in arcontext.patterns.values():
if pat.isdetected:
#print pat
geoms_2_display = pat.geoms
transfo_mat = pat.mat_transfo[:]
#print transfo_mat[12:15]
for geom in geoms_2_display :
if hasattr(pat,'offset') : offset = pat.offset[:]
else : offset =[0.,0.,0.]
transfo_mat[12] = (transfo_mat[12]+offset[0])* mv.art.scaleDevice
transfo_mat[13] = (transfo_mat[13]+offset[1])* mv.art.scaleDevice
transfo_mat[14] = (transfo_mat[14]+offset[2])* mv.art.scaleDevice
mat = transfo_mat.reshape(4,4)
model = geom.obj
#print obj.GetName()
#r,t,s = C.Decompose4x4(Numeric.array(mat).reshape(16,))
#print t
#newPos = c4dv(t)
#model.SetPos(newPos)
#model.Message(c4d.MSG_UPDATE)
setObjectMatrix(model,mat)
#updateAppli()
def ARstepM(mv):
#from Pmv.hostappInterface import comput_util as C
from mglutil.math import rotax
mv.art.beforeRedraw()
#up(self,dialog)
for arcontext in mv.art.arcontext :
for pat in arcontext.patterns.values():
if pat.isdetected:
#print pat
geoms_2_display = pat.geoms
#m = pat.mat_transfo[:]#pat.moveMat[:]
if mv.art.concat :
m = pat.moveMat[:].reshape(16,)
else :
m = pat.mat_transfo[:].reshape(16,)
#print transfo_mat[12:15]
for geom in geoms_2_display :
model = geom.obj
if mv.art.patternMgr.mirror:
#apply scale transformation GL.glScalef(-1.,1.,1)
scaleObj(model,[-1.,1.,1.])
if mv.art.concat :
if hasattr(pat,'offset') : offset = pat.offset[:]
else : offset =[0.,0.,0.]
m[12] = (m[12]+offset[0])#* mv.art.scaleDevice
m[13] = (m[13]+offset[1])#* mv.art.scaleDevice
m[14] = (m[14]+offset[2])#* mv.art.scaleDevice
newMat=rotax.interpolate3DTransform([m.reshape(4,4)], [1],
mv.art.scaleDevice)
concatObjectMatrix(model,newMat)
else :
if hasattr(pat,'offset') : offset = pat.offset[:]
else : offset =[0.,0.,0.]
m[12] = (m[12]+offset[0])* mv.art.scaleDevice
m[13] = (m[13]+offset[1])* mv.art.scaleDevice
m[14] = (m[14]+offset[2])* mv.art.scaleDevice
#r1=m.reshape(4,4)
#newMat=rotax.interpolate3DTransform([r1], [1],
# mv.art.scaleDevice)
#m[0:3][0:3]=newMat[0:3][0:3]
setObjectMatrix(model,m.reshape(4,4))
#updateAppli()
def ARloop(mv,ar=True,im=None,ims=None,max=1000):
count = 0
while count < max:
#print count
if im is not None:
updateImage(mv,im,scale=ims)
if ar :
ARstep(mv)
update()
count = count + 1
def AR(mv,v=None,ar=True):#,im=None,ims=None,max=1000):
count = 0
while 1:
#print count
if v is not None:
#updateBmp(mv,bmp,scale=None,show=False,viewport=v)
updateImage(mv,viewport=v)
if ar :
ARstepM(mv)
#update()
count = count + 1
Y=range(480)*640
Y.sort()
X=range(640)*480
#import StringIO
#im = Image.open(StringIO.StringIO(buffer))
#helper.updateImage(self,viewport=Right,order=[1, 2, 3, 1])
def updateImage(mv,viewport=None,order=[1, 2, 3, 1]):
#debug image is just white...
try :
if viewport is not None :
viewport[c4d.symbols.BASEDRAW_DATA_SHOWPICTURE] = bool(mv.art.AR.show_tex)
import Image
cam = mv.art.arcontext[0].cam
cam.lock.acquire()
#print "acquire"
#arcontext = mv.art.arcontext[0]
#array = Numeric.array(cam.im_array[:])
#n=int(len(array)/(cam.width*cam.height))
if mv.art.AR.debug :
array = cam.imd_array[:]#.tostring()
#print "debug",len(array)
else :
array = cam.im_array[:]#.tostring()
#print "normal",len(array)
#img=Numeric.array(array[:])
#n=int(len(img)/(arcontext.cam.width*arcontext.cam.height))
#img=img.reshape(arcontext.cam.height,arcontext.cam.width,n)
#if n == 3 :
# mode = "RGB"
#else :
# mode = "RGBA"
#im = Image.fromarray(img, mode)#.resize((160,120),Image.NEAREST).transpose(Image.FLIP_TOP_BOTTOM)
im = Image.fromstring("RGBA",(mv.art.video.width,mv.art.video.height),
array.tostring() ).resize((320,240),Image.NEAREST)
#cam.lock.release()
#scale/resize image ?
#print "image"
rgba = im.split()
new = Image.merge("RGBA", (rgba[order[0]],rgba[order[1]],rgba[order[2]],rgba[order[3]]))
#print "save"
if mv.art.patternMgr.mirror :
import ImageOps
im=ImageOps.mirror(pilImage)
imf=ImageOps.flip(im)
imf.save("/tmp/arpmv.jpg")
else :
new.save("/tmp/arpmv.jpg")
if viewport is not None :
viewport[c4d.symbols.BASEDRAW_DATA_PICTURE] = "/tmp/arpmv.jpg"
#print "update"
cam.lock.release()
except:
print "PROBLEM VIDEO"
def updateBmp(mv,bmp,scale=None,order=[3, 2, 2, 1],show=True,viewport=None):
#cam.lock.acquire()
#dialog.keyModel.Set(imarray=cam.im_array.copy())
#cam.lock.release()
#import Image
cam = mv.art.arcontext[0].cam
mv.art.arcontext[0].cam.lock.acquire()
array = Numeric.array(cam.im_array[:])
mv.art.arcontext[0].cam.lock.release()
n=int(len(array)/(cam.width*cam.height))
array.shape = (-1,4)
map( lambda x,y,v,bmp=bmp: bmp.SetPixel(x, y, v[1], v[2], v[3]),X, Y, array)
if scale != None :
bmp.Scale(scale,256,False,False)
if show : c4d.bitmaps.ShowBitmap(scale)
scale.Save(name="/tmp/arpmv.jpg", format=c4d.symbols.FILTER_JPG)
else :
if show : c4d.bitmaps.ShowBitmap(bmp)
bmp.Save(name="/tmp/arpmv.jpg", format=c4d.symbols.FILTER_JPG)
if viewport is not None:
viewport[c4d.symbols.BASEDRAW_DATA_PICTURE] = "/tmp/arpmv.jpg"
from c4d import threading
class c4dThread(threading.C4DThread):
def __init__(self,func=None,arg=None):
threading.C4DThread.__init__(self)
self.func = func
self.arg = arg
def Main(self):
self.func(self.arg)
import time
class TimerDialog(c4d.gui.SubDialog):
"""
Timer dialog for c4d, wait time for user input.
from Pmv.hostappInterface.cinema4d import helperC4D as helper
dial = helper.TimerDialog()
dial.cutoff = 30.0
dial.Open(async=True, pluginid=3555550, width=120, height=100)
"""
def init(self):
self.startingTime = time.time()
self.dT = 0.0
self._cancel = False
self.SetTimer(100) #miliseconds
#self.cutoff = ctime #seconds
#self.T = int(ctime)
def initWidgetId(self):
id = 1000
self.BTN = {"No":{"id":id,"name":"No",'width':50,"height":10,
"action":self.continueFill},
"Yes":{"id":id+1,"name":"Yes",'width':50,"height":10,
"action":self.stopFill},
}
id += len(self.BTN)
self.LABEL_ID = [{"id":id,"label":"Did you want to Cancel the Filling Job:"},
{"id":id+1,"label":str(self.cutoff) } ]
id += len(self.LABEL_ID)
return True
def CreateLayout(self):
ID = 1
self.SetTitle("Cancel?")
self.initWidgetId()
#minimize otin/button
self.GroupBegin(id=ID,flags=c4d.gui.BFH_SCALEFIT | c4d.gui.BFV_MASK,
cols=2, rows=10)
self.GroupBorderSpace(10, 10, 5, 10)
ID +=1
self.AddStaticText(self.LABEL_ID[0]["id"],flags=c4d.gui.BFH_LEFT)
self.SetString(self.LABEL_ID[0]["id"],self.LABEL_ID[0]["label"])
self.AddStaticText(self.LABEL_ID[1]["id"],flags=c4d.gui.BFH_LEFT)
self.SetString(self.LABEL_ID[1]["id"],self.LABEL_ID[1]["label"])
ID +=1
for key in self.BTN.keys():
self.AddButton(id=self.BTN[key]["id"], flags=c4d.gui.BFH_LEFT | c4d.gui.BFV_MASK,
initw=self.BTN[key]["width"],
inith=self.BTN[key]["height"],
name=self.BTN[key]["name"])
self.init()
return True
def Timer(self,val):
# print val
#use to se if the user answer or not...like of nothing after x ms
#close the dialog
# self.T -= 1.0
curent_time = time.time()
self.dT = curent_time - self.startingTime
# print self.dT, self.T
self.SetString(self.LABEL_ID[1]["id"],str(self.cutoff-self.dT ))
if self.dT > self.cutoff :
self.continueFill()
def open(self):
self.Open(async=False, pluginid=25555589, width=120, height=100)
def stopFill(self):
self._cancel = True
self.Close()
def continueFill(self):
self._cancel = False
self.Close()
def Command(self, id, msg):
for butn in self.BTN.keys():
if id == self.BTN[butn]["id"]:
self.BTN[butn]["action"]()
return True
```
#### File: Pmv/hostappInterface/comput_util.py
```python
import numpy.oldnumeric as Numeric
from MolKit.pdbWriter import PdbWriter
#from MolKit.chargeCalculator import KollmanChargeCalculator,GasteigerChargeCalculator
from PyAutoDock.MolecularSystem import MolecularSystem
from PyAutoDock.AutoDockScorer import AutoDock305Scorer, AutoDock4Scorer
#from PyAutoDock.AutoDockScorer import AutoDockTermWeights305, AutoDockTermWeights4
#from PyAutoDock.trilinterp_scorer import TrilinterpScorer,TrilinterpScorer_AD3
from PyAutoDock.scorer import WeightedMultiTerm
from PyAutoDock.electrostatics import Electrostatics
from PyAutoDock.vanDerWaals import VanDerWaals,HydrogenBonding
#from PyAutoDock.vanDerWaals import HydrogenBonding
from PyAutoDock.desolvation import Desolvation
#import warnings
from MolKit.molecule import Atom
#######################MATH FUNCTION##########################################################
def transformedCoordinatesWithMatrice(mol,matrice):
""" for a nodeset, this function returns transformed coordinates.
This function will use the pickedInstance attribute if found.
@type mol: MolKit node
@param mol: the molecule to be transfromed
@type matrice: 4x4array
@param matrice: the matrix to apply to the molecule node
@rtype: array
@return: the transformed list of 3d points from the molecule atom coordinates
"""
vt = []
#transfo = matrice#Numeric.transpose(Numeric.reshape(pat.mat_transfo,(4,4)))
scaleFactor = 1.#pat.scaleFactor
#for node in nodes:
#find all atoms and their coordinates
coords = mol.allAtoms.coords# nodes.findType(Atom).coords
#g = nodes[0].top.geomContainer.geoms['master']
# M1 = g.GetMatrix(g.LastParentBeforeRoot())
# apply the AR transfo matrix
M = matrice#Numeric.dot(transfo,M1)
for pt in coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3]) /scaleFactor
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3]) /scaleFactor
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3]) /scaleFactor
vt.append( (ptx, pty, ptz) )
return vt
def rotatePoint(pt,m,ax):
x=pt[0]
y=pt[1]
z=pt[2]
u=ax[0]
v=ax[1]
w=ax[2]
ux=u*x
uy=u*y
uz=u*z
vx=v*x
vy=v*y
vz=v*z
wx=w*x
wy=w*y
wz=w*z
sa=sin(ax[3])
ca=cos(ax[3])
pt[0]=(u*(ux+vy+wz)+(x*(v*v+w*w)-u*(vy+wz))*ca+(-wy+vz)*sa)+ m[0]
pt[1]=(v*(ux+vy+wz)+(y*(u*u+w*w)-v*(ux+wz))*ca+(wx-uz)*sa)+ m[1]
pt[2]=(w*(ux+vy+wz)+(z*(u*u+v*v)-w*(ux+vy))*ca+(-vx+uy)*sa)+ m[2]
return pt
def matrixToEuler(mat):
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'
notes : this conversion uses conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm'
Coordinate System: right hand
Positive angle: right hand
Order of euler angles: heading first, then attitude, then bank
matrix row column ordering:
[m00 m01 m02]
[m10 m11 m12]
[m20 m21 m22]
@type mat: 4x4array
@param mat: the matrix to convert in euler angle (heading,attitude,bank)
@rtype: 3d array
@return: the computed euler angle from the matrice
"""
#Assuming the angles are in radians.
#3,3 matrix m[0:3,0:3]
#return heading,attitude,bank Y,Z,X
import math
if (mat[1][0] > 0.998) : # singularity at north pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = math.pi/2.
bank = 0
return (heading,attitude,bank)
if (mat[1][0] < -0.998) : # singularity at south pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = -math.pi/2.
bank = 0
return (heading,attitude,bank)
heading = math.atan2(-mat[2][0],mat[0][0])
bank = math.atan2(-mat[1][2],mat[1][1])
attitude = math.asin(mat[1][0])
if mat[0][0] < 0 :
if (attitude < 0.) and (math.degrees(attitude) > -90.):
attitude = -math.pi-attitude
elif (attitude > 0.) and (math.degrees(attitude) < 90.):
attitude = math.pi-attitude
return (heading,attitude,bank)
def eulerToMatrix(euler): #double heading, double attitude, double bank
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'.
this conversion uses NASA standard aeroplane conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm'
Coordinate System: right hand
Positive angle: right hand
Order of euler angles: heading first, then attitude, then bank
matrix row column ordering:
[m00 m01 m02]
[m10 m11 m12]
[m20 m21 m22]
@type euler: 3d array
@param euler: the euler angle to convert in matrice
@rtype: 4x4array
@return: the matrix computed from the euler angle
"""
# Assuming the angles are in radians.
import math
heading=euler[0]
attitude=euler[1]
bank=euler[2]
m=[[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]]
ch = math.cos(heading)
sh = math.sin(heading)
ca = math.cos(attitude)
sa = math.sin(attitude)
cb = math.cos(bank)
sb = math.sin(bank)
m[0][0] = ch * ca
m[0][1] = sh*sb - ch*sa*cb
m[0][2] = ch*sa*sb + sh*cb
m[1][0] = sa
m[1][1] = ca*cb
m[1][2] = -ca*sb
m[2][0] = -sh*ca
m[2][1] = sh*sa*cb + ch*sb
m[2][2] = -sh*sa*sb + ch*cb
return m
rotY90n = Numeric.array([[ 0., 0., 1., 0.],
[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]],'f')
def ApplyMatrix(coords,mat):
"""
Apply the 4x4 transformation matrix to the given list of 3d points
@type coords: array
@param coords: the list of point to transform.
@type mat: 4x4array
@param mat: the matrix to apply to the 3d points
@rtype: array
@return: the transformed list of 3d points
"""
#4x4matrix"
coords = Numeric.array(coords)
one = Numeric.ones( (coords.shape[0], 1), coords.dtype.char )
c = Numeric.concatenate( (coords, one), 1 )
return Numeric.dot(c, Numeric.transpose(mat))[:, :3]
def Decompose4x4(matrix):
"""
Takes a matrix in shape (16,) in OpenGL form (sequential values go
down columns) and decomposes it into its rotation (shape (16,)),
translation (shape (3,)), and scale (shape (3,))
@type matrix: 4x4array
@param matrix: the matrix to decompose
@rtype: list of array
@return: the decomposition of the matrix ie : rotation,translation,scale
"""
m = matrix
transl = Numeric.array((m[12], m[13], m[14]), 'f')
scale0 = Numeric.sqrt(m[0]*m[0]+m[4]*m[4]+m[8]*m[8])
scale1 = Numeric.sqrt(m[1]*m[1]+m[5]*m[5]+m[9]*m[9])
scale2 = Numeric.sqrt(m[2]*m[2]+m[6]*m[6]+m[10]*m[10])
scale = Numeric.array((scale0,scale1,scale2)).astype('f')
mat = Numeric.reshape(m, (4,4))
rot = Numeric.identity(4).astype('f')
rot[:3,:3] = mat[:3,:3].astype('f')
rot[:,0] = (rot[:,0]/scale0).astype('f')
rot[:,1] = (rot[:,1]/scale1).astype('f')
rot[:,2] = (rot[:,2]/scale2).astype('f')
rot.shape = (16,)
#rot1 = rot.astype('f')
return rot, transl, scale
def rotatePoint(pt,m,ax):
"""
rotate a point (x,y,z) arount an axis by alha degree.
@type pt: point
@param pt: the point to rotate
@type m: array
@param m: translation offset to apply after the rotation
@type ax: vector4D
@param ax: axise of rotation (ax[0:3]) and the angle of rotation (ax[3])
@rtype: point
@return: the new rotated point
"""
x=pt[0]
y=pt[1]
z=pt[2]
u=ax[0]
v=ax[1]
w=ax[2]
ux=u*x
uy=u*y
uz=u*z
vx=v*x
vy=v*y
vz=v*z
wx=w*x
wy=w*y
wz=w*z
sa=sin(ax[3])
ca=cos(ax[3])
pt[0]=(u*(ux+vy+wz)+(x*(v*v+w*w)-u*(vy+wz))*ca+(-wy+vz)*sa)+ m[0]
pt[1]=(v*(ux+vy+wz)+(y*(u*u+w*w)-v*(ux+wz))*ca+(wx-uz)*sa)+ m[1]
pt[2]=(w*(ux+vy+wz)+(z*(u*u+v*v)-w*(ux+vy))*ca+(-vx+uy)*sa)+ m[2]
return pt
def norm(A):
"""Return vector norm"""
return Numeric.sqrt(sum(A*A))
def dist(A,B):
"""Return distnce between point A and point B"""
return Numeric.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)
def normsq(A):
"""Return square of vector norm"""
return abs(sum(A*A))
def normalize(A):
"""Normalize the Vector A"""
if (norm(A)==0.0) : return A
else :return A/norm(A)
def getCenter(coords):
"""
Get the center from a 3d array of coordinate x,y,z.
@type coords: liste/array
@param coords: the coordinates
@rtype: list/array
@return: the center of mass of the coordinates
"""
coords = Numeric.array(coords)#self.allAtoms.coords
center = sum(coords)/(len(coords)*1.0)
center = list(center)
for i in range(3):
center[i] = round(center[i], 4)
#print "center =", self.center
return center
def computeRadius(protein,center=None):
"""
Get the radius of gyration of a protein.
@type protein: MolKit Protein
@param protein: the molecule
@type center: list/array
@param center: the center of the molecule
@rtype: float
@return: the radius of the molecule
"""
if center == None : center = protein.getCenter()
rs = 0.
for atom in protein.allAtoms:
r = dist(center,atom._coords[0])
if r > rs:
rs = r
return rs
def convertColor(col,toint=True):
"""
This function will convert a color array [r,g,b] from range 1-255
to range 0.-1 (vice/versa)
@type col: array
@param col: the color [r,g,b]
@type toint: boolean
@param toint: way of the convertion, if true convert to 1-255, if false
convert to range 0-1
@rtype: array
@return: the converted color [0-1.,0-1.,0-1.] or [1-255,1-255,1-255]
"""
if toint and max(col)<=1.0: col = map( lambda x: x*255, col)
elif not toint and max(col)>1.0: col = map( lambda x: x/255., col)
return col
DGatomIds=['ASPOD1','ASPOD2','GLUOE1','GLUOE2', 'SERHG',
'THRHG1','TYROH','TYRHH',
'LYSNZ','LYSHZ1','LYSHZ2','LYSHZ3','ARGNE','ARGNH1','ARGNH2',
'ARGHH11','ARGHH12','ARGHH21','ARGHH22','ARGHE','GLNHE21',
'GLNHE22','GLNHE2',
'ASNHD2','ASNHD21', 'ASNHD22','HISHD1','HISHE2' ,
'CYSHG', 'HN']
def lookupDGFunc(atom):
assert isinstance(atom, Atom)
if atom.name in ['HN']:
atom.atomId = atom.name
else:
atom.atomId=atom.parent.type+atom.name
if atom.atomId not in DGatomIds:
atom.atomId=atom.element
return atom.atomId.upper()
def norm(A):
"Return vector norm"
return Numeric.sqrt(sum(A*A))
def dist(A,B):
return Numeric.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)
def normsq(A):
"Return square of vector norm"
return abs(sum(A*A))
def normalize(A):
"Normalize the Vector"
if (norm(A)==0.0) : return A
else :return A/norm(A)
def changeR(txt):
from Pmv.pmvPalettes import RasmolAminoSortedKeys
from MolKit.protein import ResidueSetSelector
#problem this residue not in r_keyD
rname = txt[0:3]
rnum = txt[3:]
if rname not in RasmolAminoSortedKeys :#ResidueSetSelector.r_keyD.keys() :
print rname
rname=rname.replace(" ","")
if len(rname) == 1 :
return rname+rnum
return rname[1]+rnum
else :
rname=rname.replace(" ","")
r1n=ResidueSetSelector.r_keyD[rname]
return r1n+rnum
def patchRasmolAminoColor():
from Pmv.pmvPalettes import RasmolAmino,RasmolAminoSortedKeys
RasmolAminocorrected=RasmolAmino.copy()
for res in RasmolAminoSortedKeys:
name=res.strip()
if name in ['A', 'C', 'G', 'T', 'U']:
name = 'D'+name
RasmolAminocorrected[name]= RasmolAmino[res]
del RasmolAminocorrected[res]
return RasmolAminocorrected
#######################ENERGY CLASS & FUNCTION##########################################################
class EnergyHandler:
""" object to manage the different energies calculation between set of atoms """
def __init__(self,viewer):
self.viewer = viewer
# list the energies instance to manage
self.data = {} # keys name, values: energie classs instance
self.current_scorer = None
self.realTime = True
def add(self,atomset1,atomset2,score_type='c_ad3Score',**kw):
""" a pairs of atoms to get energies between them
should be receptor ligan
"""
# make name from molecule name of each atom set instance
n1 = atomset1.top.uniq()[0].name
n2 = atomset2.top.uniq()[0].name
n = n1+'-'+n2+'-'+score_type
if self.viewer.hasGui : self.viewer.infoBox.Set(visible=True)
# we test if energy scorer already been setup
if self.data.has_key(n):
self.current_scorer = self.data[n]
return self.data[n]
# we create a energy scorer for pairs of atoms
if score_type == 'PairWise':
nrg = PairWiseEnergyScorer(atomset1,atomset2)
elif score_type == 'Trilinterp':
nrg = TrilinterpEnergyScorer(atomset1,atomset2,stem=kw.get('stem'),atomtypes=kw.get('atomtypes'))
elif score_type == 'TrilinterpAD3':
nrg = TrilinterpEnergyScorerAD3(atomset1,atomset2,stem=kw.get('stem'),atomtypes=kw.get('atomtypes'))
elif score_type == 'PyPairWise':
nrg = PyPairWiseEnergyScorer(atomset1,atomset2)
elif score_type == 'ad3Score':
nrg = PyADCalcAD3Energies(atomset1,atomset2)
elif score_type == 'ad4Score':
nrg = PyADCalcAD4Energies(atomset1,atomset2)
elif score_type == 'c_ad3Score':
nrg = cADCalcAD3Energies(atomset1,atomset2)
elif score_type == 'c_ad4Score':
nrg = cADCalcAD4Energies(atomset1,atomset2)
self.data[n]=nrg
self.current_scorer = nrg
if self.viewer.hasGui:
self.viewer.GUI.nrg_pairs_combobox.setlist(self.data.keys())
self.viewer.GUI.nrg_pairs_combobox.setentry(self.data.keys()[0])
return nrg
def reset(self):
""" delete all the atoms pairs """
self.current_scorer = None
if self.viewer.hasGui:
self.viewer.GUI.nrg_pairs_combobox.setlist(self.data.keys())
## ATTENTION the following code do create a segmentation fault
## FIX ME AG 04/2007
## # free up allocate memory for each nengy scorer
## for scorer in self.data.values():
## scorer.free_memory()
## del(scorer)
## self.data.clear()
def compute_energies(self):
""" retrieve the score for each pairs """
sc = self.current_scorer
if sc is None: return
#if sc.mol1 in self.viewer.mol_detected.keys() and sc.mol2 in self.viewer.mol_detected.keys():
score,estat,hbond,vdw,ds = sc.doit()
from Pmv.moleculeViewer import EditAtomsEvent
#editAtom event ? just to check ?
#event = EditAtomsEvent('coords', sc.mol2.allAtoms)
#self.viewer.dispatchEvent(event)
if self.viewer.hasGui:
self.viewer.infoBox.update_entry(score=score,estat=estat,hbond=hbond,
vdw=vdw,ds=ds)
return True
def save_conformations(self):
for nrg in self.data.values():
nrg.saveCoords()
cAD=True
try:
from cAutoDock import scorer as c_scorer
from memoryobject import memobject
except:
cAD = False
memobject = None
c_scorer = None
class EnergyScorer:
""" Base class for energie scorer """
def __init__(self,atomset1,atomset2,func=None):
self.atomset1 =atomset1
self.atomset2 =atomset2
# save molecule instance of parent molecule
self.mol1 = self.atomset1.top.uniq()[0]
self.mol2 = self.atomset2.top.uniq()[0]
# dictionnary to save the state of each molecule when the
# energie is calculated, will allow to retrieve the conformation
# use for the energie calculation
# keys are score,values is a list a 2 set of coords (mol1,mol2)
self.confcoords = {}
self.ms = ms = MolecularSystem()
self.cutoff = 1.0
self.score = 0.0
def doit(self):
self.update_coords()
score,estat,hbond,vdw,ds= self.get_score()
self.score = score
self.saveCoords(score)
self.atomset1.setConformation(0)
self.atomset2.setConformation(0)
return (score,estat,hbond,vdw,ds)
def update_coords(self):
""" methods to update the coordinate of the atoms set """
pass
def get_score(self):
""" method to get the score """
score = estat = hbond = vdw = ds = 1000.
return (score,estat,hbond,vdw,ds)
def saveCoords(self,score):
"""methods to store each conformation coordinate.
the score is use as the key of a dictionnary to store the different conformation.
save the coords of the molecules to be use later to write out
a pdb file
We only save up 2 ten conformations per molecule. When 10 is reach we delete the one with the
highest energie
"""
score_int= int(score*100)
# check number of conf save
if len(self.confcoords.keys()) >= 50:
# find highest energies
val =max(self.confcoords.keys())
del(self.confcoords[val])
# add new conformation
coords = [self.atomset1.coords[:],self.atomset2.coords[:]]
self.confcoords[score_int] = coords
def writeCoords(self,score=None,filename1=None,filename2=None,
sort=True, transformed=False,
pdbRec=['ATOM', 'HETATM', 'CONECT'],
bondOrigin='all', ssOrigin=None):
""" write the coords of the molecules in pdb file
pdb is file will have the molecule name follow by number of conformation
"""
writer = PdbWriter()
if score is None:
score = min( self.confcoords.keys())
if not self.confcoords.has_key(float(score)): return
c1 = self.confcoords[score][0]
c2 = self.confcoords[score][1]
if filename1 is None:
filename1 = self.mol1.name + '_1.pdb'
prev_conf = self.setCoords(self.atomset1,c1)
writer.write(filename1, self.atomset1, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
self.atomset1.setConformation(prev_conf)
if filename2 is None:
filename2 = self.mol2.name + '_1.pdb'
prev_conf = self.setCoords(self.atomset2,c2)
writer.write(filename2, self.atomset2, sort=sort, records=pdbRec,
bondOrigin=bondOrigin, ssOrigin=ssOrigin)
self.atomset2.setConformation(prev_conf)
def setCoords(self,atomset,coords):
""" set the coords to a molecule """
mol = atomset.top.uniq()[0]
prev_conf = atomset.conformation[0]
# number of conformations available
confNum = len(atomset[0]._coords)
if hasattr(mol, 'nrgCoordsIndex'):
# uses the same conformation to store the transformed data
atomset.updateCoords(coords,
mol.nrgCoordsIndex)
else:
# add new conformation to be written to file
atomset.addConformation(coords)
mol.nrgCoordsIndex = confNum
atomset.setConformation( mol.nrgCoordsIndex )
return prev_conf
def free_memory(self):
""" Method to free memory allocate by scorer
Should be implemented """
pass
class TrilinterpEnergyScorer(EnergyScorer):
""" Scorer using the trilinterp method, base on autogrid
"""
def __init__(self,atomset1,atomset2,stem, atomtypes):
"""
based on AD4 scoring function:
stem (string) and atomtypes list (list of string)2 specify filenames for maps
value_outside_grid is energy penalty for pts outside box
atoms_to_ignore are assigned 0.0 energy: specifically
added to avoid huge energies from atoms bonded to flexible residues
"""
EnergyScorer.__init__(self,atomset1,atomset2)
self.l = self.ms.add_entities(self.atomset2)
#eg: stem = 'hsg1', atomtypes= ['C','A','HD','N','S']
scorer = self.scorer = TrilinterpScorer(stem, atomtypes,readMaps=True)
self.scorer.set_molecular_system(self.ms)
self.prop='Trilinterp'
self.scorer.prop = self.prop
self.grid_obj = None
def set_grid_obj(self,grid_obj):
self.grid_obj = grid_obj
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
confNum = 0
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
confNum = self.mol2.cconformationIndex
# transform ligand coord with grid.mat_transfo_inv
# put back the ligand in grid space
#print "dans update coord nrg"
#print self.mol2.allAtoms.coords
if hasattr(self.grid_obj,'mat_transfo_inv'):
M = self.grid_obj.mat_transfo_inv
vt = []
for pt in self.mol2.allAtoms.coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3])
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3])
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3])
vt.append( (ptx, pty, ptz) )
self.mol2.allAtoms.updateCoords(vt,ind=confNum)
#print vt
def get_score(self):
# labels atoms
score_array,terms_dic = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
self.score =score= min(Numeric.add.reduce(score_array),100.)
#self.score =score= min(self.scorer.get_score(),100.)
terms_score = terms_dic
estat = min(round(Numeric.add.reduce(terms_score[0]),2),1000.)
hbond = 0.#min(round(terms_score['m'],2),1000.)
vdw = min(round(Numeric.add.reduce(terms_score[1]),2),1000.)
ds = min(round(Numeric.add.reduce(terms_score[2]),2),1000.) #problem with ds
#ds=ds-ds
#self.score = self.score -ds
return (score,estat,hbond,vdw,ds)
class TrilinterpEnergyScorerAD3(EnergyScorer):
""" Scorer using the trilinterp method, base on autogrid
"""
def __init__(self,atomset1,atomset2,stem, atomtypes):
"""
based on AD4 scoring function:
stem (string) and atomtypes list (list of string)2 specify filenames for maps
value_outside_grid is energy penalty for pts outside box
atoms_to_ignore are assigned 0.0 energy: specifically
added to avoid huge energies from atoms bonded to flexible residues
"""
EnergyScorer.__init__(self,atomset1,atomset2)
self.l = self.ms.add_entities(self.atomset2)
#eg: stem = 'hsg1', atomtypes= ['C','A','HD','N','S']
scorer = self.scorer = TrilinterpScorer_AD3(stem, atomtypes)
self.scorer.set_molecular_system(self.ms)
self.prop = 'Trilinterp'
self.grid_obj = None
def set_grid_obj(self,grid_obj):
self.grid_obj = grid_obj
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
confNum = 0
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
confNum = self.mol2.cconformationIndex
# transform ligand coord with grid.mat_transfo_inv
# put back the ligand in grid space
#print "dans update coord nrg"
#print self.mol2.allAtoms.coords
if hasattr(self.grid_obj,'mat_transfo_inv'):
M = self.grid_obj.mat_transfo_inv
vt = []
for pt in self.mol2.allAtoms.coords:
ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3])
pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3])
ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3])
vt.append( (ptx, pty, ptz) )
self.mol2.allAtoms.updateCoords(vt,ind=confNum)
#print vt
def get_score(self):
score = self.scorer.get_score()
estat = 0.0
hbond = 0.0
vdw = 0.0
ds = 0.0
return (score,estat,hbond,vdw,ds)
class PairWiseEnergyScorer(EnergyScorer):
"""For each atom in one AtomSet, determine the electrostatics eneregy vs all the atoms in a second
AtomSet using the C implementation of the autodock scorer.
When using the autodock3 scorer, the receptor need to be loaded as a pdbqs file, the ligand as pdbqt.
"""
def __init__(self,atomset1,atomset2,scorer_ad_type='305'):
EnergyScorer.__init__(self,atomset1,atomset2)
self.prop = 'ad305_energy'
self.ms = ms = c_scorer.MolecularSystem()
self.receptor= self.pyMolToCAtomVect(atomset1)
self.ligand = self.pyMolToCAtomVect(atomset2)
self.r = ms.add_entities(self.receptor)
self.l = ms.add_entities(self.ligand)
ms.build_bonds( self.r )
ms.build_bonds( self.l )
# Notice: keep references to the terms !
# or they will be garbage collected.
self.scorer_ad_type = scorer_ad_type
if self.scorer_ad_type == '305':
self.ESTAT_WEIGHT_AUTODOCK = 0.1146 # electrostatics
self.HBOND_WEIGHT_AUTODOCK = 0.0656 # hydrogen bonding
self.VDW_WEIGHT_AUTODOCK = 0.1485 # van der waals
self.DESOLV_WEIGHT_AUTODOCK= 0.1711 # desolvation
## !!! Make sure that all the terms are save and not free after init is done
## use self.
self.estat = c_scorer.Electrostatics(ms)
self.hbond = c_scorer.HydrogenBonding(ms)
self.vdw = c_scorer.VanDerWaals(ms)
self.ds = c_scorer.Desolvation(ms)
self.scorer = c_scorer.WeightedMultiTerm(ms)
self.scorer.add_term(self.estat, self.ESTAT_WEIGHT_AUTODOCK)
self.scorer.add_term(self.hbond, self.HBOND_WEIGHT_AUTODOCK)
self.scorer.add_term(self.vdw, self.VDW_WEIGHT_AUTODOCK)
self.scorer.add_term(self.ds, self.DESOLV_WEIGHT_AUTODOCK)
# shared memory, used by C++ functions
self.proteinLen = len(atomset1)
self.ligLen = len(atomset2)
self.msLen = self.proteinLen + self.ligLen
self.sharedMem = memobject.allocate_shared_mem([self.msLen, 3],
'SharedMemory', memobject.FLOAT)
self.sharedMemPtr = memobject.return_share_mem_ptr('SharedMemory')[0]
#print "Shared memory allocated.."
def update_coords(self):
""" update the coordinate of atomset """
# use conformation set by dectected patterns
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
# get the coords
R_coords = self.atomset1.coords
L_coords = self.atomset2.coords
self.sharedMem[:] = Numeric.array(R_coords+L_coords, 'f')[:]
c_scorer.updateCoords(self.proteinLen, self.msLen, self.ms,self.sharedMemPtr)
def get_score(self):
""" return the score """
mini = self.ms.check_distance_cutoff(0, 1, self.cutoff)
# when number return should not do get_score ( proteins too close)
# flag = (mini==1.0 and mini==2.0)
flag = (mini == mini)
# for each of the terms and the score, we cap their max value to 100
# so if anything is greater than 100 we assign 100
# If their is bad contact score = 1000.
if flag: # if any distance < cutoff : no scoring
#self.score = min(9999999.9, 9999.9/mini)
self.score = 1000.
estat = hbond = vdw = ds = 1000.
else:
self.score = min(self.scorer.get_score(),100.)
estat = min(round(self.estat.get_score() * self.ESTAT_WEIGHT_AUTODOCK,2),1000.)
hbond = min(round(self.hbond.get_score() * self.HBOND_WEIGHT_AUTODOCK,2),1000.)
vdw = min(round(self.vdw.get_score() * self.VDW_WEIGHT_AUTODOCK,2),1000.)
ds = min(round(self.ds.get_score() * self.DESOLV_WEIGHT_AUTODOCK,2),1000.)
#print "--",estat,hbond,vdw,ds
return (self.score,estat,hbond,vdw,ds)
def pyMolToCAtomVect( self,mol):
"""convert Protein or AtomSet to AtomVector
"""
try :
from cAutoDock.scorer import AtomVector, Atom, Coords
except :
pass
className = mol.__class__.__name__
if className == 'Protein':
pyAtoms = mol.getAtoms()
elif className == 'AtomSet':
pyAtoms = mol
else:
return None
pyAtomVect = AtomVector()
for atm in pyAtoms:
a=Atom()
a.set_name(atm.name)
a.set_element(atm.autodock_element)# aromatic type 'A', vs 'C'
coords=atm.coords
a.set_coords( Coords(coords[0],coords[1],coords[2]))
a.set_charge( atm.charge)
try:
a.set_atvol( atm.AtVol)
except:
pass
try:
a.set_atsolpar( atm.AtSolPar)
except:
pass
a.set_bond_ord_rad( atm.bondOrderRadius)
a.set_charge( atm.charge)
pyAtomVect.append(a)
return pyAtomVect
def free_memory(self):
# free the shared memory
memobject.free_shared_mem("SharedMemory")
from AutoDockTools.pyAutoDockCommands import pep_aromList
class PyADCalcAD3Energies(EnergyScorer):
"""For each atom in one AtomSet, determine the autodock3 energy vs all the atoms in a second
AtomSet
"""
def __init__(self,atomset1,atomset2):
""" """
EnergyScorer.__init__(self,atomset1,atomset2)
self.weight = None
self.weightLabel = None
self.scorer = AutoDock305Scorer()
self.prop = self.scorer.prop
bothAts = atomset1 + atomset2
for a in bothAts:
if a.parent.type + '_' + a.name in pep_aromList:
a.autodock_element=='A'
a.AtSolPar = .1027
elif a.autodock_element=='A':
a.AtSolPar = .1027
elif a.autodock_element=='C':
a.AtSolPar = .6844
else:
a.AtSolPar = 0.0
self.r = self.ms.add_entities(atomset1)
self.l = self.ms.add_entities(atomset2)
self.scorer.set_molecular_system(self.ms)
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
for ind in (self.r,self.l):
# clear distance matrix
self.ms.clear_dist_mat(ind)
def get_score(self):
score = self.scorer.get_score()
terms_score = []
for t,w in self.scorer.terms:
terms_score.append(w*t.get_score())
estat = min(round(terms_score[0]),1000.)
hbond = min(round(terms_score[1]),1000.)
vdw = min(round(terms_score[2]),1000.)
ds = min(round(terms_score[3]),1000.)
# labels atoms
score_array = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
return (score,estat,hbond,vdw,ds)
class PyADCalcAD4Energies(EnergyScorer):
"""For each atom in one AtomSet, determine the autodock4 energy vs all the atoms
in a second AtomSet
"""
def __init__(self,atomset1,atomset2):
""" """
EnergyScorer.__init__(self,atomset1,atomset2)
self.weight = None
self.weightLabel = None
self.scorer = AutoDock4Scorer()
self.prop = self.scorer.prop
self.r = self.ms.add_entities(atomset1)
self.l = self.ms.add_entities(atomset2)
self.scorer.set_molecular_system(self.ms)
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
for ind in (self.r,self.l):
# clear distance matrix
self.ms.clear_dist_mat(ind)
def get_score(self):
score = self.scorer.get_score()
terms_score = []
for t,w in self.scorer.terms:
terms_score.append(w*t.get_score())
estat = min(round(terms_score[0]),1000.)
hbond = min(round(terms_score[1]),1000.)
vdw = min(round(terms_score[2]),1000.)
ds = min(round(terms_score[3]),1000.)
self.scores = [estat,hbond,vdw,ds]
# labels atoms
score_array = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
return (score,estat,hbond,vdw,ds)
if cAD:
from cAutoDock.AutoDockScorer import AutoDock305Scorer as c_AutoDock305Scorer
from cAutoDock.scorer import MolecularSystem as c_MolecularSystem
from cAutoDock.scorer import updateCoords as c_updateCoords
class cADCalcAD3Energies(EnergyScorer):
"""For each atom in one AtomSet, determine the electrostatics eneregy vs all the atoms in a second
AtomSet using the C implementation of the autodock scorer.
When using the autodock3 scorer, the receptor need to be loaded as a pdbqs file, the ligand as pdbqt.
"""
def __init__(self,atomset1,atomset2):
EnergyScorer.__init__(self,atomset1,atomset2)
self.weight = None
self.weightLabel = None
bothAts = atomset1 + atomset2
## for a in bothAts:
## if a.parent.type + '_' + a.name in pep_aromList:
## a.autodock_element=='A'
## a.AtSolPar = .1027
## elif a.autodock_element=='A':
## a.AtSolPar = .1027
## elif a.autodock_element=='C':
## a.AtSolPar = .6844
## else:
## a.AtSolPar = 0.0
self.ms = c_MolecularSystem()
self.receptor= self.pyMolToCAtomVect(atomset1)
self.ligand = self.pyMolToCAtomVect(atomset2)
self.r = self.ms.add_entities(self.receptor)
self.l = self.ms.add_entities(self.ligand)
self.ms.build_bonds( self.r )
self.ms.build_bonds( self.l )
self.scorer = c_AutoDock305Scorer(ms=self.ms,
pyatomset1=atomset1,
pyatomset2=atomset2)
self.prop = self.scorer.prop
# shared memory, used by C++ functions
self.proteinLen = len(atomset1)
self.ligLen = len(atomset2)
self.msLen = self.proteinLen + self.ligLen
self.sharedMem = memobject.allocate_shared_mem([self.msLen, 3],
'SharedMemory', memobject.FLOAT)
self.sharedMemPtr = memobject.return_share_mem_ptr('SharedMemory')[0]
#print "Shared memory allocated.."
def update_coords(self):
""" update the coordinate of atomset """
# use conformation set by dectected patterns
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
#confNum = self.mol2.cconformationIndex
# get the coords
#if hasattr(self.mol1,'mat_transfo_inv'):
# M = self.mol1.mat_transfo_inv
# vt = []
# for pt in self.mol2.allAtoms.coords:
# ptx = (M[0][0]*pt[0]+M[0][1]*pt[1]+M[0][2]*pt[2]+M[0][3])#+self.mol1.getCenter()[0]
# pty = (M[1][0]*pt[0]+M[1][1]*pt[1]+M[1][2]*pt[2]+M[1][3])#+self.mol1.getCenter()[1]
# ptz = (M[2][0]*pt[0]+M[2][1]*pt[1]+M[2][2]*pt[2]+M[2][3])#+self.mol1.getCenter()[2]
# vt.append( (ptx, pty, ptz) )
# self.mol2.allAtoms.updateCoords(vt,ind=confNum)#confNum
#
R_coords = self.atomset1.coords
L_coords = self.atomset2.coords
self.sharedMem[:] = Numeric.array(R_coords+L_coords, 'f')[:]
c_updateCoords(self.proteinLen, self.msLen, self.ms,self.sharedMemPtr)
def get_score(self):
""" return the score """
mini = self.ms.check_distance_cutoff(0, 1, self.cutoff)
# when number return should not do get_score ( proteins too close)
# flag = (mini==1.0 and mini==2.0)
flag = (mini == mini)
# for each of the terms and the score, we cap their max value to 100
# so if anything is greater than 100 we assign 100
# If their is bad contact score = 1000.
if flag: # if any distance < cutoff : no scoring
#self.score = min(9999999.9, 9999.9/mini)
self.score = 1000.
estat = hbond = vdw = ds = 1000.
self.scores = [1000.,1000.,1000.,1000.]
else:
self.score = min(self.scorer.get_score(),100.)
terms_score = self.scorer.get_score_per_term()
estat = min(round(terms_score[0],2),1000.)
hbond = min(round(terms_score[1],2),1000.)
vdw = min(round(terms_score[2],2),1000.)
ds = 0.#min(round(terms_score[3],2),1000.) #problem with ds
#print "--",estat,hbond,vdw,ds
self.scores = [estat,hbond,vdw,ds]
# labels atoms
score_array = self.scorer.get_score_array()
self.scorer.labels_atoms_w_nrg(score_array)
#ds=ds-ds
#self.score = self.score -ds
return (self.score,estat,hbond,vdw,ds)
def pyMolToCAtomVect( self,mol):
"""convert Protein or AtomSet to AtomVector
"""
from cAutoDock.scorer import AtomVector, Atom, Coords
className = mol.__class__.__name__
if className == 'Protein':
pyAtoms = mol.getAtoms()
elif className == 'AtomSet':
pyAtoms = mol
else:
return None
pyAtomVect = AtomVector()
for atm in pyAtoms:
a=Atom()
a.set_name(atm.name)
a.set_element(atm.autodock_element)# aromatic type 'A', vs 'C'
coords=atm.coords
a.set_coords( Coords(coords[0],coords[1],coords[2]))
a.set_charge( atm.charge)
try:
a.set_atvol( atm.AtVol)
except:
pass
try:
a.set_atsolpar( atm.AtSolPar)
except:
pass
a.set_bond_ord_rad( atm.bondOrderRadius)
a.set_charge( atm.charge)
pyAtomVect.append(a)
return pyAtomVect
def free_memory(self):
# free the shared memory
memobject.free_shared_mem("SharedMemory")
#############################################################################################################
class PyPairWiseEnergyScorer(EnergyScorer):
"""For each atom in one AtomSet, determine the electrostatics energy vs all the atoms in a second
AtomSet
"""
def __init__(self,atomset1,atomset2,scorer_ad_type='305'):
EnergyScorer.__init__(self,atomset1,atomset2)
self.r = self.ms.add_entities(self.atomset1)
self.l = self.ms.add_entities(self.atomset2)
self.scorer = WeightedMultiTerm()
self.scorer.set_molecular_system(self.ms)
self.scorer_ad_type = scorer_ad_type
if self.scorer_ad_type == '305':
self.ESTAT_WEIGHT_AUTODOCK = 0.1146 # electrostatics
self.HBOND_WEIGHT_AUTODOCK = 0.0656 # hydrogen bonding
self.VDW_WEIGHT_AUTODOCK = 0.1485 # van der waals
self.DESOLV_WEIGHT_AUTODOCK= 0.1711 # desolvation
# different terms to be use for score
self.estat= Electrostatics(self.ms)
self.scorer.add_term(self.estat, self.ESTAT_WEIGHT_AUTODOCK)
self.hbond=HydrogenBonding(self.ms)
self.scorer.add_term(self.hBond, self.HBOND_WEIGHT_AUTODOCK)
self.vdw = VanDerWaals(self.ms)
self.scorer.add_term(self.vdw, self.VDW_WEIGHT_AUTODOCK)
self.ds= Desolvation(self.ms)
self.scorer.add_term(self.ds,self.DESOLV_WEIGHT_AUTODOCK)
def update_coords(self):
""" update the coords """
if hasattr(self.mol1,'cconformationIndex'):
self.atomset1.setConformation(self.mol1.cconformationIndex)
if hasattr(self.mol2,'cconformationIndex'):
self.atomset2.setConformation(self.mol2.cconformationIndex)
for ind in (self.r,self.l):
# clear distance matrix
self.ms.clear_dist_mat(ind)
def get_score(self):
score = self.scorer.get_score()
estat = min(round(self.estat.get_score() * self.ESTAT_WEIGHT_AUTODOCK,2),1000.)
hbond = min(round(self.hbond.get_score() * self.HBOND_WEIGHT_AUTODOCK,2),1000.)
vdw = min(round(self.vdw.get_score() * self.VDW_WEIGHT_AUTODOCK,2),1000.)
ds = min(round(self.ds.get_score() * self.DESOLV_WEIGHT_AUTODOCK,2),1000.)
return (score,estat,hbond,vdw,ds)
#"""
#class PatternDistanceMatrix:
# # Object to store information about distance between a
# # set of patterns
#
#
# def __init__(self,patternList):
# self.patterns = patternList # list of patterns object
# self.vertices = [] # list of vertice of center of pattern
# self.centers = [] # list of center between two marker
# self.dist = [] # distance between 2 markers
# self.dist_str = [] # distance between 2 markers as string, so we
# # can pass it to display
#
# def clear_matrix(self):
# # delete all values store
# self.vertices = []
# self.centers = []
# self.dist = []
# self.dist_str = []
#
# def compute(self):
# # compute the distance between patterns
# We only compute half of the distance matrix as the rest is not needed
#
# self.clear_matrix()
# index = 0
# for pat in self.patterns[index:]:
# if not pat.isdetected: continue
# x = pat.gl_para[12]
# y = pat.gl_para[13]
# z = pat.gl_para[14]
# v = (x,y,z)
# for pat1 in self.patterns[index+1:]:
# if not pat1.isdetected: continue
# x1= pat1.gl_para[12]
# y1= pat1.gl_para[13]
# z1= pat1.gl_para[14]
# v1= (x1,y1,z1)
# # calculate distance
# d = util.measure_distance(Numeric.array(v),Numeric.array(v1))
# # calculate center between 2 patterns
# c = util.get_center(Numeric.array(v),Numeric.array(v1))
#
# self.dist.append(d)
# self.dist_str.append('%4.1f'%(d/10.)) # we want the values in centimeters
# # 1 unit = 10 mm
#
# self.vertices.append(v)
# self.vertices.append(v1)
# self.centers.append(c.tolist())
# index +=1
#
# def getall(self):
# # return vertices,centers,dist,dist_str
# return self.vertices,self.centers,self.dist,self.dist_str
#
#### Functions used to create Event
#
#def test_display_dist(arviewer):
# # test function to determine if we need to run the event function
# if arviewer.display_pat_distance: return True
#
#def display_distance(arviewer):
# # event function to display the distance between patterns
# vertices,centers,dist,dist_str = arviewer.patternMgr.distance_matrix.getall()
# arviewer.set_dist_geoms(vertices,centers,dist_str)
#
#
#
#def measure_atoms_dist(arviewer):
# # calculate and set to display the distance between atoms selected
# #Computes the distance between atom1, atom2, atom3.All coordinates are Cartesian; result is in mm
#
# #print "-- measure_atoms_dist --"
# detected_mols = [] # name list
# if len(arviewer.atoms_selected) < 2: return # we need at least 2 atoms selected to measure a distance
# vertices = []
# labelStr = []
# atm_dist_label = []
# centers = []
#
# for i in range(len(arviewer.atoms_selected) -1):
#
# at1 = arviewer.atoms_selected[i]
# at2 = arviewer.atoms_selected[i+1]
# # set correct conformation to get coordinate of atom
# # check if pattern is detected
# conf1=0
# conf2=0
# #if at1.top not in arviewer.mol_detected: continue
# #if at2.top not in arviewer.mol_detected: continue
#
# if hasattr(at1,'pat') :
# pat1 = at1.pat[0]
# if pat1 not in arviewer.current_context.patterns.keys(): continue
# pat1 = arviewer.current_context.patterns[at1.pat[0]]
# if not pat1.isdetected : continue
# #conf1 = arviewer.current_context.patterns[pat1].confNum
# conf1 = pat1.confNum
# if hasattr(at2,'pat') :
# pat2 = at2.pat[0]
# if pat2 not in arviewer.current_context.patterns.keys(): continue
# pat2 = arviewer.current_context.patterns[at2.pat[0]]
# if not pat2.isdetected : continue
# #conf1 = arviewer.current_context.patterns[pat1].confNum
# conf2 = pat2.confNum
# # check if atomset belong to a molecule that is part of
# # detected pattern
# #if at1.top not in arviewer.mol_detected: continue
# #if at2.top not in arviewer.mol_detected: continue
#
# #conf = arviewer.current_context.patterns[pat1].confNum
# at1.setConformation(conf1)
# c1 = Numeric.array(at1[0].coords)
# at1.setConformation(0)
#
# #conf = arviewer.current_context.patterns[pat2].confNum
# at2.setConformation(conf2)
# c2 = Numeric.array(at2[0].coords)
# at2.setConformation(0)
#
# d = util.measure_distance(c1,c2)#Numeric.array
# c = util.get_center(c1,c2)
# #print "%s - %s :%f"%(atom1.full_name(),atom2.full_name(),distance)
# d = d /10.0 # arviewer.current_context.patterns[pat2].scaleFactor # scale factor 1A -> 10mm
# #print d
# #print c1.tolist()
# vertices.append(c1.tolist())
# vertices.append(c2.tolist())
# #print "Distance:%3.f"%d
# atm_dist_label.append('%3.1f'%d)
# centers.append(c.tolist())
#
# labelStr.append(at1[0].name)
# labelStr.append(at2[0].name)
#
# #if arviewer.patternMgr.mirror : arviewer.set_dist_geoms_mirror(vertices,centers,atm_dist_label)
# #else : arviewer.set_dist_geoms(vertices,centers,atm_dist_label)
# arviewer.set_dist_geoms(vertices,centers,atm_dist_label)
#
#def test_measure_dist(arviewer):
# for i in range(len(arviewer.atoms_selected) -1):
# at1 = arviewer.atoms_selected[i]
# at2 = arviewer.atoms_selected[i+1]
# if at1.top[0] not in arviewer.mol_detected: return False
# if at2.top[0] not in arviewer.mol_detected: return False
# if hasattr(at1,'pat') :
# pat1 = at1.pat[0]
# if pat1 not in arviewer.current_context.patterns.keys(): return False
# pat1 = arviewer.current_context.patterns[at1.pat[0]]
# if not pat1.isdetected : return False
# if hasattr(at2,'pat') :
# pat2 = at2.pat[0]
# if pat2 not in arviewer.current_context.patterns.keys(): return False
# pat1 = arviewer.current_context.patterns[at1.pat[0]]
# if not pat1.isdetected : return False
# return True
#
#
#def measure_dist(arviewer):
# # calculate and set to display the distance between atoms selected
# #Computes the distance between atom1, atom2, atom3.All coordinates are Cartesian; result is in mm#
#
# #print "-- measure_atoms_dist --"
# detected_mols = [] # name list
# if len(arviewer.atoms_selected) < 2: return # we need at least 2 atoms selected to measure a distance
# vertices = []
# labelStr = []
# atm_dist_label = []
# centers = []
#
# mtr=arviewer.current_context.glcamera.rootObjectTransformation
# M=Numeric.reshape(mtr,(4,4))
# rot,tr,sc=arviewer.current_context.glcamera.Decompose4x4(mtr)
# p=arviewer.current_context.patterns.values()
#
# for i in range(len(arviewer.atoms_selected) -1):
#
# at1 = arviewer.atoms_selected[i]
# at2 = arviewer.atoms_selected[i+1]
# #print at1
# #print at2
# # set correct conformation to get coordinate of atom
# # check if pattern is detected
# conf1=0
# conf2=0
# #if at1.top not in arviewer.mol_detected: continue
# #if at2.top not in arviewer.mol_detected: continue
#
# if at1.top[0] not in arviewer.mol_detected:
# continue
# g=at1.top[0].geomContainer.masterGeom
# #c1 = Numeric.array(at1[0].coords)
# c1 = g.ApplyParentsTransform(Numeric.array([at1[0].coords,]))
# one = Numeric.ones( (c1.shape[0], 1), c1.dtype.char )
# c = Numeric.concatenate( (c1, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# c1=Numeric.dot(c, M)[:, :3]
# c1=c1[0]
# #print c1
# else :
# pat1 = arviewer.current_context.patterns[at1.pat[0]]
# if not pat1.isdetected : continue
# #pat1 = p[0]
# #print pat1.name
# conf1 = pat1.confNum
# #at1.setConformation(conf1)
# vt = util.transformedCoordinatesWithInstances(at1,pat1)
# c1=Numeric.array(vt)
# #c1 = Numeric.array(at1[0].coords)
# #at1.setConformation(0)
# one = Numeric.ones( (c1.shape[0], 1), c1.dtype.char )
# c = Numeric.concatenate( (c1, one), 1 )
# M=Numeric.reshape(mtr,(4,4))
# c1=Numeric.dot(c, M)[:, :3]
# c1=c1[0]
# #c1=c1+tr
# #print c1
# if at2.top[0] not in arviewer.mol_detected:
# continue
# g=at2.top[0].geomContainer.masterGeom
# #c1 = Numeric.array(at1[0].coords)
# c2 = g.ApplyParentsTransform(Numeric.array([at2[0].coords,]))
# one = Numeric.ones( (c2.shape[0], 1), c2.dtype.char )
# c = Numeric.concatenate( (c2, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# c2=Numeric.dot(c, M)[:, :3]
# c2=c2[0]
# #print c2
# else :
# #pat2 = p[0]
# pat2 = arviewer.current_context.patterns[at2.pat[0]]
# if not pat2.isdetected : continue
# #print pat2.name
# conf2 = pat2.confNum
# #at2.setConformation(conf2)
# vt = util.transformedCoordinatesWithInstances(at2,pat2)
# c2=Numeric.array(vt)
# #c2 = Numeric.array(at2[0].coords)
# #at2.setConformation(0)
# one = Numeric.ones( (c2.shape[0], 1), c2.dtype.char )
# c = Numeric.concatenate( (c2, one), 1 )
# M=Numeric.reshape(mtr,(4,4))
# c2=Numeric.dot(c, M)[:, :3]
# c2=c2[0]
# #c2=c2+tr
#
# # check if atomset belong to a molecule that is part of
# # detected pattern
# #f at1.top[0] not in arviewer.mol_detected: continue
# #f at2.top[0] not in arviewer.mol_detected: continue
#
#
# d = util.measure_distance(c1,c2)#Numeric.array
# c = util.get_center(c1,c2)
# #print "%s - %s :%f"%(atom1.full_name(),atom2.full_name(),distance)
# d = d /10.0 # arviewer.current_context.patterns[pat2].scaleFactor # scale factor 1A -> 10mm
# #print d
# #print c1.tolist()
# vertices.append(c1.tolist())
# vertices.append(c2.tolist())
# #print "Distance:%3.f"%d
# atm_dist_label.append('%3.1f'%d)
# centers.append(c.tolist())
#
# labelStr.append(at1[0].name)
# labelStr.append(at2[0].name)
#
# arviewer.set_dist_geoms(vertices,centers,atm_dist_label)
#
#def measure_dist2(arviewer):
# # calculate and set to display the distance between atoms selected
# #Computes the distance between atom1, atom2, atom3.All coordinates are Cartesian; result is in mm
#
# #print "-- measure_atoms_dist --"
# detected_mols = [] # name list
# if len(arviewer.atoms_selected) < 2: return # we need at least 2 atoms selected to measure a distance
# vertices = []
# labelStr = []
# atm_dist_label = []
# centers = []
# mtr=arviewer.current_context.glcamera.rootObjectTransformation
# M=Numeric.reshape(mtr,(4,4))
# rot,tr,sc=arviewer.current_context.glcamera.Decompose4x4(mtr)
# p=arviewer.current_context.patterns.values()
# for i in range(len(arviewer.atoms_selected) -1):
#
# at1 = arviewer.atoms_selected[i]
# at2 = arviewer.atoms_selected[i+1]
# #print at1
# #print at2
# # set correct conformation to get coordinate of atom
# # check if pattern is detected
# conf1=0
# conf2=0
#
# if at1.top[0] not in arviewer.mol_detected:
# g=at1.top[0].geomContainer.masterGeom
# #c1 = Numeric.array(at1[0].coords)
# c1 = g.ApplyParentsTransform(Numeric.array([at1[0].coords,]))
# one = Numeric.ones( (c1.shape[0], 1), c1.dtype.char )
# c = Numeric.concatenate( (c1, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# c1=Numeric.dot(c, M)[:, :3]
# c1=c1[0]
# # print c1
# else :
# pat1 = arviewer.current_context.patterns[at1.pat[0]]
# #pat1 = p[0]
# print pat1.name
# #f pat1 not in arviewer.current_context.patterns.keys(): continue
# conf1 = pat1.confNum
# #vt=util.transformedCoord(at1,pat1)
# vt = util.transformedCoordinatesWithInstances(at1,pat1)
# c1=Numeric.array(vt[0])
# #at1.setConformation(conf1)
# #c1 = Numeric.array(at1[0].coords)
# #at1.setConformation(0)
# #one = Numeric.ones( (c1.shape[0], 1), c1.dtype.char )
# #c = Numeric.concatenate( (c1, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# #c1=Numeric.dot(c, M)[:, :3]
# #c1=c1[0]
# #c1=c1-tr
# #print c1
# if at2.top[0] not in arviewer.mol_detected:
# g=at2.top[0].geomContainer.masterGeom
# #c1 = Numeric.array(at1[0].coords)
# c2 = g.ApplyParentsTransform(Numeric.array([at2[0].coords,]))
# one = Numeric.ones( (c2.shape[0], 1), c2.dtype.char )
# c = Numeric.concatenate( (c2, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# c2=Numeric.dot(c, M)[:, :3]
# c2=c2[0]
# #print c2
# else :
# #pat2 = p[0]
# pat2 = arviewer.current_context.patterns[at2.pat[0]]
# #print pat2.name
# #f pat1 not in arviewer.current_context.patterns.keys(): continue
# conf2 = pat2.confNum
# vt = util.transformedCoordinatesWithInstances(at2,pat2)
# c2=Numeric.array(vt[0])
# # print c2
# #at2.setConformation(conf2)
# #c2 = Numeric.array(at2[0].coords)
# #at2.setConformation(0)
# #one = Numeric.ones( (c2.shape[0], 1), c2.dtype.char )
# #c = Numeric.concatenate( (c2, one), 1 )
# #M=Numeric.reshape(mtr,(4,4))
# #c2=Numeric.dot(c, M)[:, :3]
# #c2=c2[0]
# #c2=c2-tr
#
# # check if atomset belong to a molecule that is part of
# # detected pattern
# #f at1.top[0] not in arviewer.mol_detected: continue
# #f at2.top[0] not in arviewer.mol_detected: continue
#
#
# d = util.measure_distance(c1,c2)#Numeric.array
# c = util.get_center(c1,c2)
# #print "%s - %s :%f"%(atom1.full_name(),atom2.full_name(),distance)
# d = d /10.0 # arviewer.current_context.patterns[pat2].scaleFactor # scale factor 1A -> 10mm
# #print d
# #print c1.tolist()
# vertices.append(c1.tolist())
# vertices.append(c2.tolist())
# # print "Distance:%3.f"%d
# atm_dist_label.append('%3.1f'%d)
# centers.append(c.tolist())
#
# labelStr.append(at1[0].name)
# labelStr.append(at2[0].name)
#
# arviewer.set_dist_geoms(vertices,centers,atm_dist_label)
#"""
################
import math
from math import sqrt, cos, sin, acos,atan2,asin
import numpy as N
import numpy
Q_EPSILON = 0.0000000001
X = 0
Y = 1
Z = 2
W = 3
def q_make( x, y, z, angle):
"""q_make: make a quaternion given an axis and an angle (in radians)
notes:
- rotation is counter-clockwise when rotation axis vector is
pointing at you
- if angle or vector are 0, the identity quaternion is returned.
double x, y, z : axis of rotation
double angle : angle of rotation about axis in radians
"""
length=0
cosA=0
sinA=0
destQuat = [0.0,0.0,0.0,0.0]
#/* normalize vector */
length = sqrt( x*x + y*y + z*z )
#/* if zero vector passed in, just return identity quaternion */
if ( length < Q_EPSILON ) :
destQuat[X] = 0
destQuat[Y] = 0
destQuat[Z] = 0
destQuat[W] = 1
return
x /= length
y /= length
z /= length
cosA = cos(angle / 2.0)
sinA = sin(angle / 2.0)
destQuat[W] = cosA
destQuat[X] = sinA * x
destQuat[Y] = sinA * y
destQuat[Z] = sinA * z
return destQuat
def q_from_col_matrix(srcMatrix) :
"""#/*****************************************************************************
# * q_from_col_matrix- Convert 4x4 column-major rotation matrix
# * to unit quaternion.
# *****************************************************************************/
"""
trace=0
s=0
i=0
j=0
k=0
next = [Y, Z, X]
destQuat = [0.0,0.0,0.0,0.0]
trace = srcMatrix[X][X] + srcMatrix[Y][Y] + srcMatrix[Z][Z]
if (trace > 0.0) :
s = sqrt(trace + 1.0)
destQuat[W] = s * 0.5
s = 0.5 / s
destQuat[X] = (srcMatrix[Z][Y] - srcMatrix[Y][Z]) * s
destQuat[Y] = (srcMatrix[X][Z] - srcMatrix[Z][X]) * s
destQuat[Z] = (srcMatrix[Y][X] - srcMatrix[X][Y]) * s
else :
i = X
if (srcMatrix[Y][Y] > srcMatrix[X][X]):
i = Y
if (srcMatrix[Z][Z] > srcMatrix[i][i]):
i = Z
j = next[i]
k = next[j]
s = sqrt( (srcMatrix[i][i] - (srcMatrix[j][j]+srcMatrix[k][k])) + 1.0 )
destQuat[i] = s * 0.5
s = 0.5 / s
destQuat[W] = (srcMatrix[k][j] - srcMatrix[j][k]) * s
destQuat[j] = (srcMatrix[j][i] + srcMatrix[i][j]) * s
destQuat[k] = (srcMatrix[k][i] + srcMatrix[i][k]) * s
return destQuat
def q_from_row_matrix(srcMatrix):
"""#/*****************************************************************************
# *
# q_from_row_matrix: Convert 4x4 row-major rotation matrix to unit quaternion
# *
# *****************************************************************************/
"""
trace=0
s=0
i=0
j=0
k=0
next = [Y, Z, X]
destQuat = [0.0,0.0,0.0,0.0]
trace = srcMatrix[X][X] + srcMatrix[Y][Y]+ srcMatrix[Z][Z];
if (trace > 0.0):
s = sqrt(trace + 1.0)
destQuat[W] = s * 0.5
s = 0.5 / s
destQuat[X] = (srcMatrix[Y][Z] - srcMatrix[Z][Y]) * s
destQuat[Y] = (srcMatrix[Z][X] - srcMatrix[X][Z]) * s
destQuat[Z] = (srcMatrix[X][Y] - srcMatrix[Y][X]) * s
else :
i = X
if (srcMatrix[Y][Y] > srcMatrix[X][X]):
i = Y
if (srcMatrix[Z][Z] > srcMatrix[i][i]):
i = Z
j = next[i]
k = next[j]
s = sqrt( (srcMatrix[i][i] - (srcMatrix[j][j]+srcMatrix[k][k])) + 1.0 )
destQuat[i] = s * 0.5
s = 0.5 / s
destQuat[W] = (srcMatrix[j][k] - srcMatrix[k][j]) * s
destQuat[j] = (srcMatrix[i][j] + srcMatrix[j][i]) * s
destQuat[k] = (srcMatrix[i][k] + srcMatrix[k][i]) * s
return destQuat
def quat_to_ogl_matrix(srcQuat):
print "quat"
#For unit srcQuat, just set s = 2.0, or set xs = srcQuat[X] + srcQuat[X], etc.
s = 2.0 / ( srcQuat[X] * srcQuat[X] + srcQuat[Y] * srcQuat[Y] + srcQuat[Z] * srcQuat[Z] + srcQuat[W] * srcQuat[W] )
xs = srcQuat[X] * s
ys = srcQuat[Y] * s
zs = srcQuat[Z] * s
wx = srcQuat[W] * xs
wy = srcQuat[W] * ys
wz = srcQuat[W] * zs
xx = srcQuat[X] * xs
xy = srcQuat[X] * ys
xz = srcQuat[X] * zs
yy = srcQuat[Y] * ys
yz = srcQuat[Y] * zs
zz = srcQuat[Z] * zs
#set up 4x4 matrix
matrix=[]
matrix.append(1.0 - ( yy + zz ))
matrix.append(xy + wz)
matrix.append(xz - wy)
matrix.append(0.0)
matrix.append(xy - wz)
matrix.append(1.0 - ( xx + zz ))
matrix.append(yz + wx)
matrix.append(0.0)
matrix.append(xz + wy)
matrix.append(yz - wx)
matrix.append(1.0 - ( xx + yy ))
matrix.append(0.0)
matrix.append(0.0)
matrix.append(0.0)
matrix.append(0.0)
matrix.append(1.0)
return matrix
def quat_to_matrix(srcQuat):
#print "quat"
#For unit srcQuat, just set s = 2.0, or set xs = srcQuat[X] + srcQuat[X], etc.
#s = 2.0 / ( srcQuat[X] * srcQuat[X] + srcQuat[Y] * srcQuat[Y] + srcQuat[Z] * srcQuat[Z] + srcQuat[W] * srcQuat[W] )
#xs = srcQuat[X] * s
#ys = srcQuat[Y] * s
#zs = srcQuat[Z] * s
#wx = srcQuat[W] * xs
##wy = srcQuat[W] * ys
#wz = srcQuat[W] * zs
#xx = srcQuat[X] * xs
#xy = srcQuat[X] * ys
#xz = srcQuat[X] * zs
#yy = srcQuat[Y] * ys
#yz = srcQuat[Y] * zs
#zz = srcQuat[Z] * zs
#set up 4x4 matrix
matrix=[]
matrix.append(1.0 - 2*(srcQuat[Y] * srcQuat[Y]) - 2*(srcQuat[Z] * srcQuat[Z]))
matrix.append(2*(srcQuat[X] * srcQuat[Y])-2*(srcQuat[Z] * srcQuat[W]))
matrix.append(2*(srcQuat[X] * srcQuat[Z])+2*(srcQuat[Y] * srcQuat[W]))
matrix.append(0.0)
matrix.append(2*(srcQuat[X] * srcQuat[Y])+2*(srcQuat[Z] * srcQuat[W]))
matrix.append(1.0 - 2*(srcQuat[X] * srcQuat[X]) - 2*(srcQuat[Z] * srcQuat[Z]))
matrix.append(2*(srcQuat[Y] * srcQuat[Z])-2*(srcQuat[X] * srcQuat[W]))
matrix.append(0.0)
matrix.append(2*(srcQuat[X] * srcQuat[Z])-2*(srcQuat[Y] * srcQuat[W]))
matrix.append(2*(srcQuat[Y] * srcQuat[Z])+2*(srcQuat[X] * srcQuat[W]))
matrix.append(1.0 - 2*(srcQuat[X] * srcQuat[X]) - 2*(srcQuat[Y] * srcQuat[Y]))
matrix.append(0.0)
matrix.append(0.0)
matrix.append(0.0)
matrix.append(0.0)
matrix.append(1.0)
return matrix
def quat_invert(q) :
qres = [0.0,0.0,0.0,0.0]
qNorm = 0.0;
qNorm = 1.0 / (q[X]*q[X] + q[Y]*q[Y] + q[Z]*q[Z] + q[W]*q[W])
qres[X] = -q[X] * qNorm
qres[Y] = -q[Y] * qNorm
qres[Z] = -q[Z] * qNorm
qres[W] = q[W] * qNorm
return qres
def quat_sum(q1,q2) :
qres = [0.0,0.0,0.0,0.0]
qres[W] = q1[W]+q2[W]
qres[X] = q1[X]+q2[X]
qres[Y] = q1[Y]+q2[Y]
qres[Z] = q1[Z]+q2[Z]
return qres
def quat_mult(q1,q2) :
qres = [0.0,0.0,0.0,0.0]
qres[W] = q1[W]*q2[W] - q1[X]*q2[X] - q1[Y]*q2[Y] - q1[Z]*q2[Z]
qres[X] = q1[W]*q2[X] + q1[X]*q2[W] + q1[Y]*q2[Z] - q1[Z]*q2[Y]
qres[Y] = q1[W]*q2[Y] + q1[Y]*q2[W] + q1[Z]*q2[X] - q1[X]*q2[Z]
qres[Z] = q1[W]*q2[Z] + q1[Z]*q2[W] + q1[X]*q2[Y] - q1[Y]*q2[X]
return qres
def quat_normalize(q) :
qres = [0.0,0.0,0.0,0.0]
normalizeFactor = 0.0;
normalizeFactor = 1.0 / sqrt( q[X]*q[X] + q[Y]*q[Y] + q[Z]*q[Z] + q[W]*q[W])
qres[X] = q[X] * normalizeFactor
qres[Y] = q[Y] * normalizeFactor
qres[Z] = q[Z] * normalizeFactor
qres[W] = q[W] * normalizeFactor
return qres
def quat_diff(q1,q2) :
quat_inv = quat_invert(q1)
quat_diff = quat_mult(q2,quat_inv)
quat_norm = quat_normalize(quat_diff)
return quat_norm
# -*- coding: utf-8 -*-
# transformations.py
# http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
# Copyright (c) 2006, <NAME>
# Copyright (c) 2006-2010, The Regents of the University of California
# All rights reserved.
def unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. eucledian norm, along axis.
>>> v0 = numpy.random.random(3)
>>> v1 = unit_vector(v0)
>>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
True
>>> v0 = numpy.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, axis=-1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2)
>>> numpy.allclose(v1, v2)
True
>>> v1 = unit_vector(v0, axis=1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1)
>>> numpy.allclose(v1, v2)
True
>>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float64)
>>> unit_vector(v0, axis=1, out=v1)
>>> numpy.allclose(v1, v2)
True
>>> list(unit_vector([]))
[]
>>> list(unit_vector([1.0]))
[1.0]
"""
if out is None:
data = numpy.array(data, dtype=numpy.float64, copy=True)
if data.ndim == 1:
data /= math.sqrt(numpy.dot(data, data))
return data
else:
if out is not data:
out[:] = numpy.array(data, copy=False)
data = out
length = numpy.atleast_1d(numpy.sum(data*data, axis))
numpy.sqrt(length, length)
if axis is not None:
length = numpy.expand_dims(length, axis)
data /= length
if out is None:
return data
def swithQuat(quat,inv=False):
if inv:
return [quat[1],quat[2],quat[3],quat[0]]
else :
return [quat[3],quat[0],quat[1],quat[2]]
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0.0)
>>> numpy.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1.0, 1)
>>> numpy.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = math.acos(numpy.dot(q0, q))
>>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \
numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle)
True
"""
q0 = unit_vector(swithQuat(quat0)[:4])
q1 = unit_vector(swithQuat(quat1)[:4])
if fraction == 0.0:
return q0
elif fraction == 1.0:
return q1
d = numpy.dot(q0, q1)
if abs(abs(d) - 1.0) < _EPS:
return q0
if shortestpath and d < 0.0:
# invert rotation
d = -d
q1 *= -1.0
angle = math.acos(d) + spin * math.pi
if abs(angle) < _EPS:
return q0
isin = 1.0 / math.sin(angle)
q0 *= math.sin((1.0 - fraction) * angle) * isin
q1 *= math.sin(fraction * angle) * isin
q0 += q1
return swithQuat(q0,inv=True)
def quat_to_axis_angle(q) :
axis_angle = [0.0,0.0,0.0,0.0]
length = sqrt( q[X]*q[X] + q[Y]*q[Y] + q[Z]*q[Z])
if (length < Q_EPSILON) :
axis_angle[2] = 1.0
else :
#According to an article by <NAME> (<EMAIL>) on Game Developer's
#Network, the following conversion is appropriate.
axis_angle[X] = q[X] / length;
axis_angle[Y] = q[Y] / length;
axis_angle[Z] = q[Z] / length;
axis_angle[W] = 2 * acos(q[W]);
return axis_angle
def rotatePoint(pt,m,ax):
x=pt[0]
y=pt[1]
z=pt[2]
u=ax[0]
v=ax[1]
w=ax[2]
ux=u*x
uy=u*y
uz=u*z
vx=v*x
vy=v*y
vz=v*z
wx=w*x
wy=w*y
wz=w*z
sa=sin(ax[3])
ca=cos(ax[3])
pt[0]=(u*(ux+vy+wz)+(x*(v*v+w*w)-u*(vy+wz))*ca+(-wy+vz)*sa)+ m[0]
pt[1]=(v*(ux+vy+wz)+(y*(u*u+w*w)-v*(ux+wz))*ca+(wx-uz)*sa)+ m[1]
pt[2]=(w*(ux+vy+wz)+(z*(u*u+v*v)-w*(ux+vy))*ca+(-vx+uy)*sa)+ m[2]
return pt
def euler_to_quat(yaw, pitch, roll):
half_yaw=float(yaw)/2.0
half_pitch=float(pitch)/2.0
half_roll=float(roll)/2.0
cosYaw = cos(half_yaw);
sinYaw = sin(half_yaw);
cosPitch = cos(half_pitch);
sinPitch = sin(half_pitch);
cosRoll = cos(half_roll);
sinRoll = sin(half_roll);
destQuat=[]
destQuat.append(cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw)
destQuat.append(cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw)
destQuat.append(sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw)
destQuat.append(cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw)
return destQuat
def quat_to_euler(q):
euler=[0.,0.,0.]#heading-pitch Y, attitude-yaw-Z,bank-roll-tilts-X // Y-azimuth, X-elevation, Z-tilt. // Y Z X
sqw=q[3]*q[3]
sqx=q[0]*q[0]
sqy=q[1]*q[1]
sqz=q[2]*q[2]
unit=sqx + sqy + sqz + sqw
test=q[0]*q[1]+q[2]*q[3]
if (test > 0.499) : # singularity at north pole
euler[0]=2 * atan2(q[0],q[3])
euler[1]=math.pi/2
euler[2]=0
return euler
if (test < -0.499) :# singularity at south pole
euler[0]=2 * atan2(q[0],q[3])
euler[1]=-1*math.pi/2
euler[2]=0
return euler
euler[0]=atan2(2*q[1]*q[3]-2*q[0]*q[2],1 - 2*sqy - 2*sqz)
euler[1]=asin(2*test)
euler[2]=atan2(2*q[0]*q[3]-2*q[1]*q[2],1 - 2*sqx - 2*sqz)
return euler
def dot(A,B):
return((A[0] * B[0]) + (A[1] * B[1]) + (A[2] * B[2]));
def angle(A,B):
"""give radians angle between vector A and B"""
normA=N.sqrt(N.sum(A*A))
normB=N.sqrt(N.sum(B*B))
return acos(dot(A/normA,B/normB))
def dist(A,B):
return sqrt((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)
def norm(A):
"Return vector norm"
return sqrt(sum(A*A))
def normsq(A):
"Return square of vector norm"
return abs(sum(A*A))
def normalize(A):
"Normalize the Vector"
if (norm(A)==0.0) : return A
else :return A/norm(A)
def mini_array(array):
count=0
mini=9999
mini_array=N.array([0.,0.,0.])
for i in xrange(len(array)):
norm=N.sqrt(N.sum(array[i]*array[i]))
if N.sum(array[i]) != 0.0 :
if norm < mini :
mini_array=array[i]
mini=norm
return mini_array
def spAvg(array):
count=0
avg=N.array([0.,0.,0.])
for i in xrange(len(array)):
if N.sum(array[i]) != 0.0 :
avg+=array[i]
count=count+1
if count !=0 : avg*=1.0/count
return avg
def spAverage(cube):
count=0
avg=N.array([0.,0.,0.])
lavg=[]
for c in cube:
for x in xrange(len(c)):
for y in xrange(len(c[0])):
for z in xrange(len(c[0][0])):
if N.sum(c[x,y,z]) != 0.0 :
avg+=c[x,y,z]
count=count+1
if count !=0 : avg*=1.0/count
lavg.append(avg.copy())
avg=N.array([0.,0.,0.])
count=0
return N.array(lavg)
def stddev(values):
sum = sum2 = 0.
n = len(values)
for value in values:
sum += value
sum2 += value*value
from math import sqrt
stddev = sqrt((n*sum2-sum*sum)/(n*(n-1)))
return stddev
# epsilon for testing whether a number is close to zero
_EPS = numpy.finfo(float).eps * 4.0
# axis sequences for Euler angles
_NEXT_AXIS = [1, 2, 0, 1]
# map axes strings to/from tuples of inner axis, parity, repetition, frame
_AXES2TUPLE = {
'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0),
'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0),
'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0),
'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0),
'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1),
'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1),
'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1),
'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)}
_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())
################################################################################
import sys,os
import glob
plateform=sys.platform
def listDir(dir):
return glob.glob(dir+"/*")
def findDirectory(dirname,where):
result=None
#print where
if dirname in os.listdir(where):
print "founded"
result=os.path.join(where,dirname)
else :
for dir in listDir(where):
if os.path.isdir(dir):
result = findDirectory(dirname,dir)
if result != None:
break
return result
```
#### File: hostappInterface/demo/pymol_like_demo.py
```python
import sys,os
#get the current software
if __name__ == "__main__":
soft = os.path.basename(sys.argv[0]).lower()
else :
soft = __name__
plugin=False
if not plugin :
#define the python path
import math
MGL_ROOT="/Library/MGLTools/1.5.6.csv/"#os.environ['MGL_ROOT']
sys.path[0]=(MGL_ROOT+'lib/python2.5/site-packages')
sys.path.append(MGL_ROOT+'lib/python2.5/site-packages/PIL')
sys.path.append(MGL_ROOT+'/MGLToolsPckgs')
#start epmv
from Pmv.hostappInterface.epmvAdaptor import epmv_start
epmv = epmv_start(soft,debug=1)
else :
#get epmv and mv (adaptor and molecular viewer)
if sotf == 'c4d':
import c4d
epmv = c4d.mv.values()[0]#[dname]
self = epmv.mv
from Pmv import hostappInterface
plgDir = hostappInterface.__path__[0]
from Pmv.hostappInterface import comput_util as util
#epmv.doCamera = False
#epmv.doLight = False
pdbname = 'pymolpept'
pdbname = '1q21'
ext = ".pdb"
demodir = plgDir+'/demo/'
demodir="/Library/MGLTools/1.5.4/MGLToolsPckgs/ARDemo/hiv/"
pdbname = '1hvr'
mext = '.dx'
demodir = "/Library/MGLTools/1.5.4/MGLToolsPckgs/ARDemo/hsg1a/"
pdbname = "hsg1"
ext=".pdbqt"
mext = '.map'
#read the molecule and store some usefull information
self.readMolecule(demodir+pdbname+ext)
mol = self.Mols[0]
mname = mol.name
sc = epmv._getCurrentScene()
masterParent = mol.geomContainer.masterGeom.obj
#MAKE THE REGULAR REPRESNETATION
self.displayLines(pdbname)
self.displaySticksAndBalls(pdbname,sticksBallsLicorice='Sticks and Balls',
cquality=0, bquality=0, cradius=0.2, only=False,
bRad=0.3, negate=False, bScale=0.0)
self.colorByAtomType(pdbname,['sticks','balls'])
self.displayCPK(pdbname)
self.colorAtomsUsingDG(pdbname,['cpk'])
self.computeMSMS(pdbname,surfName='MSMS-MOL')
#self.computeMSMS(pdbname,surfName='MSMS-MOL',pRadius=0.8)
self.colorByResidueType(pdbname,['MSMS-MOL'])
self.displayExtrudedSS(pdbname)
self.colorBySecondaryStructure(pdbname,['secondarystructure'])
#MAKE THE SPECIAL REPRESENTATION
#CMS
name='CoarseMS_'+mname
parent=masterParent
geom=epmv.coarseMolSurface(mol,[32,32,32],
isovalue=7.1,resolution=-0.3,
name=name)
mol.geomContainer.geoms[name]=geom
#force binding
#self.mv.bindGeomToMolecularFragment(g, atoms)
obj=epmv._createsNmesh(name,geom.getVertices(),None,
geom.getFaces(),smooth=True)
epmv._addObjToGeom(obj,geom)
epmv._addObjectToScene(sc,obj[0],parent=parent)
self.colorResiduesUsingShapely(pdbname, [name])
g=mol.geomContainer.geoms[name]
#if soft=='c4d':
# import c4d
# #special case for c4d wihch didnt handle the color per vertex
# #use of the graham johnson c++ plugin for color by vertex
# colors=mol.geomContainer.getGeomColor(name)
# pObject=epmv._getObject(name+"_color")
# if pObject is not None :
# sc.SetActiveObject(pObject)
# c4d.call_command(100004787) #delete the obj
# pObject=epmv._getObject(name+"_color")
# if pObject is not None :
# sc.set_active_object(pObject)
# c4d.call_command(100004787) #delete the obj
# elif hasattr(g,'color_obj') :
# pObject=g.color_obj#getObject(name+"_color")
# sc.set_active_object(pObject)
# c4d.call_command(100004787) #delete the obj
# g.color_obj = None
# pObject=epmv.helper.PolygonColorsObject(name,colors)
# g.color_obj=pObject
# epmv._addObjectToScene(sc,pObject,parent=parent)
# sc.set_active_object(obj[0])
# #call the graham J. color per vertex C++ plugin
# c4d.call_command(1023892)
#make a spline
name='spline'+mol.name
atoms = mol.allAtoms.get("CA")
atoms.sort()
obSpline,spline=epmv.helper.spline(name,atoms.coords,scene=sc,parent=masterParent)
#make a ribbon/ruban using soft loft modifier in c4d
#in order to make a ribbon we need a spline, a 2dshape to extrude
ruban = epmv._makeRibbon("ribbon"+mol.name,atoms.coords,parent=masterParent)
#Attention in Blender to render and see the spline need to extrude it
#make the armature
name='armature'+mol.name
#remember to modify c4dhelper Armature -> armature and doc->scn
armature=epmv.helper.armature(name,atoms,scn=sc,root=masterParent)
#make the metaballs
name='metaballs'+mol.name
atoms = mol.allAtoms #or a subselection of surface atoms according sas
#in maya it is just a particle system, the metaball option have to be set manually in the
#render attributes
metaballsModifyer,metaballs = epmv.helper.metaballs(name,atoms,scn=sc,root=masterParent)
#clone the cpk, make them child of the metaball object
#or do we use metaball tag ????
if soft == 'c4d':
#again a litlle trick in C4d, seems easier to just clone the cpk, and make
#them child of the metaball Objects
#clone the cpk,
mol = atoms[0].top
cpkname = mol.geomContainer.masterGeom.chains_obj[mol.chains[0].name+"_cpk"]
cpk = epmv._getObject(cpkname)
cpk_copy = cpk.GetClone()
cpk_copy.SetName("cpkMeta")
#make them child of the metaball
epmv._addObjectToScene(sc,cpk_copy,parent=metaballsModifyer)
#cpk_copy
#this can produce instability as all cpk sphere are cloned
#but share the same name
#make isocontour exple
self.readAny(demodir+pdbname+mext)
name = self.grids3D.keys()[-1]
print name
grid = self.grids3D[name]
self.cmol = mol
self.isoC.select(grid_name=name)
self.isoC(grid,name=mname+"Pos",isovalue=1.0)
self.isoC(grid,name=mname+"Neg",isovalue=-1.0)
#color it
g1 = grid.geomContainer['IsoSurf'][mname+"Pos"]
isoP = epmv._getObject(g1.obj)
g2 = grid.geomContainer['IsoSurf'][mname+"Neg"]
isoN = epmv._getObject(g2.obj)
#Attention : not done in maya
epmv.helper.changeObjColorMat(isoN,(0.,0.,1.))
epmv.helper.changeObjColorMat(isoP,(1.,0.,0.))
#MOVE THE OBJECT on a GRID 4*3
center = mol.getCenter()
radius = util.computeRadius(mol,center)
ch=mol.chains[0]
chname = ch.full_name()
if soft == 'maya' :
#in maya the caracter ':' is not allow
#moreover begining a name by a nymber is also forbidden
chname = chname.replace(":","_")
line = None
else : line = mol.geomContainer.geoms[chname+'_line'][0]
#define the geom to be translated
#problem the name with maya ? have to replace :/_
lgeom=[[],[],[]]
lgeom[0].append(epmv._getObject(mol.name+"_cloudds"))
lgeom[0].append(line)
lgeom[0].append(epmv._getObject(mol.geomContainer.masterGeom.chains_obj[ch.name+"_balls"]))
lgeom[0].append(epmv._getObject(mol.geomContainer.masterGeom.chains_obj[ch.name+"_cpk"]))
lgeom[1].append(epmv._getObject('spline'+mol.name)) #spline
lgeom[1].append(epmv._getObject('armature'+mol.name)) #bones armature
lgeom[1].append(epmv._getObject(mol.geomContainer.masterGeom.chains_obj[ch.name+"_ss"])) #cartoon
lgeom[1].append(ruban) #ribbon : simple backbone trace
msms = mol.geomContainer.geoms['MSMS-MOL'].obj
lgeom[2].append("iso") #isoContour #2geoms
lgeom[2].append(metaballs) #Metaballs
lgeom[2].append(obj[0]) #CMS
lgeom[2].append(epmv._getObject(msms)) #MSMS
print lgeom
#move it according the grid rules :
sc = 3.
x = [center[0] - (sc*radius),center[0] - (radius),center[0] + (radius),center[0] + (sc*radius)]
y = [center[1] + (sc/2*radius),center[1],center[1]-(sc/2*radius)]
z = center[2]
def position(lgeom,x,y,z,mname):
for i in range(3):
for j in range(4):
print i,j
obj = lgeom[i][j]
#print obj
if obj == "iso":
coord= [x[j],y[i],z]
g1 = grid.geomContainer['IsoSurf'][mname+"Pos"]
isoP = epmv._getObject(g1.obj)
g2 = grid.geomContainer['IsoSurf'][mname+"Neg"]
isoN = epmv._getObject(g2.obj)
epmv.helper.translateObj(isoP,coord,use_parent=False)
epmv.helper.translateObj(isoN,coord,use_parent=False)
elif obj != "" and obj != None:
coord= [x[j],y[i],z]
print obj
epmv.helper.translateObj(obj,coord,use_parent=False)
#position(lgeom,x,y,z,mname)
```
#### File: Pmv/hostappInterface/epmvAdaptor.py
```python
import sys,os
from Pmv.mvCommand import MVCommand
from Pmv.moleculeViewer import MoleculeViewer
from Pmv.moleculeViewer import DeleteGeomsEvent, AddGeomsEvent, EditGeomsEvent
from Pmv.moleculeViewer import DeleteAtomsEvent
from Pmv.displayCommands import BindGeomToMolecularFragment
from Pmv.trajectoryCommands import PlayTrajectoryCommand
from Pmv.pmvPalettes import SecondaryStructureType
from mglutil.util.recentFiles import RecentFiles
from MolKit.molecule import Atom
from MolKit.protein import Protein , Chain
import numpy
import numpy.oldnumeric as Numeric #backward compatibility
import math
from Pmv.hostappInterface import comput_util as util
from Pmv.hostappInterface.lightGridCommands import addGridCommand
from Pmv.hostappInterface.lightGridCommands import readAnyGrid
from Pmv.hostappInterface.lightGridCommands import IsocontourCommand
#TODO:
#add computation (trajectory reading,energy,imd,pyrosetta?,amber)
#check if work with server/client mode...
def epmv_start(soft,debug=0):
"""
Initialise a embeded PMV cession in the provided hostApplication.
@type soft: string
@param soft: name of the host application
@type debug: int
@param debug: debug mode, print verbose
@rtype: epmvAdaptor
@return: the embeded PMV object which consist in the adaptor, the molecular
viewer and the helper.
"""
if soft == 'blender':
from Pmv.hostappInterface.blender.blenderAdaptor import blenderAdaptor as adaptor
elif soft=='c4d':
from Pmv.hostappInterface.cinema4d.c4dAdaptor import c4dAdaptor as adaptor
elif soft=='c4dR12':
from Pmv.hostappInterface.cinema4d_dev.c4dAdaptor import c4dAdaptor as adaptor
elif soft=='maya':
from Pmv.hostappInterface.autodeskmaya.mayaAdaptor import mayaAdaptor as adaptor
elif soft == 'chimera':
from Pmv.hostappInterface.Chimera.chimeraAdaptor import chimeraAdaptor as adaptor
elif soft == 'houdini':
from Pmv.hostappInterface.houdini.houdiniAdaptor import houdiniAdaptor as adaptor
# you can add here additional soft if an adaptor and an helper is available
# use the following syntaxe, replace template by the additional hostApp
# elif soft == 'template':
# from Pmv.hostappInterface.Template.chimeraAdaptor import templateAdaptor as adaptor
#Start ePMV
return adaptor(debug=debug)
class loadMoleculeInHost(MVCommand):
"""
Command call everytime a molecule is read in PMV. Here is define whats happen
in the hostApp when a molecule is add in PMV.ie creating hierarchy, empty
parent optional pointCloud object, camera, light, etc...
"""
def __init__(self,epmv):
"""
constructor of the command.
@type epmv: epmvAdaptor
@param epmv: the embeded PMV object which consist in the adaptor, the molecular
viewer and the helper.
"""
MVCommand.__init__(self)
self.mv=epmv.mv
self.epmv = epmv
def checkDependencies(self, vf):
from bhtree import bhtreelib
def doit(self, mol, **kw):
"""
actual function of the command.
@type mol: MolKit molecule
@param mol: the molecule loaded in PMV
@type kw: dictionary
@param kw: the dictionary of optional keywords arguments
"""
chname=['Z','Y','X','W','V','U','T']
molname=mol.name#mol.replace("'","")
#setup some variable
if molname not in self.mv.molDispl.keys() :
#cpk,bs,ss,surf,cms
self.mv.molDispl[molname]=[False,False,False,False,False,None,None]
if molname not in self.mv.MolSelection.keys() :
self.mv.MolSelection[molname]={}
if molname not in self.mv.selections.keys() :
self.mv.selections[molname]={}
if molname not in self.mv.iMolData.keys() :
self.mv.iMolData[molname]=[]
sc = self.epmv._getCurrentScene()
#mol=os.path.splitext(os.path.basename(mol))[0]
#sys.stderr.write('%s\n'%molname)
if self.epmv.duplicatemol : #molecule already loaded,so the name is overwrite by pmv, add _ind
print self.epmv.duplicatedMols.keys()
if mol in self.epmv.duplicatedMols.keys() : self.epmv.duplicatedMols[molname]+=1
else : self.epmv.duplicatedMols[molname]=1
molname=molname+"_"+str(self.epmv.duplicatedMols[molname])
molname=molname.replace(".","_")
#sys.stderr.write('%s\n'%mol)
print self.mv.Mols.name
P=mol=self.mv.getMolFromName(molname)
if mol == None :
# print "WARNING RMN MODEL OR ELSE, THERE IS SERVERAL MODEL IN THE
# FILE\nWE LOAD ONLY LOAD THE 1st\n",self.Mols.name
P=mol=self.mv.getMolFromName(molname+"_model1")
mol.name=molname
#mol=mol.replace("_","")
sys.stderr.write('%s\n'%mol)
#mol.name = mol.name.replace("_","")
self.mv.buildBondsByDistance(mol,log=0)
self.mv.computeSESAndSASArea(mol,log=0)
center = mol.getCenter()
#if centering is need we will translate to center
if self.epmv.center_mol :
matrix = numpy.identity(4,'f')
matrix[3,:3] = numpy.array(center)*-1
#print matrix
vt=util.transformedCoordinatesWithMatrice(mol,matrix.transpose())
mol.allAtoms.updateCoords(vt,ind=0)
#mol.allAtoms.setConformation(0)
center = mol.getCenter()
#print center
if self.epmv.host == 'chimera':
model=self.epmv.helper.readMol(mol.parser.filename)
mol.ch_model = model
mol.geomContainer.masterGeom.obj = model
return
if self.epmv.useModeller:
print "ok add a conf"
#add a conformation for modeller
mol.allAtoms.addConformation(mol.allAtoms.coords[:])
iConf = len(mol.allAtoms[0]._coords)-1
from Pmv.hostappInterface.extension.Modeller.pmvAction import pmvAction
mol.pmvaction=pmvAction(1, 1, 1000,iconf=iConf,pmvModel=mol,mv=self.epmv)#skip,first,last
#create an empty/null object as the parent of all geom, and build the
#molecule hierarchy as empty for each Chain
master=self.epmv._newEmpty(mol.name,location=[0.,0.,0.])#center)
mol.geomContainer.masterGeom.obj=master
self.epmv._addObjectToScene(sc,master)
mol.geomContainer.masterGeom.chains_obj={}
mol.geomContainer.masterGeom.res_obj={}
if self.epmv.doCloud:
cloud = self.epmv._PointCloudObject(mol.name+"_cloud",
vertices=mol.allAtoms.coords,
parent=master)
ch_colors = self.mv.colorByChains.palette.lookup(mol.chains)
for i,ch in enumerate(mol.chains):
#how to fix this problem...?
if self.epmv.host =='maya':
if ch.name == " " or ch.name == "" :
#this dont work with stride....
ch.name = chname[i]
ch_center=[0.,0.,0.]#util.getCenter(ch.residues.atoms.coords)
chobj=self.epmv._newEmpty(ch.full_name(),location=ch_center)#,parentCenter=center)
mol.geomContainer.masterGeom.chains_obj[ch.name]=self.epmv._getObjectName(chobj)
self.epmv._addObjectToScene(sc,chobj,parent=master,centerRoot=True)
parent = chobj
#make the chain material
ch.material = self.epmv.helper.addMaterial(ch.full_name()+"_mat",ch_colors[i])
if self.epmv.doCloud:
cloud = self.epmv._PointCloudObject(ch.full_name()+"_cloud",
vertices=ch.residues.atoms.coords,
parent=chobj)
#self.epmv._addObjectToScene(sc,cloud,parent=chobj)
#if self.useTree == 'perRes' :
# for res in ch.residues :
# res_obj = util.makeResHierarchy(res,parent,useIK='+str(self.useIK)+')
# mol.geomContainer.masterGeom.res_obj[res.name]=util.getObjectName(res_obj)
#elif self.useTree == 'perAtom' :
# for res in ch.residues :
# parent = util.makeAtomHierarchy(res,parent,useIK='+str(self.useIK)+')
#else :
chobjcpk=self.epmv._newEmpty(ch.full_name()+"_cpk",location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name+"_cpk"]=self.epmv._getObjectName(chobjcpk)
self.epmv._addObjectToScene(sc,chobjcpk,parent=chobj,centerRoot=True)
chobjballs=self.epmv._newEmpty(ch.full_name()+"_bs",location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name+"_balls"]=self.epmv._getObjectName(chobjballs)
self.epmv._addObjectToScene(sc,chobjballs,parent=chobj,centerRoot=True)
chobjss=self.epmv._newEmpty(ch.full_name()+"_ss",location=ch_center)
mol.geomContainer.masterGeom.chains_obj[ch.name+"_ss"]=self.epmv._getObjectName(chobjss)
self.epmv._addObjectToScene(sc,chobjss,parent=chobj,centerRoot=True)
radius = util.computeRadius(P,center)
focal = 2. * math.atan((radius * 1.03)/100.) * (180.0 / 3.14159265358979323846)
center =center[0],center[1],(center[2]+focal*2.0)
if self.epmv.doCamera :
self.epmv._addCameraToScene("cam_"+mol.name,"ortho",focal,center,sc)
if self.epmv.doLight :
self.epmv._addLampToScene("lamp_"+mol.name,'Area',(1.,1.,1.),15.,0.8,1.5,False,center,sc)
self.epmv._addLampToScene("sun_"+mol.name,'Sun',(1.,1.,1.),15.,0.8,1.5,False,center,sc)
def onAddObjectToViewer(self, obj):
apply(self.doitWrapper, (obj,))
def __call__(self, mol, **kw):
apply(self.doitWrapper, (mol,), kw)
class epmvAdaptor:
"""
The ePMV Adaptor object
=======================
The base class for embedding pmv in a hostApplication
define the hostAppli helper function to apply according Pmv event.
Each hostApp adaptor herited from this class.
"""
keywords={"useLog":None,
"bicyl":"Split bonds",#one or two cylinder to display a bond stick
"center_mol":"Center Molecule",
"center_grid":"Center Grid",
"joins":None,
"colorProxyObject":None,
"only":None,
"updateSS":None,
"use_instances":None,
"duplicatemol":None,
"useTree":None,#None#'perRes' #or perAtom
"useIK":None,
"use_progressBar":None,
"doCloud":"Render points",
"doCamera":"PMV camera",
"doLight":"PMV light",
"useModeller":"Modeller",
"synchro_timeline":"Synchronize data player to timeline",
"synchro_ratio":["steps every","frames"],
}
def __init__(self,mv=None,host=None,useLog=False,debug=0,**kw):
"""
Constructor of the adaptor. Register the listener for PMV events and setup
defaults options. If no molecular viewer are provided, start a fresh pmv
session.
@type mv: MolecularViewer
@param mv: a previous pmv cession gui-less
@type host: string
@param host: name of the host application
@type useLog: boolean
@param useLog: use Command Log event instead of Geom event (deprecated)
@type debug: int
@param debug: debug mode, print verbose
"""
self.mv = mv
self.host = host
self.Set(reset=True,useLog=useLog,**kw)
if self.mv == None :
self.mv = self.start(debug=debug)
#define the listener
self.mv.registerListener(DeleteGeomsEvent, self.updateGeom)
self.mv.registerListener(AddGeomsEvent, self.updateGeom)
self.mv.registerListener(EditGeomsEvent, self.updateGeom)
self.mv.registerListener(DeleteAtomsEvent, self.updateModel)
#we should register to deleteAtom
#need to react to the delete atom/residues/molecule event
#need to add a command to pmv
self.mv.addCommand(loadMoleculeInHost(self),'_loadMol',None)
#self.mv.setOnAddObjectCommands(['buildBondsByDistance',
# 'displayLines',
# 'colorByAtomType',
# '_loadMol'],
# topCommand=0)
#ADT commands ? but need first to fix adt according noGUI..
self.addADTCommands()
if not hasattr(self.mv,'molDispl') : self.mv.molDispl={}
if not hasattr(self.mv,'MolSelection') : self.mv.MolSelection={}
if not hasattr(self.mv,'selections') : self.mv.selections={}
if not hasattr(self.mv,'iMolData') :self.mv.iMolData={}
#options with default values
self.duplicatedMols={}
self.env = None
self.GUI = None
def initOption(self):
"""
Initialise the defaults options for ePMV, e.g. keywords.
"""
self.useLog = False
self.bicyl = True #one or two cylinder to display a bond stick
self.center_mol = True
self.center_grid = False
self.joins=False
self.colorProxyObject=False
self.only=False
self.updateSS = False
self.use_instances=False
self.duplicatemol=False
self.useTree = 'default'#None#'perRes' #or perAtom
self.useIK = False
self.use_progressBar = False
self.doCloud = True
self.doCamera = False
self.doLight = False
self.useModeller = False
self.synchro_timeline = False #synchor the gui data-player to the host timeline
self.synchro_ratio = [1,1] #every 1 step for every 1 frame
def Set(self,reset=False,**kw):
"""
Set ePmv options provides by the keywords arguments.
e.g. epmv.Set(bicyl=True)
@type reset: bool
@param reset: reset to default values all options
@type kw: dic
@param kw: list of options and their values.
"""
if reset :
self.initOption()
val = kw.pop( 'useLog', None)
if val is not None:
self.useLog = val
val = kw.pop( 'bicyl', None)
if val is not None:
self.useLog = val
val = kw.pop( 'center_mol', None)
if val is not None:
self.useLog = val
val = kw.pop( 'center_grid', None)
if val is not None:
self.useLog = val
val = kw.pop( 'joins', None)
if val is not None:
self.useLog = val
val = kw.pop( 'colorProxyObject', None)
if val is not None:
self.useLog = val
val = kw.pop( 'only', None)
if val is not None:
self.useLog = val
val = kw.pop( 'updateSS', None)
if val is not None:
self.useLog = val
val = kw.pop( 'use_instances', None)
if val is not None:
self.useLog = val
val = kw.pop( 'duplicatemol', None)
if val is not None:
self.useLog = val
val = kw.pop( 'useTree', None)
if val is not None:
self.useLog = val
val = kw.pop( 'useIK', None)
if val is not None:
self.useLog = val
val = kw.pop( 'use_progressBar', None)
if val is not None:
self.useLog = val
val = kw.pop( 'doCloud', None)
if val is not None:
self.useLog = val
val = kw.pop( 'doCamera', None)
if val is not None:
self.useLog = val
val = kw.pop( 'doLight', None)
if val is not None:
self.useLog = val
val = kw.pop( 'useModeller', None)
if val is not None:
self.useLog = val
val = kw.pop( 'synchro_timeline', None)
if val is not None:
self.useLog = val
val = kw.pop( 'synchro_ratio', None)
if val is not None:
self.useLog = val
def start(self,debug=0):
"""
Initialise a PMV guiless session. Load specific command to PMV such as
trajectory, or grid commands which are not automatically load in the
guiless session.
@type debug: int
@param debug: debug mode, print verbose
@rtype: MolecularViewer
@return: a PMV object session.
"""
mv = MoleculeViewer(logMode = 'overwrite', customizer=None,
master=None,title='pmv', withShell= 0,
verbose=False, gui = False)
mv.addCommand(BindGeomToMolecularFragment(), 'bindGeomToMolecularFragment', None)
mv.browseCommands('trajectoryCommands',commands=['openTrajectory'],log=0,package='Pmv')
mv.addCommand(PlayTrajectoryCommand(),'playTrajectory',None)
mv.addCommand(addGridCommand(),'addGrid',None)
mv.addCommand(readAnyGrid(),'readAny',None)
mv.addCommand(IsocontourCommand(),'isoC',None)
#compatibility with PMV
mv.Grid3DReadAny = mv.readAny
#mv.browseCommands('superimposeCommandsNew', package='Pmv', topCommand=0)
mv.userpref['Read molecules as']['value']='conformations'
#recentFiles Folder
rcFile = mv.rcFolder
if rcFile:
rcFile += os.sep + 'Pmv' + os.sep + "recent.pkl"
mv.recentFiles = RecentFiles(mv, None, filePath=rcFile,index=0)
mv.embedInto(self.host,debug=debug)
#this create mv.hostapp which handle server/client and log event system
#NOTE : need to test it in the latest version
if not self.useLog :
mv.hostApp.driver.useEvent = True
mv.hostApp.driver.bicyl = self.bicyl
return mv
def addADTCommands(self):
"""
Add to PMV some usefull ADT commands, and setup the conformation player.
readDLG
showDLGstates
"""
from AutoDockTools.autoanalyzeCommands import ADGetDLG,StatesPlayerWidget,ShowAutoDockStates
# from AutoDockTools.autoanalyzeCommands import ADShowBindingSite
self.mv.addCommand(ADGetDLG(),'readDLG',None)
#self.mv.addCommand(StatesPlayerWidget(),'playerDLG',None)
self.mv.addCommand(ShowAutoDockStates(),'showDLGstates',None)
self.mv.userpref['Player GUI']={}
self.mv.userpref['Player GUI']['value']='Player'
#general util function
def createMesh(self,name,g,proxyCol=False,parent=None):
"""
General function to create mesh from DejaVu.Geom.
@type name: string
@param name: name of the host application
@type g: DejaVu.Geom
@param g: the DejaVu geometry to convert in hostApp mesh
@type proxyCol: boolean
@param proxyCol: if need special object when host didnt support color by vertex (ie C4D)
@type parent: hostApp object
@param parent: the parent for the hostApp mesh
"""
obj = self._createsNmesh(name,g.getVertices(),None,g.getFaces(),
proxyCol=proxyCol)
self._addObjToGeom(obj,g)
self._addObjectToScene(self._getCurrentScene(),obj[0],parent=parent)
def getChainParentName(self,selection,mol):
"""
Return the hostApp object masterParent at the chain level for a
given MolKit selection.
@type selection: MolKit.AtomSet
@param selection: the current selection
@type mol: MolKit.Protein
@param mol: the selection's parent molecule
@rtype: hostApp object
@return: the masterparent object at the chain level or None
"""
parent=None
if len(selection) != len(mol.allAtoms) :
chain=selection.findParentsOfType(Chain)[0]
parent = mol.geomContainer.masterGeom.chains_obj[chain.name]
parent = self._getObject(parent)
return parent
def compareSel(self,currentSel,molSelDic):
"""
Comapre the currentSel to the selection dictionary, return selname if retrieved.
@type currentSel: MolKit.AtomSet
@param currentSel: the current selection
@type molSelDic: dictionary
@param molSelDic: the dictionary of saved selection
@rtype: string
@return: the name of the selection in the dictionary if retrieved.
"""
for selname in molSelDic.keys():
if currentSel[-1] == ';' : currentSel=currentSel[0:-1]
if currentSel == molSelDic[selname][3] : return selname
if currentSel == molSelDic[selname] : return selname
return None
def getSelectionCommand(self,selection,mol):
"""
From the given currentSel and its parent molecule, return the selection name
in the selection dictionary.
@type selection: MolKit.AtomSet
@param selection: the current selection
@type mol: MolKit.Protein
@param mol: the selection's parent molecule
@rtype: string
@return: the name of the selection in the dictionary if retrieved.
"""
parent=None
if hasattr(self.mv,"selections") :
parent=self.compareSel('+selection+',self.mv.selections[mol.name])
return parent
def updateModel(self,event):
"""
This is the callback function called everytime
a PMV command affect the molecule data, ie deleteAtomSet.
@type event: VFevent
@param event: the current event, ie DeleteAtomsEvent
"""
if isinstance(event, DeleteAtomsEvent):
action='delete'
print action
#when atom are deleted we have to redo the current representation and
#selection
atom_set = event.objects
#mol = atom_set[0].getParentOfType(Protein)
#need helperFunction to delete Objects
for i,atms in enumerate(atom_set):
nameo = "S"+"_"+atms.full_name()
o=self._getObject(nameo)
if o is not None :
print nameo
self._deleteObject(o)
#and the ball/stick
nameo = "B"+"_"+atms.full_name()
o=self._getObject(nameo)
if o is not None :
print nameo
self._deleteObject(o)
#and the bonds...
#the main function, call every time an a geom event is dispatch
def updateGeom(self,event):
"""
This the main core of ePMV, this is the callback function called everytime
a PMV command affect a geometry.
@type event: VFevent
@param event: the current event, ie EditGeomsEvent
"""
if isinstance(event, AddGeomsEvent):
action='add'
elif isinstance(event, DeleteGeomsEvent):
action='delete'
elif isinstance(event, EditGeomsEvent):
action='edit'
else:
import warnings
warnings.warn('Bad event %s for epmvAdaptor.updateGeom'%event)
return
nodes,options = event.objects
if event.arg == 'iso' :
self._isoSurface(nodes,options)
return
mol, atms = self.mv.getNodesByMolecule(nodes, Atom)
#################GEOMS EVENT############################################
if event.arg == 'lines' and action =='edit' :
self._editLines(mol,atms)
elif event.arg == 'cpk' and action =='edit' and not self.useLog :
self._editCPK(mol,atms,options)
elif event.arg == 'bs' and action =='edit' and not self.useLog :
self._editBS(mol,atms,options)
elif event.arg == 'trace' and action =='edit' and not self.useLog :
print "displayTrace not supported Yet"
#displayTrace should use a linear spline extruded like _ribbon command
elif event.arg[0:4] == 'msms' and action =='edit' and not self.useLog :
#there is 2 different msms event : compute msms_c and display msms_ds
if event.arg == "msms_c" : #ok compute
self._computeMSMS(mol,atms,options)
elif event.arg == "msms_ds" : #ok display
self._displayMSMS(mol,atms,options)
elif event.arg[:2] == 'SS' and action =='edit' and not self.useLog :
if event.arg == "SSextrude":
self._SecondaryStructure(mol,atms,options,extrude=True)
if event.arg == "SSdisplay":
self._SecondaryStructure(mol,atms,options)
#################COLOR EVENT############################################
elif event.arg[0:5] == "color" : #color Commands
#in this case liste of geoms correspond to the first options
#and the type of function is the last options
self._color(mol,atms,options)
def _addMolecule(self,molname):
"""
Initialise a molecule. ie prepare the specific dictionary for this molecule.
@type molname: str
@param molname: the molecule name
"""
if molname not in self.mv.molDispl.keys() :
self.mv.molDispl[molname]=[False,False,False,False,False,None,None]
if molname not in self.mv.MolSelection.keys() :
self.mv.MolSelection[molname]={}
if molname not in self.mv.selections.keys() :
self.mv.selections[molname]={}
if molname not in self.mv.iMolData.keys() :
self.mv.iMolData[molname]=[]
def _toggleUpdateSphere(self,atms,display,needRedo,i,N,prefix):
"""
Handle the visibility and the update (pos) of each atom's Sphere geometry.
i and N arg are used for progress bar purpose.
@type atms: MolKit.Atom
@param atms: the atom to handle
@type display: boolean
@param display: visibility option
@type needRedo: boolean
@param needRedo: do we need to update
@type i: int
@param i: the atom indice
@type N: int
@param N: the total number of atoms
@type prefix: str
@param prefix: cpk or ball sphere geometry, ie "S" or "B"
"""
#TODO, fix problem with Heteratom that can have the same fullname
nameo = prefix+"_"+atms.full_name()
o=self._getObject(nameo)
if o != None :
self._toggleDisplay(o,display)
if needRedo :
self._updateSphereObj(o,atms.coords)
if self.use_progressBar and (i%20)==0 :
progress = float(i) / N
self._progressBar(progress, 'update Spheres')
def _toggleUpdateStick(self,bds,display,needRedo,i,N,molname):
"""
Handle the visibility and the update (pos) of each atom's bonds cylinder geometry.
i and N arg are used for progress bar purpose.
@type bds: MolKit.Bonds
@param bds: the bonds to handle
@type display: boolean
@param display: visibility option
@type needRedo: boolean
@param needRedo: do we need to update
@type i: int
@param i: the atom indice
@type N: int
@param N: the total number of atoms
@type molname: str
@param molname: the name of the parent molecule.
"""
atm1=bds.atom1
atm2=bds.atom2
if not self.bicyl :
c0=numpy.array(atm1.coords)
c1=numpy.array(atm2.coords)
n1=atm1.full_name().split(":")
name="T_"+molname+"_"+n1[1]+"_"+util.changeR(n1[2])+"_"+n1[3]+"_"+atm2.name
# name="T_"+atm1.name+str(atm1.number)+"_"+atm2.name+str(atm2.number)
o=self._getObject(name)
if o != None :
if needRedo :
self._updateTubeObj(o,c0,c1)
self._toggleDisplay(o,display=display)
else :
c0=numpy.array(atm1.coords)
c1=numpy.array(atm2.coords)
vect = c1 - c0
n1=atm1.full_name().split(":")
n2=atm2.full_name().split(":")
name1="T_"+molname+"_"+n1[1]+"_"+util.changeR(n1[2])+"_"+n1[3]+"_"+atm2.name
name2="T_"+molname+"_"+n2[1]+"_"+util.changeR(n2[2])+"_"+n2[3]+"_"+atm1.name
o=self._getObject(name1)
if o != None :
if needRedo :
self._updateTubeObj(o,c0,(c0+(vect/2.)))
self._toggleDisplay(o,display=display)
o=self._getObject(name2)
if o != None :
if needRedo :
self._updateTubeObj(o,(c0+(vect/2.)),c1)
self._toggleDisplay(o,display=display)
if self.use_progressBar and (i%20)==0 :
progress = float(i) / N
self._progressBar(progress, 'update sticks')
def _editCPK(self,mol,atms,opts):
"""
Callback for displayCPK commands. Create and update the cpk geometries
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type opts: list
@param opts: the list of option used for the command (only, negate, scaleFactor,
cpkRad, quality, byproperty, propertyName, propertyLevel, redraw)
"""
sc = self._getCurrentScene()
display = not opts[1]
needRedo = opts[8]
# print "redo",needRedo
options=self.mv.displayCPK.lastUsedValues["default"]
if options.has_key("redraw"): needRedo = options["redraw"]
# print "redo",needRedo
##NB do we want to handle multiple mol at once?
mol = mol[0]
g = mol.geomContainer.geoms['cpk']
root = mol.geomContainer.masterGeom.obj
chobj = mol.geomContainer.masterGeom.chains_obj
sel = atms[0]
if not hasattr(g,"obj") and display:
name=mol.name+"_cpk"
mesh=self._createBaseSphere(name=mol.name+"_b_cpk",quality=opts[4],cpkRad=opts[3],
scale=opts[2],parent=root)
ob=self._instancesAtomsSphere(name,mol.allAtoms,mesh,sc,scale=opts[2],
R=opts[3],Res=opts[4],join=self.joins,
geom=g,pb=self.use_progressBar)
self._addObjToGeom([ob,mesh],g)
# for i,o in enumerate(ob):
# parent=root
# hierarchy=self._parseObjectName(o)
# if hierarchy != "" :
# if self.useTree == 'perRes' :
# parent = self._getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
# elif self.useTree == 'perAtom' :
# parent = self._getObject(o.get_name().split("_")[1])
# else :
# parent = self._getObject(chobj[hierarchy[1]+"_cpk"])
# self._addObjectToScene(sc,o,parent=parent)
# #self._toggleDisplay(o,False)
# if self.use_progressBar :
# progress = float(i) / len(ob)
# self._progressBar(progress, 'add CPK to scene')
#elif hasattr(g,"obj") and needRedo :
# self._updateSphereObjs(g)
if hasattr(g,"obj"):
self._updateSphereMesh(g,quality=opts[4],cpkRad=opts[3],scale=opts[2])
atoms=sel
if self.use_progressBar : self._resetProgressBar(len(atoms))
#can we reaplce the map/lambda by [[]]?
[self._toggleUpdateSphere(x[1],display,needRedo,x[0],
len(atoms),"S") for x in enumerate(atoms)]
# map(lambda x,display=display,needRedo=needRedo,N=len(atoms):
# self._toggleUpdateSphere(x[1],display,needRedo,x[0],N,"S"),
# enumerate(atoms))
def _editBS(self,mol,atms,opts):
"""
Callback for displayStickandBalls commands. Create and update the sticks
and balls geometries
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type opts: list
@param opts: the list of option used for the command (only, negate, bRad,
bScale, bquality, cradius, cquality, sticksBallsLicorice, redraw)
"""
sc = self._getCurrentScene()
display = not opts[1]
needRedo = opts[-1]
options=self.mv.displaySticksAndBalls.lastUsedValues["default"]
if options.has_key("redraw"): needRedo = options["redraw"]
#NB do we want to handle multiple mol at once?
mol = mol[0]
root = mol.geomContainer.masterGeom.obj
chobj = mol.geomContainer.masterGeom.chains_obj
sel=atms[0]
#if not hasattr(g,"obj") and display:
gb = mol.geomContainer.geoms['balls']
gs = mol.geomContainer.geoms['sticks']
if not hasattr(gb,"obj") and not hasattr(gs,"obj") :
mol.allAtoms.ballRad = opts[2]
mol.allAtoms.ballScale = opts[3]
mol.allAtoms.cRad = opts[5]
for atm in mol.allAtoms:
atm.colors['sticks'] = (1.0, 1.0, 1.0)
atm.opacities['sticks'] = 1.0
atm.colors['balls'] = (1.0, 1.0, 1.0)
atm.opacities['balls'] = 1.0
if opts[7] !='Sticks only' : #no balls
if not hasattr(gb,"obj") and display:
mesh=self._createBaseSphere(name=mol.name+"_b_balls",quality=opts[4],
cpkRad=opts[2],scale=opts[3],
radius=opts[2],parent=root)
ob=self._instancesAtomsSphere("base_balls",mol.allAtoms,mesh,sc,
scale=opts[3],R=opts[2],
join=self.joins,geom=gb,
pb=self.use_progressBar)
self._addObjToGeom([ob,mesh],gb)
"""for i,o in enumerate(ob):
parent=root
hierarchy=self._parseObjectName(o)
if hierarchy != "" :
if self.useTree == 'perRes' :
parent = self._getObject(mol.geomContainer.masterGeom.res_obj[hierarchy[2]])
elif self.useTree == 'perAtom' :
parent = self._getObject(o.get_name().split("_")[1])
else :
parent = self._getObject(chobj[hierarchy[1]+"_balls"])
#self._addObjectToScene(sc,o,parent=parent)
#self._toggleDisplay(o,False) #True per default
if self.use_progressBar :
progress = float(i) / len(ob)
self._progressBar(progress, 'add Balls to scene')
"""
if not hasattr(gs,"obj") and display:
set = mol.geomContainer.atoms["sticks"]
stick=self._Tube(set,sel,gs.getVertices(),gs.getFaces(),sc, None,
res=15, size=opts[5], sc=1.,join=0,bicyl=self.bicyl,
hiera =self.useTree,pb=self.use_progressBar)
self._addObjToGeom(stick,gs)
#adjust the size
#self._updateTubeMesh(gs,cradius=opts[5],quality=opts[6])
#toggleds off while create it
#for o in stick[0]:
# self._toggleDisplay(o,False)
#else:
if hasattr(gb,"obj"):
#if needRedo :
self._updateSphereMesh(gb,quality=opts[4],cpkRad=opts[2],
scale=opts[3],radius=opts[2])
atoms=sel
if self.use_progressBar : self._resetProgressBar(len(atoms))
if opts[7] =='Sticks only' :
display = False
else : display = display
[self._toggleUpdateSphere(x[1],display, needRedo,x[0],
len(atoms),"B") for x in enumerate(atoms)]
# map(lambda x,display=display,needRedo=needRedo,N=len(atoms):
# self._toggleUpdateSphere(x[1],display,needRedo,x[0],N,"B"),
# enumerate(atoms))
if hasattr(gs,"obj"):
#first update geom
self._updateTubeMesh(gs,cradius=opts[5],quality=opts[6])
atoms=sel
#set = mol.geomContainer.atoms["sticks"]
bonds, atnobnd = atoms.bonds
#print len(atoms)
#for o in gs.obj:util.toggleDisplay(o,display=False)
if len(atoms) > 0 :
if self.use_progressBar : self._resetProgressBar(len(bonds))
[self._toggleUpdateStick(x[1],display,needRedo,x[0],len(bonds),
mol.name) for x in enumerate(bonds)]
# map(lambda x,display=display,needRedo=needRedo,N=len(bonds),molname=mol.name:
# self._toggleUpdateStick(x[1],display,needRedo,x[0],N,molname),
# enumerate(bonds))
def _SecondaryStructure(self,mol,atms,options,extrude=False):
"""
Callback for display/extrudeSecondaryStructrure commands. Create and update
the mesh polygons for representing the secondary structure
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type options: list
@param options: the list of option used for the command (only, negate, bRad,
bScale, bquality, cradius, cquality, sticksBallsLicorice, redraw)
@type extrude: boolean
@param extrude: type of command : extrude or display
"""
proxy = self.colorProxyObject
self.colorProxyObject = False
sc = self._getCurrentScene()
mol = mol[0]
root = mol.geomContainer.masterGeom.obj
chobj = mol.geomContainer.masterGeom.chains_obj
display = not options[1]
i=0
if extrude :display = options[9]
for name,g in mol.geomContainer.geoms.items():
if name[:4] in ['Heli', 'Shee', 'Coil', 'Turn', 'Stra']:
print name
#problem with name renaming of chain
fullname=mol.name+":"+name[-1]+":"+name[:-1]
if not hasattr(g,"obj") and display :#and fullname in self.mv.sets.keys():
parent=self._getObject(chobj[name[-1]+"_ss"])
self.createMesh(mol.name+"_"+name,g,parent=parent)
elif hasattr(g,"obj") :
#if extrude :
parent = self._getObject(chobj[name[-1]+"_ss"])
self._updateMesh(g,parent=parent)
self._toggleDisplay(g.obj,display)
if self.use_progressBar and (i%20)==0 :
progress = float(i) / 100#len(self.mv.sets.keys())
self._progressBar(progress, 'add SS to scene')
i+=1
self.colorProxyObject = proxy
def _computeMSMS(self, mol,atms,options):
"""
Callback for computation of MSMS surface. Create and update
the mesh polygons for representing the MSMS surface
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type options: list
@param options: the list of option used for the command; options order :
surfName, pRadius, density,perMol, display, hdset, hdensity
"""
name=options[0]
mol = mol[0]
root = mol.geomContainer.masterGeom.obj
#chobj = mol.geomContainer.masterGeom.chains_obj
sel=atms[0]
parent=self.getChainParentName(sel,mol)
if parent == None : parent=root
g = mol.geomContainer.geoms[name]
if not hasattr(g,"mol"):
g.mol = mol
if hasattr(g,"obj") :
self._updateMesh(g,parent=parent,proxyCol=self.colorProxyObject,mol=mol)
else :
self.createMesh(name,g,parent=parent,proxyCol=self.colorProxyObject)
if options[4] :
self._toggleDisplay(g.obj,display=options[4])
def _displayMSMS(self, mol,atms,options):
"""
Callback for displayMSMS commands. display/undisplay
the mesh polygons representing the MSMS surface
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type options: list
@param options: the list of option used for the command; options order :
surfName, pRadius, density,perMol, display, hdset, hdensity
"""
#options order : surfName(names), negate, only, nbVert
#this function only toggle the display of the MSMS polygon
name=options[0][0] #surfName(names) is a list...
display = not options[1]
g = mol[0].geomContainer.geoms[name]
if hasattr(g,"obj") :
self._toggleDisplay(g.obj,display=display)
def _colorStick(self,bds,i,atoms,N,fType,p,mol):
"""
Handle the coloring of one bonds stick geometry.
i and N arg are used for progress bar purpose.
@type bds: MolKit.Bonds
@param bds: the bonds to color
@type i: int
@param i: the bond indice
@type atoms: MolKit.AtomSet
@param atoms: the list of atoms
@type N: int
@param N: the total number of bonds
@type fType: str
@param fType: the colorCommand type
@type p: Object
@param p: the parent object
@type mol: MolKit.Protein
@param mol: the molecule parent
"""
atm1=bds.atom1
atm2=bds.atom2
if atm1 in atoms or atm2 in atoms :
vcolors=[atm1.colors["sticks"],atm2.colors["sticks"]]
if not self.bicyl :
n1=atm1.full_name().split(":")
name="T_"+mol.name+"_"+n1[1]+"_"+util.changeR(n1[2])+"_"+n1[3]+"_"+atm2.name
# name="T_"+atm1.name+str(atm1.number)+"_"+atm2.name+str(atm2.number)
o=self._getObject(name)
if o != None :
self._checkChangeMaterial(o,fType,
atom=atm1,parent=p,color=vcolors[0])
else :
n1=atm1.full_name().split(":")
n2=atm2.full_name().split(":")
name1="T_"+mol.name+"_"+n1[1]+"_"+util.changeR(n1[2])+"_"+n1[3]+"_"+atm2.name
name2="T_"+mol.name+"_"+n2[1]+"_"+util.changeR(n2[2])+"_"+n2[3]+"_"+atm1.name
o=self._getObject(name1)
if o != None :
self._checkChangeMaterial(o,fType,
atom=atm1,parent=p,color=vcolors[0])
o=self._getObject(name2)
if o != None :
self._checkChangeMaterial(o,fType,
atom=atm2,parent=p,color=vcolors[1])
if self.use_progressBar and (i%20)==0:
progress = float(i) / N
self._progressBar(progress, 'color Sticks')
def _colorSphere(self,atm,i,sel,prefix,p,fType,geom):
"""
Handle the coloring of one atom sphere geometry.
i and N arg are used for progress bar purpose.
@type atm: MolKit.Atom
@param atm: the atom to color
@type i: int
@param i: the atom indice
@type sel: MolKit.AtomSet
@param sel: the list of atoms
@type prefix: str
@param prefix: cpk or ball sphere geometry, ie "S" or "B"
@type p: Object
@param p: the parent object
@type fType: str
@param fType: the colorCommand type
@type geom: str
@param geom: the parent geometry ie cpk or balls
"""
name = prefix+"_"+atm.full_name()
o=self._getObject(name)
vcolors = [atm.colors[geom],]
if o != None :
self._checkChangeMaterial(o,fType,atom=atm,parent=p,color=vcolors[0])
if self.use_progressBar and (i%20)==0 :
progress = float(i) / len(sel)
self._progressBar(progress, 'color Spheres')
def _color(self,mol,atms,options):
"""
General Callback function reacting to any colorX commands. Call according
function to change/update the object color.
Note: should be optimized...
@type mol: MolKit.Protein
@param mol: the molecule affected by the command
@type atms: MolKit.AtomSet
@param atms: the atom selection
@type options: list
@param options: the list of option used for the command
"""
#color the list of geoms (options[0]) according the function (options[-1])
lGeoms = options[0]
fType = options[-1]
mol = mol[0] #TO FIX
sel=atms[0]
for geom in lGeoms :
if geom=="secondarystructure" :
#TOFIX the color/res not working...
#gss = mol.geomContainer.geoms["secondarystructure"]
for name,g in mol.geomContainer.geoms.items() :
if name[:4] in ['Heli', 'Shee', 'Coil', 'Turn', 'Stra']:
SS= g.SS
name='%s%s'%(SS.name, SS.chain.id)
#print name
colors=mol.geomContainer.getGeomColor(name)
if colors is None :
#get the regular color for this SS if none is get
colors = [SecondaryStructureType[SS.structureType],]
flag=mol.geomContainer.geoms[name].vertexArrayFlag
if hasattr(g,"obj"):
self._changeColor(g,colors,perVertex=flag)
elif geom=="cpk" or geom=="balls":
#have instance materials...so if colorbyResidue have to switch to residueMaterial
parent = self.getSelectionCommand(sel,mol)
g = mol.geomContainer.geoms[geom]
colors=mol.geomContainer.getGeomColor(geom)
#or do we use the options[1] which should be the colors ?
prefix="S"
name="cpk"
if geom == "balls" :
prefix="B"
name="bs"#"balls&sticks"
if len(sel) == len(mol.allAtoms) :
p = mol.name+"_"+name
else :
p = parent
if hasattr(g,"obj"):
[self._colorSphere(x[1],x[0],sel,
prefix,p,fType,geom) for x in enumerate(sel)]
# map(lambda x,sel=sel,prefix=prefix,p=p,fType=fType,geom=geom:
# self._colorSphere(x[1],x[0],sel,prefix,p,fType,geom),
# enumerate(sel))
elif geom =="sticks" :
g = mol.geomContainer.geoms[geom]
colors = mol.geomContainer.getGeomColor(geom)
parent = self.getSelectionCommand(sel,mol)
if hasattr(g,"obj"):
atoms=sel
set = mol.geomContainer.atoms["sticks"]
if len(set) == len(mol.allAtoms) : p = mol.name+"_cpk"
else : p = parent
bonds, atnobnd = set.bonds
if len(set) != 0 :
[self._colorStick(x[1],x[0],atoms,len(bonds),fType,p,mol) for x in enumerate(bonds)]
# map(lambda x,atoms=atoms,p=p,fType=fType,mol=mol,bonds=bonds:
# self._colorStick(x[1],x[0],atoms,bonds,fType,p,mol),
# enumerate(bonds))
else :
g = mol.geomContainer.geoms[geom]
colors=mol.geomContainer.getGeomColor(geom)
flag=g.vertexArrayFlag
if hasattr(g,"obj"):
if self.soft=="c4d" :
self._changeColor(g,colors,perVertex=flag,
proxyObject=self.colorProxyObject,
pb=self.use_progressBar)
elif self.soft =="c4dr12":
self._changeColor(g,colors,perVertex=flag,
proxyObject=True,
pb=self.use_progressBar)
else :
self._changeColor(g,colors,perVertex=flag,
pb=self.use_progressBar)
def _isoSurface(self,grid,options):
"""
Callback for computing isosurface of grid volume data. will create and update
the mesh showing the isosurface at a certain isovalue.
@type grid: Volume.Grid3D
@param grid: the current grid volume data
@type options: list
@param options: the list of option used for the command; ie isovalue, size...
"""
if len(options) ==0:
name=grid.name
g = grid.srf
else :
name = options[0]
g = grid.geomContainer['IsoSurf'][name]
print name, g
root = None
if hasattr(self.mv,'cmol') and self.mv.cmol != None:
mol = self.mv.cmol
root = mol.geomContainer.masterGeom.obj
else :
if hasattr(grid.master_geom,"obj"):
root = grid.master_geom.obj
else :
root = self._newEmpty(grid.master_geom.name)
self._addObjectToScene(self._getCurrentScene(),root)
self._addObjToGeom(root,grid.master_geom)
if hasattr(g,"obj") : #already computed so need update
sys.stderr.write("UPDATE MESH")
self._updateMesh(g,parent=root)
else :
self.createMesh(name,g,proxyCol=False,parent=root)
def coarseMolSurface(self,molFrag,XYZd,isovalue=7.0,resolution=-0.3,padding=0.0,
name='CoarseMolSurface',geom=None):
"""
Function adapted from the Vision network which compute a coarse molecular
surface in PMV
@type molFrag: MolKit.AtomSet
@param molFrag: the atoms selection
@type XYZd: array
@param XYZd: shape of the volume
@type isovalue: float
@param isovalue: isovalue for the isosurface computation
@type resolution: float
@param resolution: resolution of the final mesh
@type padding: float
@param padding: the padding
@type name: string
@param name: the name of the resultante geometry
@type geom: DejaVu.Geom
@param geom: update geom instead of creating a new one
@rtype: DejaVu.Geom
@return: the created or updated DejaVu.Geom
"""
self.mv.assignAtomsRadii(molFrag.top, united=1, log=0, overwrite=0)
from MolKit.molecule import Atom
atoms = molFrag.findType(Atom)
coords = atoms.coords
radii = atoms.vdwRadius
#self.assignAtomsRadii("1xi4g", united=1, log=0, overwrite=0)
from UTpackages.UTblur import blur
import numpy.oldnumeric as Numeric
volarr, origin, span = blur.generateBlurmap(coords, radii, XYZd,resolution, padding = 0.0)
volarr.shape = (XYZd[0],XYZd[1],XYZd[2])
volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f')
#print volarr
weights = Numeric.ones(len(radii), typecode = "f")
h = {}
from Volume.Grid3D import Grid3DF
maskGrid = Grid3DF( volarr, origin, span , h)
h['amin'], h['amax'],h['amean'],h['arms']= maskGrid.stats()
#(self, grid3D, isovalue=None, calculatesignatures=None, verbosity=None)
from UTpackages.UTisocontour import isocontour
isocontour.setVerboseLevel(0)
data = maskGrid.data
origin = Numeric.array(maskGrid.origin).astype('f')
stepsize = Numeric.array(maskGrid.stepSize).astype('f')
# add 1 dimension for time steps amd 1 for multiple variables
if data.dtype.char!=Numeric.Float32:
#print 'converting from ', data.dtype.char
data = data.astype('f')#Numeric.Float32)
newgrid3D = Numeric.ascontiguousarray(Numeric.reshape( Numeric.transpose(data),
(1, 1)+tuple(data.shape) ), data.dtype.char)
ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize)
isoc = isocontour.getContour3d(ndata, 0, 0, isovalue,
isocontour.NO_COLOR_VARIABLE)
vert = Numeric.zeros((isoc.nvert,3)).astype('f')
norm = Numeric.zeros((isoc.nvert,3)).astype('f')
col = Numeric.zeros((isoc.nvert)).astype('f')
tri = Numeric.zeros((isoc.ntri,3)).astype('i')
isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)
#print vert
if maskGrid.crystal:
vert = maskGrid.crystal.toCartesian(vert)
#from DejaVu.IndexedGeom import IndexedGeom
from DejaVu.IndexedPolygons import IndexedPolygons
if geom == None :
g=IndexedPolygons(name=name)
else :
g = geom
#print g
inheritMaterial = None
g.Set(vertices=vert, faces=tri, materials=None,
tagModified=False,
vnormals=norm, inheritMaterial=inheritMaterial )
#shouldnt this only for the selection set ?
g.mol = molFrag.top
for a in atoms:#g.mol.allAtoms:
a.colors[g.name] = (1.,1.,1.)
a.opacities[g.name] = 1.0
self.mv.bindGeomToMolecularFragment(g, atoms)
#print len(g.getVertices())
return g
def getCitations(self):
citation=""
for module in self.mv.showCitation.citations:
citation +=self.mv.showCitation.citations[module]
return citation
def testNumberOfAtoms(self,mol):
nAtoms = len(mol.allAtoms)
if nAtoms > 5000 :
mol.doCPK = False
else :
mol.doCPK = True
#def piecewiseLinearInterpOnIsovalue(x):
# """Piecewise linear interpretation on isovalue that is a function
# blobbyness.
# """
# import sys
# X = [-3.0, -2.5, -2.0, -1.5, -1.3, -1.1, -0.9, -0.7, -0.5, -0.3, -0.1]
# Y = [0.6565, 0.8000, 1.0018, 1.3345, 1.5703, 1.8554, 2.2705, 2.9382, 4.1485, 7.1852, 26.5335]
# if x<X[0] or x>X[-1]:
# print "WARNING: Fast approximation :blobbyness is out of range [-3.0, -0.1]"
# return None
# i = 0
# while x > X[i]:
# i +=1
# x1 = X[i-1]
# x2 = X[i]
# dx = x2-x1
# y1 = Y[i-1]
# y2 = Y[i]
# dy = y2-y1
# return y1 + ((x-x1)/dx)*dy
#####EXTENSIONS FUNCTION
def showMolPose(self,mol,pose,conf):
"""
Show pyrosetta pose object which is a the result conformation of a
simulation
@type mol: MolKit.Protein
@param mol: the molecule node to apply the pose
@type pose: rosetta.Pose
@param pose: the new pose from PyRosetta
@type conf: int
@param conf: the indice for storing the pose in the molecule conformational stack
"""
from Pmv.moleculeViewer import EditAtomsEvent
pmv_state = conf
import time
if type(mol) is str:
model = self.getMolFromName(mol.name)
else :
model = mol
model.allAtoms.setConformation(conf)
coord = {}
print pose.n_residue(),len(model.chains.residues)
for resi in range(1, pose.n_residue()+1):
res = pose.residue(resi)
resn = pose.pdb_info().number(resi)
#print resi,res.natoms(),len(model.chains.residues[resi-1].atoms)
k=0
for atomi in range(1, res.natoms()+1):
name = res.atom_name(atomi).strip()
if name != 'NV' :
a=model.chains.residues[resi-1].atoms[k]
pmv_name=a.name
k = k + 1
if name != pmv_name :
if name[1:] != pmv_name[:-1]:
print name,pmv_name
else :
coord[(resn, pmv_name)] = res.atom(atomi).xyz()
cood=res.atom(atomi).xyz()
a._coords[conf]=[cood.x,cood.y,cood.z]
else :
coord[(resn, name)] = res.atom(atomi).xyz()
cood=res.atom(atomi).xyz()
a._coords[conf]=[cood.x,cood.y,cood.z] #return coord
model.allAtoms.setConformation(conf)
event = EditAtomsEvent('coords', model.allAtoms)
self.dispatchEvent(event)
#epmv.insertKeys(model.geomContainer.geoms['cpk'],1)
self.helper.update()
def updateDataGeom(self,mol):
"""
Callback for updating special geometry that are not PMV generated and which
do not react to editAtom event. e.g. pointCloud or Spline
@type mol: MolKit.Protein
@param mol: the parent molecule
"""
mname = mol.name
for c in mol.chains :
self.helper.update_spline(mol.name+"_"+c.name+"spline",c.residues.atoms.get("CA").coords)
if self.doCloud :
self.helper.updatePoly(mol.name+":"+c.name+"_cloud",vertices=c.residues.atoms.coords)
#look if there is a msms:
# #find a way to update MSMS and coarse
# if self.mv.molDispl[mname][3] : self.gui.updateSurf()
# if self.mv.molDispl[mname][4] : self.gui.updateCoarseMS()
def updateData(self,traj,step):
"""
Callback for updating molecule data following the data-player.
DataType can be : MD trajectory, Model Data (NMR, DLG, ...)
@type traj: array
@param traj: the current trajectory object. ie [trajData,trajType]
@type step: int or float
@param step: the new value to apply
"""
if traj[0] is not None :
if traj[1] == 'traj':
mol = traj[0].player.mol
maxi=len(traj[0].coords)
mname = mol.name
if step < maxi :
traj[0].player.applyState(int(step))
self.updateDataGeom(mol)
elif traj[1] == "model":
mname = traj[0].split(".")[0]
type = traj[0].split(".")[1]
mol = self.mv.getMolFromName(mname)
if type == 'model':
nmodels=len(mol.allAtoms[0]._coords)
if step < nmodels:
mol.allAtoms.setConformation(step)
#self.mv.computeSecondaryStructure(mol.name,molModes={mol.name:'From Pross'})
from Pmv.moleculeViewer import EditAtomsEvent
event = EditAtomsEvent('coords', mol.allAtoms)
self.mv.dispatchEvent(event)
self.updateDataGeom(mol)
else :
nmodels=len(mol.docking.ch.conformations)
if step < nmodels:
mol.spw.applyState(step)
self.updateDataGeom(mol)
def updateTraj(self,traj):
"""
Callback for updating mini,maxi,default,step values needed by the data player
DataType can be : MD trajectory, Model Data (NMR, DLG, ...)
@type traj: array
@param traj: the current trajectory object. ie [trajData,trajType]
"""
if traj[1] == "model":
mname = traj[0].split(".")[0]
type = traj[0].split(".")[1]
mol = self.mv.getMolFromName(mname)
if type == 'model':
nmodels=len(mol.allAtoms[0]._coords)
else :
nmodels=len(mol.docking.ch.conformations)
mini=0
maxi=nmodels
default=0
step=1
elif type == "traj":
mini=0
maxi=len(traj[0].coords)
default=0
step=1
elif type == "grid":
mini=traj[0].mini
maxi=traj[0].maxi
default=traj[0].mean
step=0.01
return mini,maxi,default,step
def renderDynamic(self,traj,timeWidget=False,timeLapse=5):
"""
Callback for render a full MD trajectory.
@type traj: array
@param traj: the current trajectory object. ie [trajData,trajType]
@type timeWidget: boolean
@param timeWidget: use the timer Widget to cancel the rendering
@type timeLapse: int
@param timeLapse: the timerWidget popup every timeLapse
"""
if timeWidget:
dial= self.helper.TimerDialog()
dial.cutoff = 15.0
if traj[0] is not None :
if traj[1] == 'traj':
mol = traj[0].player.mol
maxi=len(traj[0].coords)
mname = mol.name
for i in range(maxi):
if timeWidget and (i % timeLapse) == 0 :
dial.open()
if dial._cancel :
return False
traj[0].player.applyState(i)
self.updateDataGeom(mol)
if self.mv.molDispl[mname][3] : self.gui.updateSurf()
if self.mv.molDispl[mname][4] : self.gui.updateCoarseMS()
self.helper.update()
self._render("md%.4d" % i,640,480)
elif traj[1] == 'model':
mname = traj[0].split(".")[0]
type = traj[0].split(".")[1]
mol = self.mv.getMolFromName(mname)
if type == 'model':
maxi=len(mol.allAtoms[0]._coords)
for i in range(maxi):
mol.allAtoms.setConformation(step)
#self.mv.computeSecondaryStructure(mol.name,molModes={mol.name:'From Pross'})
from Pmv.moleculeViewer import EditAtomsEvent
event = EditAtomsEvent('coords', mol.allAtoms)
self.mv.dispatchEvent(event)
self.updateDataGeom(mol)
if self.mv.molDispl[mname][3] : self.gui.updateSurf()
if self.mv.molDispl[mname][4] : self.gui.updateCoarseMS()
self.helper.update()
self._render("model%.4d" % i,640,480)
def APBS(self):
""" DEPRECATED AND NOT USE """
#need the pqrfile
#then can compute
self.mv.APBSSetup.molecule1Select(molname)
self.mv.APBSSetup({'solventRadius':1.4,'ions':[],'surfaceCalculation':
'Cubic B-spline',
'pdb2pqr_Path':'/Library/MGLTools/1.5.6.up/MGLToolsPckgs/MolKit/pdb2pqr/pdb2pqr.py',
'xShiftedDielectricFile':'',
'proteinDielectric':2.0,
'projectFolder':'apbs-project',
'zShiftedDielectricFile':'',
'complexPath':'','splineBasedAccessibilityFile':'',
'chargeDiscretization':'Cubic B-spline',
'ionAccessibilityFile':'','gridPointsY':65,
'chargeDistributionFile':'','ionChargeDensityFile':'',
'pdb2pqr_ForceField':'amber','energyDensityFile':'',
'fineCenterZ':22.6725,'forceOutput':'','fineCenterX':10.0905,
'fineCenterY':52.523,'potentialFile':'OpenDX','splineWindow':0.3,
'yShiftedDielectricFile':'','VDWAccessibilityFile':'',
'gridPointsX':65,'molecule1Path':'/Users/ludo/1M52mono.pqr',
'sdens':10.0,'coarseLengthY':73.744,
'boundaryConditions':'Single Debye-Huckel',
'calculationType':'Electrostatic potential',
'fineLengthZ':73.429,'fineLengthY':52.496,
'fineLengthX':68.973,'laplacianOfPotentialFile':'',
'saltConcentration':0.01,'pbeType':'Linearized','coarseCenterX':10.0905,
'coarseCenterZ':22.6725,'ionNumberFile':'','coarseCenterY':52.523,
'name':'Default','solventDielectric':78.54,'solventAccessibilityFile':'',
'APBS_Path':'/Library/MGLTools/1.5.6.up/MGLToolsPckgs/binaries/apbs',
'molecule2Path':'','coarseLengthX':98.4595,'kappaFunctionFile':'',
'coarseLengthZ':105.1435,'systemTemperature':298.15,'gridPointsZ':65,
'energyOutput':'Total'}, log=0)
#then run
self.mv.APBSRun('1M52mono', None, None, APBSParamName='Default',
blocking=False, log=0)
#then read the dx grid
self.Grid3DReadAny('/Library/MGLTools/1.5.6.up/bin/apbs-1M52mono/1M52mono.potential.dx',
normalize=False, log=0, show=False)
#self.APBSMapPotential2MSMS(potential='/Library/MGLTools/1.5.6.up/bin/apbs-1M52mono/1M52mono.potential.dx', log=0, mol='1M52mono')
def APBS2MSMS(self,grid,surf=None,offset=1.0,stddevM=5.0):
"""
Map a surface mesh using grid (APBS,AD,...) values projection.
This code is based on the Pmv vision node network which color a MSMS using a APBS computation.
@type grid: grids3D
@param grid: the grid to project
@type surf: DejaVu.Geom or hostApp mesh
@param surf: the surface mesh to color
@type offset: float
@param offset: the offset to apply to the vertex normal used for the projection
@type stddevM: float
@param stddevM: scale factor for the standard deviation fo the grid data values
"""
v, f,vn,fn =self.getSurfaceVFN(surf)
if v is None : return
points = v+(vn*offset)
data = self.TriInterp(grid,points)
#need to apply some stddev on data
datadev = util.stddev(data)*stddevM
#need to make a colorMap from this data
#colorMap should be the rgbColorMap
from Pmv import hostappInterface
cmap = hostappInterface.__path__[0]+"/apbs_map.py"
lcol = self.colorMap(colormap='rgb256',mini=-datadev,
maxi=datadev,values=data,filename=cmap)
if self.soft=="c4d" :
self._changeColor(surf,lcol,proxyObject=self.colorProxyObject)
elif self.soft =="c4dr12":
self._changeColor(surf,lcol,proxyObject=True)
else :
self._changeColor(surf,lcol)
def getSurfaceVFN(self,geometry):
"""
Extract vertices, faces and normals from either an DejaVu.Geom
or a hostApp polygon mesh
@type geometry: DejaVu.Geom or hostApp polygon
@param geometry: the mesh to decompose
@rtype: list
@return: faces,vertices,vnormals of the geometry
"""
if geometry:
if not hasattr(geometry,'asIndexedPolygons'):
f=None
v=None
vn=None
f,v,vn = self.helper.DecomposeMesh(geometry,edit=False,
copy=False,tri=False,
transform=False)
fn=None
else :
geom = geometry.asIndexedPolygons()
v = geom.getVertices()
vn = geom.getVNormals()
fn = geom.getFNormals()
f = geom.getFaces()
return Numeric.array(v), f,Numeric.array(vn),fn
def TriInterp(self,grid,points):
"""
Trilinear interpolation of a list of point in the given grid.
@type grid: grid3D
@param grid: the grid object
@type points: numpy.array
@param points: list of point to interpolate in the grid
@rtype: list
@return: the interpolated value for the given list of point
"""
values = []
import numpy.oldnumeric as N
from Volume.Operators.trilinterp import trilinterp
origin = N.array(grid.origin, Numeric.Float32)
stepSize = N.array(grid.stepSize, Numeric.Float32)
invstep = ( 1./stepSize[0], 1./stepSize[1], 1./stepSize[2] )
if grid.crystal:
points = grid.crystal.toFractional(points)
values = trilinterp(points, grid.data, invstep, origin)
return values
def colorMap(self, colormap='rgb256', values=None, mini=None, maxi=None,filename=None):
"""
Prepare and setup a DejaVu.colorMap using the given options
@type colormap: str
@param colormap: name of existing colormap
@type values: list
@param values: list of color for the colormap
@type mini: float
@param mini: minimum value for the ramp
@type maxi: float
@param maxi: maximum value for the ramp
@type filename: str
@param filename: colormap filename
@rtype: DejaVu.colorMap
@return: the prepared color map
"""
from DejaVu.colorMap import ColorMap
import types
if colormap is None:
pass#colormap = RGBARamp
elif type(colormap) is types.StringType \
and self.mv.colorMaps.has_key(colormap):
colormap = self.mv.colorMaps[colormap]
if not isinstance(colormap, ColorMap):
return 'ERROR'
if values is not None and len(values)>0:
if mini is None:
mini = min(values)
if maxi is None:
maxi = max(values)
colormap.configure(mini=mini, maxi=maxi)
if filename :
colormap.read(filename)
colormap.configure(mini=mini, maxi=maxi)
if (values is not None) and (len(values) > 0) :
lCol = colormap.Map(values)
if lCol is not None:
return lCol.tolist()
elif len(colormap.ramp) == 1:
return colormap.ramp[0]
else:
return colormap.ramp
def setEnvPyRosetta(self,extensionPath):
#path = epmv.gui.inst.extdir[1]
#epmv.setEnvPyRosetta(path)
os.environ["PYROSETTA"]=extensionPath
os.environ["PYROSETTA_DATABASE"]=extensionPath+os.sep+"minirosetta_database"
if not os.environ.has_key("DYLD_LIBRARY_PATH"):
os.environ["DYLD_LIBRARY_PATH"]=""
os.environ["DYLD_LIBRARY_PATH"]=extensionPath+":"+extensionPath+"/rosetta:"+os.environ["DYLD_LIBRARY_PATH"]
if not os.environ.has_key("LD_LIBRARY_PATH"):
os.environ["LD_LIBRARY_PATH"]=""
os.environ["LD_LIBRARY_PATH"]=extensionPath+"/rosetta:"+os.environ["LD_LIBRARY_PATH"]
#this is not working! how can I do it
```
#### File: Pmv/hostappInterface/epmvGui.py
```python
from Pmv.hostappInterface import comput_util as C
class ParameterModeller:
def __init__(self,epmv=None):
self.epmv = epmv
id=1005
self.NUMBERS = {"miniIterMax":{"id":id,"name":"max_iteration",'width':50,"height":10,"action":None},
"mdIterMax":{"id":id+1,"name":"max_iteration",'width':50,"height":10,"action":None},
"mdTemp":{"id":id+2,"name":"temperature",'width':50,"height":10,"action":None},
"rtstep":{"id":id+2,"name":"rtstep",'width':100,"height":10,"action":None},
}
id = id + len(self.NUMBERS)
self.BTN = {"mini":{"id":id,"name":"minimize",'width':50,"height":10,"action":None},
"md":{"id":id+1,"name":"MD",'width':50,"height":10,"action":None},
"cancel":{"id":id+2,"name":"Cancel",'width':50,"height":10,"action":None},
"update coordinate":{"id":id+3,"name":"Update coordinates",'width':100,"height":10,"action":self.updateCoord}
}
id = id + len(self.BTN)
self.CHECKBOXS ={"store":{"id":id,"name":"store",'width':100,"height":10,"action":None},
"real-time":{"id":id+1,"name":"real-time",'width':100,"height":10,"action":None},
}
id = id + len(self.CHECKBOXS)
self.COMB_BOX = {"sobject":{"id":id,"width":60,"height":10,"action":None},
"rtType":{"id":id+1,"width":60,"height":10,"action":None}}
id = id + len(self.COMB_BOX)
self.sObject = ["cpk","lines","bones","spline"]
self.rtType = ["mini","md"]
return True
# def setRealTime(self):
# pass
#
# def setRealTimeStep(self):
# pass
#
# def minimize(self):
# pass
#
# def md(self):
# pass
def updateCoord(self):
if hasattr(self.epmv,'gui'):
mol = self.epmv.gui.current_mol
if hasattr(mol,'pmvaction'):
self.epmv.helper.updateMolAtomCoord(mol,mol.pmvaction.idConf,types=mol.pmvaction.sObject)
mol.pmvaction.updateModellerCoord(mol.pmvaction.idConf,mol.mdl)
class ParameterScoringGui:
def __init__(self,epmv=None):
self.epmv = epmv
id=1005
self.BTN = {"rec":{"id":id,"name":"Browse",'width':50,"height":10,
"action":None},
"lig":{"id":id+1,"name":"Browse",'width':50,"height":10,
"action":None},
"ok":{"id":id+2,"name":"Add Scorer",'width':50,"height":10,
"action":self.setup},
"gScore":{"id":id+3,"name":"Get Score",'width':50,"height":10,
"action":self.getScore}
}
id = id + len(self.BTN)
self.TXT = {"rec":{"id":id,"name":"Receptor",'width':50,
"height":10,"action":None},
"lig":{"id":id+1,"name":"ligand",'width':50,
"height":10,"action":None}
}
id = id + len(self.TXT)
self.COMB_BOX = {"score":{"id":id,"name":"type of score","width":60,
"height":10,"action":self.setScorer},
"scorer":{"id":id+1,"name":"available scorer","width":60,
"height":10,"action":self.setCurrentScorer},
}
id = id + len(self.COMB_BOX)
self.scorertype = ['PyPairWise','ad3Score','ad4Score']
if C.cAD : #cAutodock is available
self.scorertype.append('c_ad3Score')
self.scorertype.append('PairWise')
self.getScorerAvailable()
self.CHECKBOXS ={"store":{"id":id,"name":"store",'width':100,
"height":10,"action":None},
"displayLabel":{"id":id+1,"name":"display Label",'width':100,
"height":10,"action":None},
"colorRec":{"id":id+2,"name":"color Rec",'width':100,
"height":10,"action":None},
"colorLig":{"id":id+3,"name":"color Lig",'width':100,
"height":10,"action":None},
"realtime":{"id":id+4,"name":"real time",'width':100,
"height":10,"action":self.setRealtime}
}
id = id + len(self.CHECKBOXS)
return True
def getScorerAvailable(self):
self.scoreravailable = []
if hasattr(self.epmv.mv,'energy'):
self.scoreravailable = self.epmv.mv.energy.data.keys()
def getScore(self):
if hasattr(self.epmv.mv,'energy'):
self.epmv.helper.get_nrg_score(self.epmv.mv.energy)
class parameter_epmvGUI:
def __init__(self,epmv):
self.epmv = epmv
witdh=350
id=1005
#need to split in epmv options and gui options - >guiClass?
self.EPMVOPTIONS = {}
for key in self.epmv.keywords.keys() :
self.EPMVOPTIONS[key] = {"id": id, "name":self.epmv.keywords[key],'width':witdh,"height":10,"action":None}
id = id +1
self.GUIOPTIONS = {}
for key in self.epmv.gui.keywords.keys():
self.GUIOPTIONS[key] = {"id": id, "name":self.epmv.gui.keywords[key],'width':witdh,"height":10,"action":None}
id = id +1
if self.epmv.gui._modeller :
self.OPTIONS['modeller']={"id": id, "name":"Modeller",'width':witdh,"height":10,"action":None}
id = id + 1
self.INPUT ={'timeStep':{"id": id, "name":"steps every",'width':50,"height":10,"action":None},
'frameStep':{"id": id+1, "name":"frames",'width':50,"height":10,"action":None},
}
id = id + (len(self.INPUT))
self.BTN = {"ok":{"id":id,"name":"OK",'width':50,"height":10,"action":self.SetPreferences}}
id = id + 1
return True
class epmvGui:
keywords = {
"_logConsole":"Console log",
"_forceFetch":"Force web Fetch instead of pdb cache"
}
def __init__(self):
id=0
self.MENU_ID = {"File":
[{"id": id, "name":"Open PDB","action":self.buttonLoad},
{"id": id+1, "name":"Open Data","action":self.buttonLoadData}],
"Edit" :
[{"id": id+3, "name":"Options","action":self.drawPreferences}],
"Extensions" : [
{"id": id+4, "name":"PyAutoDock","action":self.drawPyAutoDock}
],
"Help" :
[{"id": id+5, "name":"About ePMV","action":self.drawAbout},
{"id": id+6, "name":"ePMV documentation","action":self.launchBrowser},
{"id": id+2, "name":"Check for Update","action":self.check_update},
],
}
id = id + 7
if self._AF :
self.MENU_ID["Extensions"].append({"id": id, "name":"AutoFill",
"action":self.launchAFgui})
id = id + 1
if self._AR :
self.MENU_ID["Extensions"].append({"id": id, "name":"ARViewer",
"action":self.launchARgui})
id = id + 1
if self._modeller:
self.MENU_ID["Extensions"].append({"id": id, "name":"Modeller",
"action":self.modellerGUI})
id = id + 1
self.MENU_ID["Extensions"].append({"id": id, "name":"Add an Extension",
"action":self.addExtensionGUI})
id = id + 1
self.LABEL_ID = [{"id":id,"label":"to a PDB file OR enter a 4 digit ID (e.g. 1crn):"},
{"id":id+1,"label":""},
{"id":id+2,"label":"Current selection :"},
{"id":id+3,"label":"Add selection set using string or"},
{"id":id+4,"label":"Color scheme:"},
{"id":id+5,"label":"to load a Data file"},
{"id":id+6,"label":"to Current Selection and play below:"},
{"id":id+7,"label":"PMV-Python scripts/commands"},
{"id":id+8,"label":"Molecular Representations"},
{"id":id+9,"label":"Apply"},
{"id":id+10,"label":"a Selection Set"},
{"id":id+11,"label":"atoms in the Selection Set"},
{"id":id+12,"label":"or"},
{"id":id+13,"label":"or"},
{"id":id+14,"label":":"},
]
id = id + len(self.LABEL_ID)#4?
self.EDIT_TEXT = {"id":id,"name":"pdbId","action":None}
id = id + 1
self.DATA_TEXT = {"id":id,"name":"dataFile","action":None}
id = id +1
self.LOAD_BTN = {"id":id,"name":"Browse",'width':40,"height":10,
"action":self.buttonBrowse}
id = id + 1
self.FETCH_BTN = {"id":id,"name":"Fetch",'width':30,"height":10,
"action":self.buttonLoad}
id = id + 1
self.DATA_BTN = {"id":id,"name":"Browse",'width':50,"height":10,
"action":self.buttonLoadData}
id = id + 1
self.PMV_BTN = {"id":id,"name":"Submit/exec",'width':80,"height":10,
"action":self.execPmvComds}
id = id + 1
self.KEY_BTN= {"id":id,"name":"store key-frame",'width':80,"height":10,
"action":None}
id = id + 1
self.DEL_BTN= {"id":id,"name":"delete",'width':80,"height":10,
"action":self.deleteMol}
id = id + 1
self.COMB_BOX = {"mol":{"id":id,"width":60,"height":10,"action":self.update},
"col":{"id":id+1,"width":60,"height":10,"action":self.color},
"dat":{"id":id+2,"width":60,"height":10,"action":self.updateTraj},
"pdbtype":{"id":id+3,"width":50,"height":10,"action":None},
"datatype":{"id":id+4,"width":60,"height":10,"action":None},
"preset":{"id":id+5,"width":60,"height":10,"action":self.drawPreset},
"keyword":{"id":id+6,"width":60,"height":10,"action":self.setKeywordSel},
"scriptO":{"id":id+7,"width":60,"height":10,"action":self.set_ePMVScript},
"scriptS":{"id":id+8,"width":60,"height":10,"action":self.save_ePMVScript},
"selection":{"id":id+9,"width":60,"height":10,"action":self.edit_Selection},
}
id = id + len(self.COMB_BOX)
self.pdbtype=['PDB','TMPDB','OPM','CIF','PQS']
self.datatype=['e.g.','Trajectories:',' .trj',' .xtc','VolumeGrids:']
DataSupported = '\.mrc$|\.MRC$|\.cns$|\.xplo*r*$|\.ccp4*$|\.grd$|\.fld$|\.map$|\.omap$|\.brix$|\.dsn6$|\.dn6$|\.rawiv$|\.d*e*l*phi$|\.uhbd$|\.dx$|\.spi$'
DataSupported=DataSupported.replace("\\"," ").replace("$","").split("|")
self.datatype.extend(DataSupported)
self.presettype=['available presets:',' Lines',' Liccorice',' SpaceFilling',
' Ball+Sticks',' RibbonProtein+StickLigand',
' RibbonProtein+CPKligand',' xray',' Custom',
' Save Custom As...']
self.keyword = ['keywords:',' backbone',' sidechain',' chain',' picked']
kw=map(lambda x:" "+x,ResidueSetSelector.residueList.keys())
self.keyword.extend(kw)
self.scriptliste = ['Open:','pymol_demo','interactive_docking','demo1','user_script']
self.scriptsave = ['Save','Save as']
self.editselection = ['Save set','Rename set','Delete set']
self.SELEDIT_TEXT = {"id":id,"name":"selection","action":None}
id = id+1
self.SEL_BTN ={"add":{"id":id,"name":"Save set",'width':45,"height":10,
"action":self.add_Selection},
"rename":{"id":id+1,"name":"Rename",'width':44,"height":10,
"action":self.rename_Selection},
"deleteS":{"id":id+2,"name":"Delete Set",'width':33,"height":10,
"action":self.delete_Selection},
"deleteA":{"id":id+3,"name":"Delete",'width':33,"height":10,
"action":self.delete_Atom_Selection}
}
id = id + len(self.SEL_BTN)
self.CHECKBOXS ={"cpk":{"id":id,"name":"Atoms",'width':80,"height":10,"action":self.displayCPK},
"bs":{"id":id+1,"name":"Sticks",'width':80,"height":10,"action":self.displayBS},
"ss":{"id":id+2,"name":"Ribbons",'width':40,"height":10,"action":self.displaySS},
"loft":{"id":id+3,"name":"Loft",'width':40,"height":10,"action":self.createLoft},
"arm":{"id":id+4,"name":"Armature",'width':40,"height":10,"action":self.createArmature},
"spline":{"id":id+5,"name":"Spline",'width':40,"height":10,"action":self.createSpline},
"surf":{"id":id+6,"name":"MSMSurf",'width':80,"height":10,"action":self.displaySurf},
"cms":{"id":id+7,"name":"CoarseMolSurf",'width':80,"height":10,"action":self.displayCoarseMS},
"meta":{"id":id+8,"name":"MetaBalls",'width':40,"height":10,"action":self.displayMetaB}
}
id = id + len(self.CHECKBOXS)
self.SLIDERS = {"cpk":{"id":id,"name":"cpk_scale",'width':35,"height":10,"action":self.displayCPK},
"bs_s":{"id":id+1,"name":"bs_scale",'width':35,"height":10,"action":self.displayBS},
"bs_r":{"id":id+2,"name":"bs_ratio",'width':35,"height":10,"action":self.displayBS},
#"ss":{"id":id+2,"name":"ss",'width':15,"height":10,"action":self.displaySS},
#"loft":{"id":id+3,"name":"loft",'width':15,"height":10,"action":self.createLoft},
#"arm":{"id":id+4,"name":"armature",'width':15,"height":10,"action":self.createArmature},
#"spline":{"id":id+5,"name":"spline",'width':15,"height":10,"action":self.createSpline},
"surf":{"id":id+3,"name":"probe",'width':45,"height":10,"action":self.updateSurf},
"cmsI":{"id":id+4,"name":"isovalue",'width':45,"height":10,"action":self.updateCoarseMS},
"cmsR":{"id":id+5,"name":"resolution",'width':45,"height":10,"action":self.updateCoarseMS},
#"meta":{"id":id+8,"name":"MBalls",'width':15,"height":10,"action":self.displayMetaB}
"datS":{"id":id+6,"name":"state",'width':50,"height":10,"action":self.applyState},
#"datV":{"id":id+7,"name":"value",'width':15,"height":10,"action":self.applyValue},
}
id = id + len(self.SLIDERS)
self.COLFIELD = {"id":id,"name":"chooseCol","action":self.chooseCol}
id = id + 1
self.pd = ParameterModeller()
self.argui = ParameterARViewer()
self.ad=ParameterScoring()
self.options = Parameter_ePMV()
```
#### File: Pmv/Macros/DejaVuMac.py
```python
def sideBySideStereo():
"""switch the PMV main camera to side by side stereo mode (crosseyed)"""
self.GUI.VIEWER.cameras[0].Set(stereoMode='SIDE_BY_SIDE')
def mono():
"""switch the PMV main camera to side mono mode"""
self.GUI.VIEWER.cameras[0].Set(stereoMode='MONO')
def transformRoot():
"""Bind trackball to the root object.
The mouse transforms the whole scene move"""
vi = self.GUI.VIEWER
vi.TransformRootOnly(yesno=1)
vi.SetCurrentObject(vi.rootObject)
def selectObject():
"""Bind trackball to a user specified object.
Only geometries related to this object move, scaling
is disabled"""
from Pmv.guiTools import MoleculeChooser
mol = MoleculeChooser(self).go(modal=0, blocking=1)
vi = self.GUI.VIEWER
vi.TransformRootOnly(yesno=0)
obj = mol.geomContainer.geoms['master']
vi.SetCurrentObject(obj)
vi.BindTrackballToObject(obj)
vi.currentTransfMode = 'Object'
def continuousMotion():
"""Toggle continuous motion on and off"""
pass
def showHideDejaVuGUI():
"""show and hide the original DejaVu GUI."""
if self.GUI.VIEWER.GUI.shown:
self.GUI.VIEWER.GUI.withdraw()
else:
self.GUI.VIEWER.GUI.deiconify()
def inheritMaterial(object=None):
"""set material inheritence flag for all objects
in the sub-tree below the current object"""
if object is None: object=self.GUI.VIEWER.currentObject
for c in object.children:
c.inheritMaterial = 1
inheritMaterial(c)
c.RedoDisplayList()
```
#### File: MGLToolsPckgs/Pmv/picker.py
```python
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from ViewerFramework.picker import Picker
import Tkinter, Pmw
from MolKit.molecule import AtomSet, BondSet
class AtomPicker(Picker):
"""
This objects can be used to prompt the user for selecting a set of atoms
or starting a picker that will call a callback function after a user-
defined number of atoms have been selected
"""
def removeAlreadySelected(self, objects):
"""remove for objects the ones already in self.objects"""
return objects - self.objects
def getObjects(self, pick):
"""to be implemented by sub-class"""
atoms = self.vf.findPickedAtoms(pick)
return atoms
def clear(self):
"""clear AtomSet of selected objects"""
self.objects = AtomSet([])
def updateGUI(self, atom):
name = atom.full_name()
self.ifd.entryByName['Atom']['widget'].setentry(name)
def buildInputFormDescr(self):
"""to be implemented by sub-class"""
ifd=InputFormDescr()
ifd.title = "atom picker"
ifd.append({'widgetType':Tkinter.Label,
'name':'event',
'wcfg':{'text':'last atom: '},
'gridcfg':{'sticky':Tkinter.W} })
ifd.append({'widgetType':Pmw.EntryField,
'name':'Atom',
'wcfg':{'labelpos':'w',
'label_text':'Atom: ', 'validate':None},
'gridcfg':{'sticky':'we'}})
if self.numberOfObjects==None:
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Done'},
'command': self.stop})
return ifd
class BondPicker(Picker):
def go(self, modal=0, level='parts'):
Picker.go( self, modal, level)
def removeAlreadySelected(self, objects):
"""remove for objects the ones already in self.objects"""
return objects - self.objects
def clear(self):
"""clear BondSet of selected objects"""
self.objects = BondSet([])
def getObjects(self, pick):
"""to be implemented by sub-class"""
bonds = self.vf.findPickedBonds(pick)
return bonds
def updateGUI(self, bond):
name = bond.atom1.full_name()
self.ifd.entryByName['Atom1']['widget'].setentry(name)
name = bond.atom2.full_name()
self.ifd.entryByName['Atom2']['widget'].setentry(name)
name = str(bond.bondOrder)
self.ifd.entryByName['BondOrder']['widget'].setentry(name)
def buildInputFormDescr(self):
"""to be implemented by sub-class"""
ifd=InputFormDescr()
ifd.title = "bond picker"
ifd.append({'widgetType':Tkinter.Label,
'name':'event',
'wcfg':{'text':'event: '+self.event},
'gridcfg':{'sticky':Tkinter.W} })
ifd.append({'widgetType':Pmw.EntryField,
'name':'Atom1',
'wcfg':{'labelpos':'w',
'label_text':'Atom 1: ',
'validate':None},
'gridcfg':{'sticky':'we'}})
ifd.append({'widgetType':Pmw.EntryField,
'name':'Atom2',
'wcfg':{'labelpos':'w',
'label_text':'Atom 2: ',
'validate':None},
'gridcfg':{'sticky':'we'}})
ifd.append({'widgetType':Pmw.EntryField,
'name':'BondOrder',
'wcfg':{'labelpos':'w',
'label_text':'BondOrder: ',
'validate':None},
'gridcfg':{'sticky':'we'}})
if self.numberOfObjects==None:
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Done'},
'command': self.stop})
return ifd
from DejaVu.IndexedPolygons import IndexedPolygons
class MsmsPicker(Picker):
def getObjects(self, pick):
"""to be implemented by sub-class"""
result = []
for o in pick.hits.keys():
if isinstance(o, IndexedPolygons):
if hasattr(o, 'mol'):
if hasattr(o,'userName'):
result.append(o)
return result
def updateGUI(self, geom):
name = geom.userName
self.ifd.entryByName['Surface']['widget'].setentry(name)
def buildInputFormDescr(self):
"""to be implemented by sub-class"""
ifd=InputFormDescr()
ifd.title = "MSMSsel picker"
ifd.append({'widgetType':Tkinter.Label,
'name':'event',
'wcfg':{'text':'event: '+self.event},
'gridcfg':{'sticky':Tkinter.W} })
ifd.append({'widgetType':Pmw.EntryField,
'name':'Surface',
'wcfg':{'labelpos':'w',
'label_text':'Surface name: ',
'validate':None},
'gridcfg':{'sticky':'we'}})
if self.numberOfObjects==None:
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Done'},
'command': self.stop})
return ifd
class NewMsmsPicker(MsmsPicker):
def getObjects(self, pick):
"""to be implemented by sub-class"""
for o in pick.hits.keys():
if o:
if isinstance(o, IndexedPolygons):
if hasattr(o, 'mol'):
if hasattr(o,'userName'):
return o
if hasattr(o, 'name'):
if o.name=='msms':
result.append(o)
return result
else:
if self.ifd.entryByName.has_key('AllObjects'):
widget = self.ifd.entryByName['AllObjects']['widget']
if len(widget.lb.curselection()):
return widget.entries(int(widget.lb.curselection()[0]))
return None
def allChoices(self):
choices = []
for mol in self.vf.Mols:
geoms = mol.geomContainer.geoms
for geomname in geoms.keys():
if hasattr(geoms[geomname], 'userName') or \
(geomname=='msms' and geoms[geomname].vertexSet):
choices.append(mol.geomContainer.geoms[geomname])
return choices
def updateGUI(self, geom):
if geom.name=='msms':
name = 'msms'
else:
name = geom.userName
self.ifd.entryByName['Surface']['widget'].setentry(name)
def buildInputFormDescr(self):
"""to be implemented by sub-class"""
ifd=InputFormDescr()
ifd.title = "MSMSsel picker"
ifd.append({'widgetType':Tkinter.Label,
'name':'event',
'wcfg':{'text':'event: '+self.event},
'gridcfg':{'sticky':Tkinter.W} })
ifd.append({'widgetType':Pmw.EntryField,
'name':'Surface',
'wcfg':{'labelpos':'w',
'label_text':'Surface name: ',
'validate':None},
'gridcfg':{'sticky':'we'}})
ifd.append({'widgetType':Tkinter.Button,
'name':'Cancel',
'wcfg':{'text':'Cancel',
'command':self.Cancel
}
})
if self.numberOfObjects==None:
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Done'},
'command': self.stop})
return ifd
def Cancel(self, event=None):
self.form.destroy()
```
#### File: Pmv/scenarioInterface/animations.py
```python
from numpy import copy
from DejaVu.scenarioInterface.animations import ColorObjectMAA, PartialFadeMAA,\
RedrawMAA, expandGeoms, getObjectFromString
from DejaVu.scenarioInterface import getActor
from Scenario2.keyframes import KF
from Scenario2.multipleActorsActions import MultipleActorsActions
colorCmds = {"color by atom types": ["colorByAtomType", "Atm"],
"color by molecule":["colorByMolecules", "Mol"],
"color by DG": ["colorAtomsUsingDG", "DG "],
"color by second.struct.":["colorBySecondaryStructure", "SSt"],
"color by residue:RasmolAmino": ["colorByResidueType", "RAS"],
"color by residue:Shapely": ["colorResiduesUsingShapely", "SHA"],
"choose color": ["color", "col"]}
# the values in the colorCmds dictionary are from pmv.commands.keys()
class PmvColorObjectMAA(ColorObjectMAA):
""" Create an MAA for different coloring schemes:
- colorByAtomType
- colorByMolecules
- colorAtomsUsingDG
- colorBySecondaryStructure
- colorByResidueType
- colorResiduesUsingShapely
- color (choose color)
"""
def __init__(self, object, objectName=None, name=None, nbFrames=None,
kfpos=[0,30], pmv = None, colortype = "color by atom types",
color = [(0.0, 0.0, 1.0)], nodes = None, easeInOut='none',
objectFromString = None, startFlag="after previous", saveAtomProp=False):
""" Create an MAA to color a Pmv object.
maa <- PmvColorObjectMAA(object, objectName=None, name=None, nbFrames=None,
kfpos=[0,30], pmv = None, colortype = "color by atom types",
color = [(0.0, 0.0, 1.0)], nodes = None,
objectFromString = None, startFlag='after previous')
arguments:
- object - a geometry object (or list of objects) to color;
- objectName - the object's name. If it is not specified, the class constructor
will try to use 'fullName' attribute of the object.
- name - the MAA name;
- nodes - specifies a subset of atoms;
- pmv is an instance of Pmv;
- colortype - one of the available coloring schemes;
- color - specifies (r,g, b) tuple if colortype is 'choose color';
- either a total number of frames (nbFrames) or a list of keyframe positions
(kfpos) can be specified;
- objectFromString is a string that yields the specified oject(s) when evaluated;
- startFlag - flag used in a sequence animator for computing time position of the maa.
"""
if not hasattr(object, "__len__"):
objects = [object]
else:
objects = object
if objectFromString is None:
objectFromString = getObjectFromString(objects)
self.actors = []
self.endFrame = 0
self.gui = None
self.redrawActor = None
if not pmv:
print "application Pmv is not specified"
return
vi = pmv.GUI.VIEWER
if colortype not in colorCmds.keys():
print "unsupported color scheme %s" % colortype
return
self.cmd = pmv.commands[colorCmds[colortype][0]]
self.shortName = colorCmds[colortype][1]
self.color = color
self.pmv = pmv
if nodes is None:
nodes = pmv.getSelection()
self.nodes = nodes
geoms = self.cmd.getAvailableGeoms(nodes)
#print "available geoms", geoms
molnames = map(lambda x: x.name , pmv.Mols)
for object in objects:
#print "object:", object
oname = object.name
if oname != "root" and oname not in geoms and oname not in molnames:
import tkMessageBox
tkMessageBox.showwarning("Pmv AniMol warning:", "Cannot create %s animation for %s -\nobject is not available for Pmv color command."%(colortype, object.name))
#print "object %s cannot be colored with %s" % (object.name, colortype)
ind = objects.index(object)
objects.pop(ind)
if not len(objects):
return
vi.stopAutoRedraw()
geomsToColor = []
molecules = []
for object in objects:
if object.name == "root":
geomsToColor = geoms # "all"
molecules = self.cmd.getNodes(nodes)[0]
break
elif object.name in molnames:
geomsToColor = geoms
molecules = [pmv.getMolFromName(object.name),]
break
else:
geomsToColor.append(object.name)
if hasattr(object, "mol"):
molecules.append(object.mol)
#Get initial color .If the object is a geometry container, get colors for each child geometry.
initColors = self.initColors = self.getObjectsColors(geomsToColor, molecules)
#print "nodes" , nodes
#print "color type:", colortype
#print "objects:", objects
#print "geoms to color:", geomsToColor
#print "calling command", self.cmd
editorKw = {}
# call command and get current value
if colortype == "choose color":
self.cmd(nodes, color, geomsToColor, log = 0)
editorKw = {'choosecolor': True}
else:
self.cmd(nodes, geomsToColor, log = 0)
#finalColors = self.finalColors = self.getObjectsColors(objects, nodes)
finalColors = self.finalColors = self.getObjectsColors(geomsToColor, molecules)
geoms = finalColors.keys()
self.geomsToColor = geomsToColor
self.molecules = molecules
#print "geoms:", geoms
self.atomSets = {}
if len(geoms):
ColorObjectMAA.__init__(self, geoms, initColors=initColors,
finalColors=finalColors,
objectName=objectName, name=name,
nbFrames=nbFrames, kfpos=kfpos,
colortype = colortype,
objectFromString=objectFromString,
startFlag=startFlag, easeInOut=easeInOut)
for object in objects:
# object is probably a geom container, so we need to add a 'visible' actor for it:
visibleactor = getActor(object, 'visible')
if not self.findActor(visibleactor):
self.origValues[visibleactor.name] = visibleactor.getValueFromObject()
kf1 = KF(kfpos[0], 1)
visibleactor.actions.addKeyframe(kf1)
self.AddActions( visibleactor, visibleactor.actions )
if saveAtomProp:
try:
self.saveGeomAtomProp()
except: pass
#return to the orig state
pmv.undo()
vi.startAutoRedraw()
self.editorKw = editorKw
def saveGeomAtomProp(self):
self.atomSets = {}
allobj = self.objects
from MolKit.molecule import Atom
from copy import copy
for obj in allobj:
if hasattr(obj, "mol"):
mol = obj.mol
set = mol.geomContainer.atoms.get(obj.name, None)
if set is not None and len(set):
#print "saving aset for:" , obj.fullName
aset = set.findType(Atom).copy()
self.atomSets[obj.fullName] = {'atomset': set.full_name(0)}
#self.atomSets[obj.fullName] = {'atomset': set}
#if aset.colors.has_key(obj.name):
# self.atomSets[obj.fullName]['colors']=copy(aset.colors[obj.name])
#elif aset.colors.has_key(obj.parent.name):
# self.atomSets[obj.fullName]['colors']=copy(aset.colors[obj.parent.name])
def getObjectsColors(self, geomsToColor, molecules):
colors = {}
for mol in molecules:
allGeoms = []
geomC = mol.geomContainer
for gName in geomsToColor:
if not geomC.geoms.has_key(gName): continue
geom = geomC.geoms[gName]
allGeoms.append(gName)
if len(geom.children):
childrenNames = map(lambda x: x.name, geom.children)
allGeoms = allGeoms + childrenNames
for name in allGeoms:
if geomC.atoms.has_key(name) and len(geomC.atoms[name])==0: continue
col = geomC.getGeomColor(name)
if col is not None:
g = geomC.geoms[name]
colors[g] = col
return colors
def setGeomAtomProp(self):
if not len(self.atomSets) : return
from MolKit.molecule import Atom
prop = 'colors'
for actor in self.actors:
if actor.name.find(prop) > 0:
obj = actor.object
if self.atomSets.has_key(obj.fullName):
#setstr = self.atomSets[obj.fullName]['atomset']
g = obj.mol.geomContainer
aset = g.atoms[obj.name].findType(Atom)
asetstr = aset.full_name(0)
#if len(asetstr) != len(setstr):
# return
atList = []
func = g.geomPickToAtoms.get(obj.name)
if func:
atList = func(obj, range(len(obj.vertexSet.vertices)))
else:
allAtoms = g.atoms[obj.name]
if hasattr(obj, "vertexSet") and len(allAtoms) == len(obj.vertexSet):
atList = allAtoms
if not len(atList): return
col = actor.getLastKeyFrame().getValue()
oname = None
if aset.colors.has_key(obj.name):
oname = obj.name
elif aset.colors.has_key(obj.parent.name):
oname = obj.parent.name
if not oname : return
if len(col) == 1:
for a in atList:
a.colors[oname] = tuple(col[0])
else:
for i, a in enumerate(atList):
a.colors[oname] = tuple(col[i])
from MolKit.stringSelector import StringSelector
selector = StringSelector()
#nset, msg = selector.select(atList, setstr)
nset, msg = selector.select(atList, asetstr)
#if g.atoms[obj.name].elementType == Atom:
#obj.mol.geomContainer.atoms[obj.name] = nset
def getSourceCode(self, varname, indent=0):
"""
Return python code creating this object
"""
if not self.objectFromString:
return ""
tabs = " "*indent
lines = tabs + """import tkMessageBox\n"""
lines += tabs + """from Pmv.scenarioInterface.animations import PmvColorObjectMAA\n"""
lines += tabs + """object = %s\n"""%(self.objectFromString)
newtabs = tabs + 4*" "
lines += tabs + """try:\n"""
lines += newtabs + """%s = PmvColorObjectMAA(object, objectName='%s', name='%s', kfpos=%s, pmv=pmv, colortype='%s', """ % (varname, self.objectName, self.name, self.kfpos, self.colortype)
lines += """ nodes=%s""" %(self.cmd._strArg(self.nodes)[0], )
import numpy
if type(self.color) == numpy.ndarray:
lines += """color=%s, """ % self.color.tolist()
else:
lines += """color=%s, """ % self.color
lines += """ objectFromString="%s", startFlag='%s', saveAtomProp=False)\n""" % (self.objectFromString, self.startFlag)
lines += newtabs + """assert len(%s.actors) > 0 \n""" % (varname,)
lines += tabs + """except:\n"""
lines += newtabs + """if showwarning: tkMessageBox.showwarning('Pmv AniMol warning', 'Could not create MAA %s')\n""" % self.name
lines += newtabs + """print sys.exc_info()[1]\n"""
return lines
def configure(self, **kw):
"""
set kfpos, direction and easeInOut and rebuild MAA
"""
if kw.has_key('color'):
if self.colortype == "choose color":
vi = self.pmv.GUI.VIEWER
vi.stopAutoRedraw()
self.cmd(self.nodes, kw['color'], self.geomsToColor, log = 0)
finalColors = self.finalColors = self.getObjectsColors(self.geomsToColor,
self.molecules)
self.pmv.undo()
vi.startAutoRedraw()
self.color = kw['color']
kw.pop('color')
if not kw.has_key('colortype'):
kw['colortype'] = self.colortype
ColorObjectMAA.configure(self, **kw)
def run(self, forward=True):
ColorObjectMAA.run(self, forward)
try:
self.setGeomAtomProp()
except:
pass
#print "FAILED to setGeomAtomProp"
def setValuesAt(self, frame, pos=0):
ColorObjectMAA.setValuesAt(self, frame, pos)
if frame == pos + self.lastPosition:
try:
self.setGeomAtomProp()
except:
pass
from MolKit.molecule import Atom
class PartialFadeMolGeomsMAA(PartialFadeMAA):
"""
build a MAA to fade in parts of a molecule for geometry objects where the
atom centers correspond to the geometry vertices (cpk, sticks, balls,
bonded, etc)
[maa] <- PartialFadeMolGeomsMAA(object, nodes=None, pmv=None,
objectName=None, name=name,
nbFrames=None, kfpos=[0,30], easeInOut='none',
destValue=1.0, fade='in', startFlag='after previous')
- object is a DejaVu geometry object or a list of objects
- nodes specifies a subset of atoms
- pmv is an instance of Pmv
- destValues is the opacity desired at the end of the fade in
- fade can be 'in' or 'out'. for 'in' the MAA fades nodes in to a level of
opacity destValue. For 'out' it fades them out to opacity destValue
- either a total number of frames (nbFrames) or a list of keyframe positions
(kfpos) can be specified;
- startFlag - flag used in a sequence animator for computing time position of the maa.
For each molecule a vector of an MAA is generated that will force the
geom's visibility to True and interpolate th per-vertex array of opacities
from a starting vetor to a final vector. Only entries in this vector
corresponding to the atoms to be faded in will have interpolated value.
Other displayed atoms will retain their current opacity
NOTE: the atoms specified by nodes have to be displayed for the specified
geoemtries BEFORE this function is called
"""
def __init__(self, object, nodes=None, pmv=None, objectName=None, name=None,
kfpos=[0,30], easeInOut='none', destValue=None, fade='in',
objectFromString = None, startFlag="after previous"):
if not hasattr(object, "__len__"):
objects = [object]
else:
objects = object
geometries = expandGeoms(objects)
self.actors = []
self.endFrame = 0
self.gui = None
self.redrawActor = None
self.editorClass = None
if not pmv:
print "application Pmv is not specified"
return
self.pmv = pmv
if not len(geometries):
return
vi = pmv.GUI.VIEWER
if fade=='in':
if destValue is None:
destValue = 0.6
else:
if destValue is None:
destValue = 0.4
if name is None:
if objectName:
name = "partial fade %s, %s, %3.1f"% (
fade, objectName, destValue)
if objectFromString is None:
objectFromString = getObjectFromString(objects)
self.actors = []
self.easeInOut = easeInOut
self.destValue = destValue
self.fade = fade
self.nodes = nodes
#print "geometries", geometries, "nodes", nodes
#self.objects = geometries
allobjects = self.getOpacityValues(geometries, nodes, destValue, fade)
self.objects = allobjects
if len(allobjects):
PartialFadeMAA.__init__(self, allobjects, self.initOpac, self.finalOpac, name=name,
objectName=objectName,
kfpos=kfpos, easeInOut=easeInOut,
objectFromString=objectFromString,
startFlag=startFlag)
from Pmv.scenarioInterface.animationGUI import SESpOpSet_MAAEditor
self.editorClass = SESpOpSet_MAAEditor
self.editorKw = {'pmv': pmv}
self.editorArgs = []
if not len(self.actors):
RedrawMAA.__init__(self, vi, name)
#print "cannot create PartialFadeMAA for object:", object.name, self.actors
def getOpacityValues(self, objects, nodes=None, destValue=None, fade=None):
if nodes != None:
self.nodes = nodes
if destValue != None:
self.destValue = destValue
if fade != None:
self.fade = fade
allobjects = []
self.initOpac = initOpac = {}
self.finalOpac = finalOpac = {}
#if self.nodes:
# print "lennodes:", len(self.nodes)
#print "objects ", objects
for geom in objects:
try:
molecules, atmSets = self.pmv.getNodesByMolecule(self.nodes, Atom)
# for each molecule
geomName = geom.name
for mol, atms in zip(molecules, atmSets):
if not mol.geomContainer.geoms.has_key(geomName):
continue
if geom.mol != mol:
continue
# get the set of atoms in mol currently displayed as CPK
atset = mol.geomContainer.atoms[geomName]
# build initial and final vector of opacities
_initOpac = geom.materials[1028].prop[1][:,3].copy()
_finalOpac = _initOpac.copy()
if len(_finalOpac) == 1:
import numpy
_finalOpac = numpy.ones(len(atset), 'f')*_initOpac[0]
atIndex = {} # provides atom index in atset
for i, at in enumerate(atset):
atIndex[at] = i
# set initial opacity and final opacity for all atoms to fade in
if self.fade=='in':
for at in atms:
i = atIndex[at]
_initOpac[ i ] = 0.0
_finalOpac[ i ] = self.destValue
else:
for at in atms:
i = atIndex[at]
_finalOpac[ i ] = self.destValue
allobjects.append(geom)
initOpac[geom] = _initOpac
finalOpac[geom] = _finalOpac
except:
if self.fade=='in':
initOpac[geom] = [0.0]
else:
initOpac[geom] = geom.materials[1028].prop[1][:,3]
allobjects.append(geom)
finalOpac[geom] = self.destValue
return allobjects
def configure(self, **kw):
"""set nodes, destValue, fade parameters and rebuild MAA."""
nodes = None
if kw.has_key('nodes'):
nodes = kw.pop('nodes')
destValue = None
if kw.has_key('destValue'):
destValue = kw.pop('destValue')
fade = None
if kw.has_key('fade'):
fade = kw.pop('fade')
allobjects = self.getOpacityValues(self.objects, nodes, destValue, fade)
self.objects = allobjects
PartialFadeMAA.configure(self, **kw)
self.name = "partial fade %s, %s, %3.1f"% (
self.fade, self.objectName, destValue)
def getSourceCode(self, varname, indent=0):
"""
Return python code creating this object
"""
if not self.objectFromString:
return ""
tabs = " "*indent
lines = tabs + """import tkMessageBox\n"""
lines += tabs + """from Pmv.scenarioInterface.animations import PartialFadeMolGeomsMAA\n"""
lines += tabs + """object = %s\n"""%(self.objectFromString)
newtabs = tabs + 4*" "
lines += tabs + """try:\n"""
lines += newtabs + """%s = PartialFadeMolGeomsMAA(object, objectName='%s', name='%s', kfpos=%s, pmv=pmv, fade='%s', destValue=%.2f, """ % (varname, self.objectName, self.name, self.kfpos, self.fade, self.destValue)
if not hasattr(self.pmv, "color"):
self.pmv.loadModule("colorCommands", "Pmv")
lines += """ nodes=%s""" %(self.pmv.color._strArg(self.nodes)[0], )
lines += """easeInOut='%s', """ % self.easeInOut
lines += """ objectFromString="%s", startFlag='%s')\n""" % (self.objectFromString, self.startFlag)
lines += newtabs + """assert len(%s.actors) > 0 \n""" % (varname,)
lines += tabs + """except:\n"""
lines += newtabs + """if showwarning: tkMessageBox.showwarning('Pmv AniMol warning', 'Could not create MAA %s')\n""" % self.name
lines += newtabs + """print sys.exc_info()[1]\n"""
return lines
```
#### File: Pmv/scenarioInterface/GeomChooser.py
```python
from DejaVu.GeomChooser import GeomChooser
from Pmv.GeomFilter import GeomFilter
from Pmv.moleculeViewer import MoleculeViewer
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
import Tkinter
class PmvSetChooser(ListChooser):
def __init__(self, root, mv, title="select a set:",
command=None, mode="single", cwcfg=None):
self.mv = mv
pmvsets = self.getPmvSets()
ListChooser.__init__(self, root, mode=mode, title=title, entries=pmvsets,
command=command, cwcfg=cwcfg)
self.widget.configure(exportselection = False)
def getPmvSets(self):
"""Return a list containing the names of pmv sets"""
pmvsets = []
for key, value in self.mv.sets.items():
pmvsets.append( (key, value.comments) )
## if len(pmvsets):
## pmvsets.insert(0, ("None", " "))
return pmvsets
def updateList(self):
"""Update the entries of the pmvset chooser"""
pmvsets = self.getPmvSets()
self.setlist(pmvsets)
def getSets(self):
items = []
setNames = self.get()
for name in setNames:
if self.mv.sets.has_key(name):
items.append( (name, self.mv.sets[name]))
return items
def getNodes(self):
nodes = None
sets = self.getSets()
if len(sets):
nodes = []
for set in sets:
nodes = nodes + set[1]
return nodes
class PmvGeomChooser(GeomChooser):
"""
The PmvGeomChooser object has two ListBox widgets :
- first displays a list of geometries present in the DejaVu.Viewer object.
- second displays a list of Pmv sets
"""
def __init__(self, mv, root=None, showAll=True, filterFunction=None,
command=None, pmvsetCommand=None, refreshButton=True, showAllButton=True):
"""
PmvGeomChooser constructor
PmvGeomChooserObject <- PmvGeomChooser(vf, showAll=True, filterFunction=None, root=None,
command=None)
- mv is an instance of MoleculeViewer
- showAll is a boolean. When True all objects present in the Viewer are shown
- filterFunction is an optional function that will be called when
showAll is False. I takes one argument (a Viewer object) and returns a
list of (name, [geoms]) pairs. The names will be displayed in the GUI
for representing the corresponding list of geometry objects.
- root is the master in which the chooser will be created.
- command is the fucntion call upon selection in the geometry list
- pmvsetCommand - fucntion call upon selection in the pmv sets list
"""
assert isinstance(mv, MoleculeViewer)
self.mv = mv
if filterFunction is None:
self.gf = GeomFilter(mv)
filterFunction = self.gf.filter
GeomChooser.__init__(self, self.mv.GUI.VIEWER, showAll=showAll,
filterFunction=filterFunction, root=root, #self.frame,
command=command, refreshButton=refreshButton,
showAllButton=showAllButton)
self.chooserW.mode = 'single'
self.chooserW.widget.configure(exportselection = False) # this is done to prevent disappearing
#of the ListBox selection when a text is selected in another widget or window.
self.chooserW.widget.configure(height=15)
self.setChooser=PmvSetChooser(self.frame, mv, title = "select a set:",
command=pmvsetCommand, mode="multiple" )
self.setChooser.widget.configure(height=5)
self.setChooser.pack(side='top', fill='both', expand=1)
def updateList(self):
"""Update the entries of geometry and pmvset choosers"""
GeomChooser.updateList(self)
self.setChooser.updateList()
def getSets(self):
return self.setChooser.getSets()
def getNodes(self):
return self.setChooser.getNodes()
def showAll_cb(self, even=None):
val = self.showAllVar.get()
self.showAll = val
self.updateList()
```
#### File: MGLToolsPckgs/Pmv/stringSelectorGUI.py
```python
import numpy.oldnumeric as Numeric, Tkinter, types, string
from DejaVu.viewerFns import checkKeywords
from MolKit.molecule import MoleculeSet, Atom, AtomSetSelector
from MolKit.protein import Protein, ProteinSetSelector, Residue, \
ResidueSetSelector, Chain, ChainSetSelector
import tkMessageBox, tkSimpleDialog
from MolKit.stringSelector import StringSelector
class StringSelectorGUI(Tkinter.Frame):
""" molEntry, chainEntry, resEntry, atomEntry
molMB, chainMB, resSetMB, atomSetMB, #setsMB
showBut,
clearBut, acceptBut, closeBut
"""
entryKeywords = [
'molWids',
'molLabel',
'molEntry',
'chainWids',
'chainLabel',
'chainEntry',
'resWids',
'resLabel',
'resEntry',
'atomWids',
'atomLabel',
'atomEntry',
]
menuKeywords = [
'molMB',
'chainMB',
'resSetMB',
'atomSetMB',
]
buttonKeywords = [
'showBut',
'clearBut',
]
masterbuttonKeywords = [
'acceptBut',
'closeBut'
]
def __init__(self, master, check=0, molSet=MoleculeSet([]),
userPref = 'cS', vf = None, all=1, crColor=(0.,1.,0),
clearButton=True, showButton=True, sets=None, **kw):
if not kw.get('packCfg'):
self.packCfg = {'side':'top', 'anchor':'w','fill':'x'}
self.sets = sets
#all is a shortcut to use all of default values
if 'all' in kw.keys():
all = 1
elif __debug__:
if check:
apply( checkKeywords, ('stringSelector', self.entryKeywords), kw)
Tkinter.Frame.__init__(self, master)
##????
Tkinter.Pack.config(self, side='left', anchor='w')
#to make a stringSelector need vf, moleculeSet, selString
self.master = master
self.molSet = molSet
self.residueSelector = ResidueSetSelector()
self.atomSelector = AtomSetSelector()
self.userPref = userPref
self.vf = vf
if not self.vf is None:
self.addGeom(crColor)
else:
self.showCross = None
self.molCts = {}
self.chainCts = {}
# optsDict includes defaults for all possible widgets
# in practice
# user can specify which widgets to put into gui
d = self.optsDict = {}
#first check for menubuttons:
llists = [self.entryKeywords, self.menuKeywords, self.buttonKeywords]
if all:
if not clearButton:
self.buttonKeywords.remove("clearBut")
if not showButton:
self.buttonKeywords.remove("showBut")
for l in llists:
for key in l:
d[key] = 1
else:
for l in llists:
for key in l:
d[key] = kw.get(key)
self.flexChildren = {
'mol': ['molLabel', 'molEntry'],
'chain': ['chainLabel', 'chainEntry'],
'res': ['resLabel', 'resEntry'],
'atom': ['atomLabel', 'atomEntry'],
}
for w in ['molWids', 'chainWids','resWids','atomWids']:
if kw.get(w):
lab = w[:-4]
s = lab+'Label'
d[s] = 1
s1 = lab+'Entry'
d[s1] = 1
# instantiate all Tkinter variables (?)
#DON"T HAVE ANY???
self.buildTkVars()
# only build requested widgets(?)
self.buildifdDict()
# build commandDictionary
self.buildCmdDict()
self.buildGUI()
def buildifdDict(self):
#to prevent dependency on InputFormDescr: put all widgets in a frame
#this dictionary has default values for each widget
self.ifdDict = {}
self.ifdDict['topFrame'] = {'name': 'topFrame',
'widgetType':Tkinter.Frame,
'wcfg':{'relief': 'flat', 'bd':2},
'packCfg':{'side':'top', 'fill':'x'}
}
self.ifdDict['buttonFrame'] = {'name': 'buttonFrame',
'widgetType':Tkinter.Frame,
'wcfg':{'relief': 'flat', 'bd':2},
'packCfg':{'side':'top', 'fill':'x'}
}
self.ifdDict['entryFrame'] = {'name': 'entryFrame',
'widgetType':Tkinter.Frame,
'wcfg':{'relief': 'flat', 'bd':2},
'packCfg':{'side':'left'}
}
self.ifdDict['menuFrame'] = {'name': 'menuFrame',
'widgetType':Tkinter.Frame,
'wcfg':{'relief': 'flat', 'bd':2},
'packCfg':{'side':'left', 'fill':'x'}
}
self.ifdDict['molWids'] = {'name': 'molWids',
'widgetType': Tkinter.Frame,
'wcfg':{'relief': 'flat'},
'children': ['molLabel', 'molEntry'],
'packCfg':{'side':'top'}
}
self.ifdDict['molLabel'] = {'name': 'molLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text': 'Molecule'},
'packCfg':{'side':'left', 'anchor': 'w', 'fill':'x'}
}
self.ifdDict['molEntry'] = {'name': 'molEntry',
'widgetType':Tkinter.Entry,
'wcfg':{'bd': 3},
'packCfg':{'side':'left', 'anchor':'e', 'fill':'x'}
}
self.ifdDict['chainWids'] = {'name': 'chainWids',
'widgetType': Tkinter.Frame,
'wcfg':{'relief': 'flat', 'bd':3},
'children': ['chainLabel', 'chainEntry'],
'packCfg':{'side':'top'}
}
self.ifdDict['chainLabel'] = {'name': 'chainLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text': 'Chain '},
'packCfg':{'anchor': 'w', 'side':'left'}
}
self.ifdDict['chainEntry'] = {'name': 'chainEntry',
'widgetType':Tkinter.Entry,
'wcfg':{'bd': 3},
'packCfg':{'side':'left', 'anchor':'e', 'fill':'x'}
}
self.ifdDict['resWids'] = {'name': 'resWids',
'widgetType': Tkinter.Frame,
'wcfg':{'relief': 'flat'},
'children': ['resLabel', 'resEntry'],
'packCfg':{'side':'top'}
}
self.ifdDict['resLabel'] = {'name': 'resLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text': 'Residue'},
'packCfg':{'anchor': 'w', 'side':'left'}
}
self.ifdDict['resEntry'] = {'name': 'resEntry',
'widgetType':Tkinter.Entry,
'wcfg':{'bd': 3},
'packCfg':{'side':'left', 'anchor':'e', 'fill':'x'}
}
self.ifdDict['atomWids'] = {'name': 'atomWids',
'widgetType': Tkinter.Frame,
'wcfg':{'relief': 'flat'},
'children': ['atomLabel', 'atomEntry'],
'packCfg':{'side':'top'}
}
self.ifdDict['atomLabel'] = {'name': 'atomLabel',
'widgetType':Tkinter.Label,
'wcfg':{'text': 'Atom '},
'packCfg':{'anchor': 'w', 'side':'left'}
}
self.ifdDict['atomEntry'] = {'name': 'atomEntry',
'widgetType':Tkinter.Entry,
'wcfg':{'bd': 3},
'packCfg':{'side':'left', 'anchor':'e', 'fill':'x'}
}
#next the menus
self.ifdDict['molMB'] = {'name': 'molMB',
'widgetType':Tkinter.Menubutton,
'buildMenuCmd': self.buildMolMenu,
'wcfg':{
'text': 'Molecule List',
'relief': 'ridge'},
'packCfg':{'side':'top', 'anchor':'w', 'fill':'x'}}
self.ifdDict['chainMB'] = {'name': 'chainMB',
'widgetType':Tkinter.Menubutton,
'buildMenuCmd': self.buildChainMenu,
'wcfg':{
'text': 'Chain List',
'relief': 'ridge'},
'packCfg':{'side':'top', 'anchor':'w', 'fill':'x'}}
self.ifdDict['resSetMB'] = {'name': 'resSetMB',
'widgetType':Tkinter.Menubutton,
'buildMenuCmd': self.buildResMenus,
'wcfg':{
'text': 'ResidueSet List',
'relief': 'ridge'},
'packCfg':{'side':'top', 'anchor':'w', 'fill':'x'}}
self.ifdDict['atomSetMB'] = {'name': 'atomSetMB',
'widgetType':Tkinter.Menubutton,
'buildMenuCmd': self.buildAtomMenus,
'wcfg':{
'text': 'AtomSet List',
'relief': 'ridge'},
'packCfg':{'side':'top', 'anchor':'w', 'fill':'x'}}
#some way to toggle visual aide
self.ifdDict['showBut'] = {'name': 'showBut',
'widgetType':Tkinter.Checkbutton,
'wcfg':{
'command': self.Show_cb,
'variable': self.showCurrent,
# should there be a box?
#'indicatoron':0,
'text':'Show ',
'relief':'raised',
'bd': '1'},
'packCfg':{'side':'left', 'anchor':'w', 'fill':'x'}}
#last the buttons
self.ifdDict['clearBut'] = {'name': 'clearBut',
'widgetType':Tkinter.Button,
'wcfg':{
'command': self.Clear_cb,
'text':'Clear Form',
'relief':'raised',
'bd': '1'},
'packCfg':{'side':'left', 'anchor':'w', 'fill':'x'}}
self.ifdDict['acceptBut'] = {'name': 'acceptBut',
'widgetType':Tkinter.Button,
'wcfg':{
'command': self.get,
'text':'Accept',
'relief':'raised',
'bd': '1'},
'packCfg':{'side':'left', 'anchor':'w', 'fill':'x'}}
self.ifdDict['closeBut'] = {'name': 'closeBut',
'widgetType':Tkinter.Button,
'wcfg':{
'command': self.Close_cb,
'text':'Close ',
'relief':'raised',
'bd': '1'},
'packCfg':{'side':'left', 'anchor':'w', 'fill':'x'}}
def buildTkVars(self):
self.showCurrent = Tkinter.IntVar()
self.showCurrent.set(0)
#for n in ['showCurrent']:
# exec('self.'+ n + '= Tkinter.IntVar()')
# exec('self.'+ n + '.set(0)')
def addGeom(self, crColor):
from DejaVu.Points import CrossSet
#need to have a new name if there is already a 'strSelCrossSet'
# in the viewer...
name = 'strSelCrossSet'
ctr = 0
for c in self.vf.GUI.VIEWER.rootObject.children:
if c.name[:14]==name[:14]:
ctr = ctr + 1
if ctr>0:
name = name + str(ctr)
self.showCross=CrossSet(name,
inheritMaterial=0, materials=(crColor,),
offset=0.5, lineWidth=2)
self.showCross.Set(visible=1, tagModified=False)
self.showCross.pickable = 0
self.vf.GUI.VIEWER.AddObject(self.showCross)
def bindMenuButton(self, mB, command, event='<ButtonPress>', add='+'):
mB.bind(event, command, add=add)
def buildMenu(self, mB, nameList, varDict, oldvarDict, cmd):
if nameList:
#prune non-valid entries
for i in varDict.keys():
if i not in nameList:
del varDict[i]
del oldvarDict[i]
#add anything new
for i in nameList:
if i not in varDict.keys():
varDict[i]=Tkinter.IntVar()
oldvarDict[i]=0
else:
varDict={}
oldvarDict={}
#start from scratch and build menu
#4/24: only build and add 1 menu
if hasattr(mB, 'menu'):
mB.menu.delete(1,'end')
else:
mB.menu = Tkinter.Menu(mB)
mB['menu']=mB.menu
#PACK all the entries
for i in varDict.keys():
mB.menu.add_checkbutton(label=i, var=varDict[i], command=cmd)
def buildMolMenu(self,event=None):
if not hasattr(self,'molVar'): self.molVar={}
if not hasattr(self,'oldmolVar'): self.oldmolVar={}
molNames = self.molSet.name
self.buildMenu(self.molMB,molNames,self.molVar,self.oldmolVar,self.getMolVal)
def buildChainMenu(self,event=None):
if not hasattr(self,'chainVar'): self.chainVar={}
if not hasattr(self,'oldchainVar'): self.oldchainVar={}
chMols = MoleculeSet([])
if len(self.molSet):
chMols=MoleculeSet(filter(lambda x: Chain in x.levels, self.molSet))
chainIDList = []
if len(chMols):
chains=chMols.findType(Chain)
if chains==None: return
for i in chains:
chainIDList.append(i.full_name())
self.buildMenu(self.chainMB,chainIDList,self.chainVar,self.oldchainVar,self.getChainVal)
def buildResMenus(self,event=None):
if not hasattr(self,'ResSetsVar'): self.ResSetsVar={}
if not hasattr(self,'oldResSetsVar'): self.oldResSetsVar={}
ResSetsList = self.residueSelector.residueList.keys()
self.residueList = self.residueSelector.residueList
#ResSetsList = residueList_.keys()
#self.residueList = residueList_
self.buildMenu(self.resSetMB,ResSetsList,self.ResSetsVar,self.oldResSetsVar,self.getResSetsVal)
def buildAtomMenus(self,event=None):
if not hasattr(self,'AtomSetsVar'): self.AtomSetsVar={}
if not hasattr(self,'oldAtomSetsVar'): self.oldAtomSetsVar={}
AtomSetsList = self.atomSelector.atomList.keys()
self.atomList = self.atomSelector.atomList
#AtomSetsList = atomList_.keys()
#self.atomList = atomList_
self.buildMenu(self.atomSetMB,AtomSetsList,self.AtomSetsVar,self.oldAtomSetsVar,self.getAtomSetsVal)
def increaseCts(self,dict, newStr):
if dict.has_key(newStr):
dict[newStr]=dict[newStr]+1
else:
dict[newStr]=1
def decreaseCts(self,dict,newStr):
if dict.has_key(newStr):
currentVal=dict[newStr]
if currentVal<=1: currentVal=1
dict[newStr]=currentVal-1
def getMolVal(self, event=None):
molWidget = self.molEntry
for molStr in self.molVar.keys():
#figure out which check button was just changed
newVal=self.molVar[molStr].get()
if newVal==self.oldmolVar[molStr]: continue
else:
self.oldmolVar[molStr]=newVal
molList=string.split(molWidget.get(),',')
if newVal==1:
self.increaseCts(self.molCts,molStr)
if not molStr in molList:
if molWidget.index('end')==0:
molWidget.insert('end',molStr)
else:
molWidget.insert('end',','+molStr)
else:
if molStr in molList:
self.molCts[molStr]=0
molList.remove(molStr)
molWidget.delete(0,'end')
molWidget.insert('end',string.join(molList,','))
#also turn off all of the chain checkbuttons:
chainWidget=self.chainEntry
chainList=string.split(chainWidget.get(),',')
# chain menu may not have been built yet:
if not hasattr(self, 'chainVar'):
self.buildChainMenu()
for ch in self.chainVar.keys():
chKeyList = string.split(ch,':')
thisMolStr=chKeyList[0]
thisChainStr=chKeyList[1]
#if the chain is in this molecule
if thisMolStr==molStr:
#turn off chain checkbutton
self.chainVar[ch].set(0)
self.oldchainVar[ch]=0
self.decreaseCts(self.chainCts,thisChainStr)
if len(chKeyList)>1 and thisChainStr in chainList:
chainList.remove(thisChainStr)
chainWidget.delete(0,'end')
chainWidget.insert('end',string.join(chainList,','))
def getChainVal(self, event=None):
chains = self.molSet.findType(Chain)
molWidget = self.molEntry
chainWidget = self.chainEntry
for item in self.chainVar.keys():
molStr,chainStr = string.split(item,':')
newVal=self.chainVar[item].get()
if newVal ==self.oldchainVar[item]:
continue
else:
self.oldchainVar[item]=newVal
molList=string.split(molWidget.get(),',')
chainList=string.split(chainWidget.get(),',')
if newVal==1:
self.increaseCts(self.molCts,molStr)
self.increaseCts(self.chainCts,chainStr)
if not molStr in molList:
if molWidget.index('end')==0:
molWidget.insert('end',molStr)
else:
molWidget.insert('end',','+molStr)
###11/17:#if chainStr!=' ' and not chainStr in chainList:
if not chainStr in chainList:
if chainWidget.index('end')==0:
chainWidget.insert('end',chainStr)
else:
chainWidget.insert('end',','+chainStr)
if hasattr(self, 'molVar') and self.molVar.has_key(molStr):
self.molVar[molStr].set(1)
else:
self.buildMolMenu()
self.molVar[molStr].set(1)
self.oldmolVar[molStr]=1
else:
if not self.molCts.has_key(molStr): continue
if not self.chainCts.has_key(chainStr): continue
self.decreaseCts(self.molCts,molStr)
self.decreaseCts(self.chainCts,chainStr)
chainList=string.split(chainWidget.get(),',')
###11/17:#if chainStr in chainList or chainStr==' ':
if chainStr in chainList:
if chainStr in chainList and self.chainCts[chainStr]==0:
chainList.remove(chainStr)
if self.molCts[molStr]==0:
if hasattr(self, 'molVar') and self.molVar.has_key(molStr):
self.molVar[molStr].set(0)
self.oldmolVar[molStr]=0
#also remove it from Molecule entry
molList=string.split(molWidget.get(),',')
if molStr in molList:molList.remove(molStr)
newss1=string.join(molList,',')
molWidget.delete(0,'end')
molWidget.insert('end',newss1)
##also have to fix the Chain entry:
chainWidget.delete(0,'end')
chainWidget.insert('end',string.join(chainList,','))
def getResSetsVal(self, event=None):
w = self.resEntry
ssList = string.split(w.get(),',')
for newStr in self.ResSetsVar.keys():
if self.ResSetsVar[newStr].get()==1:
if newStr not in ssList:
if w.index('end')==0:
w.insert('end',newStr)
else:
w.insert('end',',')
w.insert('end',newStr)
#method to remove here
else:
if newStr in ssList:
ssList.remove(newStr)
w.delete(0,'end')
w.insert(0,string.join(ssList,','))
def getAtomSetsVal(self, event=None):
w = self.atomEntry
ssList = string.split(w.get(),',')
for newStr in self.AtomSetsVar.keys():
if self.AtomSetsVar[newStr].get()==1:
if newStr not in ssList:
if w.index('end')==0:
w.insert('end',newStr)
else:
w.insert('end',',')
w.insert('end',newStr)
#method to remove here
else:
if newStr in ssList:
ssList.remove(newStr)
w.delete(0,'end')
w.insert(0,string.join(ssList,','))
def getSetsVal(self, event=None):
if len(self.sets):
sets = self.sets.keys()
for newStr in self.setsVar.keys():
node0 = self.sets[newStr][0]
##this would work only w/ 4 levels(/)
nodeLevel = node0.isBelow(Protein)
l = [self.molEntry, self.chainEntry, self.resEntry, self.atomEntry]
w = l[nodeLevel]
ssList=string.split(w.get(),',')
if self.setsVar[newStr].get()==1:
if newStr==' ': continue
if not newStr in ssList:
if w.index('end')==0:
w.insert('end',newStr)
else:
w.insert('end',',')
w.insert('end',newStr)
else:
if newStr in ssList:
ssList.remove(newStr)
w.delete(0,'end')
w.insert(0,string.join(ssList,','))
def buildArgs(self, event=None):
kw = {}
kw['mols'] = self.molEntry.get()
kw['chains'] = self.chainEntry.get()
kw['res'] = self.resEntry.get()
kw['atoms'] = self.atomEntry.get()
return kw
def get(self, event=None, withMsg=False):
args = self.buildArgs()
atArg = self.atomEntry.get()
#print "atArg=", atArg, "=='' is", atArg==""
resArg = self.resEntry.get()
#print "resArg=", resArg, "=='' is", resArg==""
chainArg = self.chainEntry.get()
#print "chainArg=", chainArg, "=='' is", chainArg==""
molArg = self.molEntry.get()
#print "molArg=", molArg, "=='' is", molArg==""
if atArg!="":
args = molArg + ':' + chainArg + ':' + resArg + ':' + atArg
elif resArg!="":
args = molArg + ':' + chainArg + ':' + resArg
elif chainArg!="":
args = molArg + ':' + chainArg
else:
args = molArg
#print "calling StringSelector.select with args=", args
selitem, msgStr = StringSelector().select(self.molSet, args, sets=self.sets, caseSensitive=self.userPref)
#if StringSelector starts returning msgs fix here
#selitem, msgStr = StringSelector().select(self.molSet, args, self.userPref)
#return selitem, msgStr
#if selitem and len(selitem):
# print "returning len(selitem)=", len(selitem)
if withMsg:
return selitem, msgStr
else:
return selitem
def set(self, val):
valList = string.split(val, ',')
if not len(valList)==4:
delta = 4-len(valList)
for i in range(delta):
valList.append('')
if valList[0]!="''":
self.molEntry.insert('end', valList[0])
if valList[1]!="''":
self.chainEntry.insert('end', valList[1])
if valList[2]!="''":
self.resEntry.insert('end', valList[2])
if valList[3]!="''":
self.atomEntry.insert('end', valList[3])
def Show_cb(self, event=None):
if self.showCurrent.get():
current = self.get()
#if stringSelector starts returning msgs fix here
#current, msgStr = self.get()
if not self.vf:
print 'nowhere to show'
return
if not current:
msg = 'nothing to show'
self.vf.warningMsg(msg, title='String Selector GUI WARNING:')
self.showCurrent.set(0)
return
allAt = current.findType(Atom)
if allAt is None or len(allAt)==0:
self.showCross.Set(vertices=[], tagModified=False)
else:
self.showCross.Set(vertices = allAt.coords, tagModified=False)
else:
self.showCross.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def Clear_cb(self, event=None):
for item in [self.molEntry, self.chainEntry, self.resEntry, \
self.atomEntry]:
item.delete(0, 'end')
#also have to turn off all the vars and reset all Cts
ss1 = ['molVar', 'chainVar', 'ResSetsVar', \
'AtomSetsVar']
dTkList = []
for item in ss1:
if hasattr(self, item):
#dTkList.append(eval('self.'+item))
dTkList.append(getattr(self, item))
#dTkList = [self.molVar, self.chainVar, self.ResSetsVar, \
#self.AtomSetsVar]
for d in dTkList:
for k in d.keys():
d[k].set(0)
ss2 = ['oldmolVar', 'oldchainVar', 'oldResSetsVar',\
'oldAtomSetsVar']
dintList = [self.molCts, self.chainCts]
for item in ss2:
if hasattr(self, item):
#dintList.append(eval('self.'+item))
dintList.append(getattr(self, item))
#dintList = [self.oldmolVar, self.oldchainVar, self.oldResSetsVar,\
#self.oldAtomSetsVar]
for d in dintList:
for k in d.keys():
d[k]=0
if self.showCurrent.get():
self.showCurrent.set(0)
if self.showCross:
self.showCross.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
def Close_cb(self, event=None):
if self.showCross:
self.showCross.Set(vertices=[], tagModified=False)
self.vf.GUI.VIEWER.Redraw()
self.master.withdraw()
#def buildFileMenu(self, event=None):
# cmdList = [self.Close_cb]
# #cmdList = [self.Accept_cb, self.Close_cb]
# #fileOpts = ['Accept', 'Close']
# fileOpts = ['Close']
# if not self.showFileMenu.get():
# if not hasattr(self.fileMB, 'menu'):
# self.buildMenu(fileOpts, self.fileMB, None, None,
# type = 'button', cmdList = cmdList)
# self.showFileMenu.set(1)
# else:
# self.fileMB.menu.unpost()
# self.showFileMenu.set(0)
#def buildHelpMenu(self, event=None):
#tkMessageBox.showwarning('Warning',self.helpMsg)
def buildCmdDict(self):
self.cmdDict = {}
for key, value in self.optsDict.items():
if value:
if type(value) == types.DictionaryType and \
value.has_key('command'):
self.cmdDict[key] = value['command']
elif key in self.ifdDict.keys() and self.ifdDict[key].has_key('command'):
self.cmdDict[key] = self.ifdDict[key]['command']
def updateChildren(self):
d = self.optsDict
for key, chList in self.flexChildren.items():
val = d[key]
if val:
#set alternate children list
for ch in chList:
d[ch] = val
def buildFrame(self, widName, parent = None):
#print 'in buildFrame with ', widName
if parent==None:
parent = self
widDict = self.ifdDict[widName]
newWid = apply(Tkinter.Frame, (parent,), widDict['wcfg'])
exec('self.'+widName+'=newWid')
apply(newWid.pack, (), widDict['packCfg'])
def buildGUI(self):
#first build Frames
#which set up Menubar and rest
#self.MBFrame = Tkinter.Frame(self.master, relief='raised')
#widStrings = ['MBFrame', 'WidFrame']
self.buildFrame('topFrame' )
self.buildFrame('buttonFrame' )
widStrings = ['entryFrame', 'menuFrame']
keyList = [self.entryKeywords, self.menuKeywords]
for num in range(2):
wid = widStrings[num]
widDict = self.ifdDict[wid]
if self.optsDict.get(wid):
for k, v in self.optsDict.get(wid).items():
if type(v) == types.DictionaryType:
for subk, subv in v.items():
widDict[k][subk] = subv
else: widDict[k] = v
newWid = apply(Tkinter.Frame, (self.topFrame,), widDict['wcfg'])
exec('self.'+wid+'=newWid')
apply(newWid.pack, (), widDict['packCfg'])
#if num==1: self.updateChildren()
self.buildWidgets(keyList[num], newWid)
self.buildWidgets(self.buttonKeywords, self.buttonFrame)
self.buildWidgets(self.masterbuttonKeywords, self.buttonFrame)
def buildWidgets(self, keyList, master):
for key in keyList:
value = self.optsDict.get(key)
if not value:
#skip this widget
#print 'skipping ', key
continue
else:
#first check whether there is a cfg
widDict = self.ifdDict[key]
if value!=1:
#check whether it's a dictionary
for k, v in value.items():
if type(v) == types.DictionaryType:
for subk, subv in v.items():
widDict[k][subk] = subv
else: widDict[k] = v
#make the widget here
w = widDict['widgetType']
del widDict['widgetType']
#save possible pack info + command to bind
widCallback = widDict.get('callBack')
if widCallback: del widDict['callBack']
packCfg = widDict.get('packCfg')
if packCfg: del widDict['packCfg']
else: packCfg = self.packCfg
#save possible menuBuild cmds
buildMenuCmd = widDict.get('buildMenuCmd')
if buildMenuCmd: del widDict['buildMenuCmd']
#if w==Tkinter.Menubutton: master = self.MBFrame
#else: master = self.WidFrame
newW = apply(w, (master,), widDict['wcfg'])
if buildMenuCmd:
newW.bind('<ButtonPress>', buildMenuCmd, add='+')
#frames have children to build and pack
if widDict.has_key('children'):
for ch in widDict['children']:
if not self.optsDict.get(ch): continue
else:
#first grab any passed info
wD =self.ifdDict[ch]
opD = self.optsDict[ch]
if type(opD)==types.DictionaryType:
for k, v in opD.items():
wD[k] = v
# mark this ch as done
self.optsDict[ch] = 0
ch_w = wD['widgetType']
del wD['widgetType']
childCallback = wD.get('callBack')
if childCallback: del wD['callBack']
childPackCfg = wD.get('packCfg')
if childPackCfg: del wD['packCfg']
else: childPackCfg = self.packCfg
newChild = apply(ch_w, (newW,), wD['wcfg'])
newChild.pack(childPackCfg)
exec('self.'+ch+'= newChild')
if childCallback:
self.bindCallback(newChild, childCallback)
#if key=='spacing':
#newW.pack = newW.frame.pack
#if key in ['fileMB', 'cenMB', 'visiMB', 'helpMB']:
#newW.bind('<ButtonPress>', cmdDict[key], add='+')
newW.pack(packCfg)
exec('self.'+key+'= newW')
#check for a command to bind to newW
if key in self.cmdDict.keys():
##binding depends on type of widget
if newW.__class__==Tkinter.Scale:
newW.bind('<ButtonRelease>', widDict['command'])
if widCallback:
self.bindCallback(newW, widCallback)
def bindCallback(self, wid, cmdDict):
if type(cmdDict)!=types.DictionaryType:
#this is a cheap way to set up defaults
cmdDict = {}
event = cmdDict.get('event')
if not event: event = '<ButtonPress>'
add = cmdDict.get('add')
if not add: add = '+'
command = cmdDict.get('command')
if not command: command = self.updateBox
wid.bind(event, command, add=add)
def returnEntries(self):
#build list of requested options to return
returnList=[]
for item in self.dict.keys():
if self.dict[item]:
returnList.append(self.ifdDict['item'])
return returnList
if __name__=='__main__':
#code to test it here
print 'testing stringSelector'
import pdb
root = Tkinter.Tk()
root.withdraw()
top = Tkinter.Toplevel()
top.title = 'StringSelectorGUI'
strSel = StringSelectorGUI(top, all = 1, crColor=(1.,0.,0.))
```
#### File: Pmv/styles/sessionToStyle.py
```python
import os, sys
if len(sys.argv) < 3:
print "Usage: python sessionToStyle sessionFile, molName"
sys.exit(1)
filename = sys.argv[1]
molname = sys.argv[2]
f = open(filename)
lines = f.readlines()
f.close()
name, ext = os.path.splitext(filename)
f = open(name+'_style.py', 'w')
f.write("numberOfMolecules = 1\n\n")
f.write("__doc__ = """Style_01: Applies to X molecules. It displays ..
"""\n")
f.write("def applyStyle(mv, molName):\n")
f.write(" mode='both'\n")
for l in lines:
# replace self by mv
l = l.replace('self', 'mv')
# look for "nolname in PMV commands
try:
start = l.index('"'+molname)
end = l[start+1:].index('"')
newline1 = l[:start+1]+'%s'+l[start+1+len(molname):start+end+2] +\
"%molName"+l[start+end+2:]
except ValueError:
newline1 = l
# look for |molname| in DejaVu Geometry
try:
start = newline1.index("FindObjectByName('root|")+23
end = newline1[start+1:].index('|')
newline2 = newline1[:start]+"'+molName+'"+newline1[start+1+end:]
except ValueError:
newline2 = newline1
f.write(" %s"%newline2)
f.close()
```
#### File: MGLToolsPckgs/PyAutoDock/AutoGrid.py
```python
import numpy.oldnumeric as Numeric, os, string
from MolKit.molecule import Atom, AtomSet
from MolKit import Read
from MolecularSystem import MolecularSystem
from AutoDockScorer import AutoGrid305Scorer, AutoDockTermWeights305
from AutoDockScorer import AutoGrid4Scorer, AutoDockTermWeights4
from AutoDockScorer import AutoDockVinaScorer, AutoDockVinaTermWeights
from scorer import WeightedMultiTerm
from electrostatics import Electrostatics
from desolvation import NewDesolvationDesolvMap
class GridMap:
def __init__(self, entity,
npts=[5,5,5], spacing=0.375, center=[0,0,0]):
self.entity = entity
self.npts = npts
self.spacing = spacing
self.center = center
def get_entity_list(self):
"""<gen_entities docstring>"""
npts = self.npts
sp = self.spacing
cen = self.center
ent = self.entity
for z in xrange(-(npts[2]/2), npts[2]/2 + 1):
for y in xrange(-(npts[1]/2), npts[1]/2 + 1):
for x in xrange(-(npts[0]/2), npts[0]/2 + 1):
ent._coords[ent.conformation] = [x*sp+cen[0],
y*sp+cen[1],
z*sp+cen[2]]
yield ent
def get_entity(self):
"""returns the entity supplied to the constructor"""
return self.entity
# GridMap
class AutoGrid:
at_vols = { 'C' : 12.77,
'A' : 10.80}
def __init__(self, receptor,
atom_types=['A', 'C', 'H', 'N', 'O', 'S'],
npts=[5, 5, 5], spacing=0.375, center=[0., 0., 0.]):
# we expect the receptor parameter to be a MolKit.Molecule
# or some such instance with an allAtoms attribute
assert( hasattr( receptor, 'allAtoms'))
self.receptor = receptor
# these are atom_types of the ligand for which maps will be written
self.atom_types = atom_types
# make the single atom that will traverse the grid
self.atom = self._create_atom(atom_types[0])
# create the GridMap
self.grid_map = GridMap(self.atom, npts, spacing, center)
# create molecular system
self.ms = MolecularSystem()
# (the receptor must be the first molecule in the configuration)
self.receptor_ix = self.ms.add_entities( self.receptor.allAtoms )
# add the grid generator to the ms as the 'second molecule'
self.grid_map_ix = self.ms.add_entities( self.grid_map )
# that is it for the molecular system for now. later when
# we write the maps the grid_map's atom attributes
# (autodock_element and AtVol) must be set for each atom map.
#make this a separate step so that it can be overridden
self.setup_scorer()
def setup_scorer(self):
# construct atom_map scorer...
self.atom_map_scorer = AutoGrid305Scorer()
self.atom_map_scorer.set_molecular_system(self.ms)
# ... and electrostatics scorer
self.estat_map_scorer = WeightedMultiTerm()
self.estat_map_scorer.add_term(Electrostatics(),
AutoDockTermWeights305().estat_weight)
self.estat_map_scorer.set_molecular_system(self.ms)
def _create_atom(self, atom_type):
"""Simple, private helper function for __init__
"""
element = atom_type
name = element + str(0)
at = Atom(name=name, chemicalElement=element)
at._charges = {'gridmap': 1.0}
at.chargeSet = 'gridmap'
at.number = 1
at._coords = [[0., 0., 0.]]
at.conformation = 0
#these 2 would change between maps:
at.autodock_element = element
at.AtVol = self.at_vols.get(element, 0.0)
#print "set AtVol to", at.AtVol
return at
def write_maps(self, filename=None):
# now create the atom maps
for element in self.atom_types:
# set atom.element to the element
self.atom.element = element
self.atom.autodock_element = element
self.atom.AtVol = self.at_vols.get(element, 0.0)
# score it
score_array = self.atom_map_scorer.get_score_array()
# create filename and write it
filename = self.receptor.name + "." + element + ".map"
self.write_grid_map(score_array, filename)
# create the electrostatics map
score_array = self.estat_map_scorer.get_score_array()
# create filename and write it
filename = self.receptor.name + ".e.map"
self.write_grid_map(score_array, filename)
# now write the fld file
filename = self.receptor.name + ".maps.fld"
self.write_maps_fld(filename)
# now write the xyz file
filename = self.receptor.name + ".maps.xyz"
self.write_xyz_file(filename)
def set_grid_map_center(self, center):
self.grid_map.center = center
self.ms.clear_dist_mat(self.grid_map_ix)
def set_grid_map_npts(self, npts):
self.grid_map.npts = npts
self.ms.clear_dist_mat(self.grid_map_ix)
def set_grid_map_spacing(self, spacing):
self.grid_map.spacing = spacing
self.ms.clear_dist_mat(self.grid_map_ix)
def write_grid_map(self, score_array, filename):
stem = string.split(os.path.basename(filename), '.')[0]
# open and write the file
fptr = open(filename, 'w')
# line 1:
ostr = "GRID_PARAMETER_FILE " + stem + ".gpf\n"
fptr.write(ostr)
# line 2:
ostr = "GRID_DATA_FILE " + stem + ".maps.fld\n"
fptr.write(ostr)
# line 3:
rec_name = os.path.basename(self.receptor.parser.filename)
#ostr = "MACROMOLECULE " + stem + ".pdbqs\n"
ostr = "MACROMOLECULE %s\n" %rec_name
fptr.write(ostr)
# line 4:
ostr = "SPACING " + str(self.grid_map.spacing) + "\n"
fptr.write(ostr)
# line 5:
xnpts,ynpts,znpts = self.grid_map.npts
if xnpts%2!=0: xnpts = xnpts-1
if ynpts%2!=0: ynpts = ynpts-1
if znpts%2!=0: znpts = znpts-1
ostr = "NELEMENTS %d %d %d\n" % (xnpts,ynpts,znpts)
fptr.write(ostr)
# line 6:
ostr = "CENTER %f %f %f\n" % tuple(self.grid_map.center)
fptr.write(ostr)
# now write the values after
# summing the receptor atom energies for each grid point
for value in Numeric.add.reduce(score_array):
ostr = "%.3f\n" % (value)
fptr.write(ostr)
# all done...
fptr.close()
def write_xyz_file(self, filename=None):
"""AutoDock305 and AutoDock4 may require this xyz field file
"""
xpts, ypts,zpts = self.grid_map.npts
spacing = self.grid_map.spacing
x_extent = int(xpts/2) * spacing
y_extent = int(ypts/2) * spacing
z_extent = int(zpts/2) * spacing
xcen, ycen, zcen = self.grid_map.center
if filename is None:
filename = self.receptor.name + '.maps.xyz'
fptr = open(filename, 'w')
ostr = "%5.3f %5.3f\n" %(xcen-x_extent, xcen+x_extent)
fptr.write(ostr)
ostr = "%5.3f %5.3f\n" %(ycen-y_extent, ycen+y_extent)
fptr.write(ostr)
ostr = "%5.3f %5.3f\n" %(zcen-z_extent, zcen+z_extent)
fptr.write(ostr)
fptr.close()
def write_maps_fld(self, filename=None):
"""AutoDock305 and AutoDock4 require this maps fld file
"""
if filename is None:
filename = self.receptor.name + '.maps.fld'
stem = string.split(os.path.basename(filename), '.')[0]
# open and write the file
fptr = open(filename, 'w')
# lines 1 + 2:
ostr = "# AVS field file\n#\n"
fptr.write(ostr)
# lines 3 + 4:
ostr = "# AutoDock Atomic Affinity and Electrostatic Grids\n#\n"
fptr.write(ostr)
# lines 5 + 6:
ostr = "# Created by AutoGrid.py\n#\n"
fptr.write(ostr)
# line 7 spacing info
ostr = "#SPACING %5.3f \n" %self.grid_map.spacing
fptr.write(ostr)
# line 8 npts info
npts = self.grid_map.npts
for i in range(len(npts)):
if npts[i]%2!=0:
npts[i]=npts[i]-1
ostr = "#NELEMENTS %d %d %d\n" % tuple(npts)
#ostr = "#NELEMENTS %d %d %d\n" % tuple(self.grid_map.npts)
fptr.write(ostr)
# line 9:
ostr = "#CENTER %f %f %f\n" % tuple(self.grid_map.center)
fptr.write(ostr)
# line 10:
ostr = "#MACROMOLECULE %s\n" % self.receptor.name
fptr.write(ostr)
# lines 11+12:
#IS THIS CORRECT//REQUIRED???
gpffilename = self.receptor.name + '.gpf'
ostr = "#GRID_PARAMETER_FILE %s\n#\n" % gpffilename
fptr.write(ostr)
#avs stuff
# line 13:
ostr = "ndim=3\t\t\t# number of dimensions in the field\n"
fptr.write(ostr)
# lines 14-16:
xnpts = self.grid_map.npts[0]
if xnpts%2==0: xnpts = xnpts+1
ynpts = self.grid_map.npts[1]
if ynpts%2==0: ynpts = ynpts+1
znpts = self.grid_map.npts[1]
if znpts%2==0: znpts = znpts+1
ostr = "dim1=%d # number of x-elements\n" %xnpts
fptr.write(ostr)
ostr = "dim2=%d # number of y-elements\n" %ynpts
fptr.write(ostr)
ostr = "dim3=%d # number of z-elements\n" %znpts
fptr.write(ostr)
# line 17:
ostr = "nspace=3 # number of physical coordinates per point\n"
fptr.write(ostr)
# line 18:
veclen = len(self.atom_types) + 1 #atommaps + estat map
ostr = "veclen=%d # number of affinity values at each point\n" %veclen
fptr.write(ostr)
#lines 19 + 20:
ostr = "data=float # data type (byte, integer, float, double)\nfield=uniform # field type (uniform, rectilinear, irregular)\n"
fptr.write(ostr)
#lines 21-23:
xyzfilename = self.receptor.name + '.maps.xyz'
for i in range(3):
ostr = "coord %d file=%s.maps.xyz filetype=ascii offset=%d\n" %(i+1, self.receptor.name, i*2)
fptr.write(ostr)
#lines 23-23+num_atom_maps:
for ix, t in enumerate(self.atom_types):
ostr = "label=%s-affinity\t# component label for variable %d\n"%(t,ix+1)
fptr.write(ostr)
#output electrostatics label
ostr = "label=Electrostatics\t# component label for variable %d\n"%(ix+1)
fptr.write(ostr)
# comment lines:
ostr = "#\n# location of affinity grid files and how to read them\n#\n"
fptr.write(ostr)
#more lines for each map
for ix, t in enumerate(self.atom_types):
mapfilename = self.receptor.name + '.' + t + '.map'
ostr = "variable %d file=%s filetype=ascii skip=6\n"%(ix+1,mapfilename)
fptr.write(ostr)
e_mapfilename = self.receptor.name + '.e.map'
ostr = "variable %d file=%s filetype=ascii skip=6\n"%(ix+2,e_mapfilename)
fptr.write(ostr)
fptr.close()
# AutoGrid
class AutoGrid4(AutoGrid):
def __init__( self, receptor, atom_types=['A', 'C', 'HD', 'NA', 'OA', 'SA'],
npts=[5, 5, 5], spacing=0.375, center=[0., 0., 0.]):
AutoGrid.__init__(self, receptor, atom_types, npts, spacing, center)
def setup_scorer(self):
# construct atom_map scorer...
#lenB is required for newHydrogenBonding term
npts = self.grid_map.npts
self.ms.lenB = npts[0]*npts[1]*npts[2]
self.atom_map_scorer = AutoGrid4Scorer()
self.atom_map_scorer.set_molecular_system(self.ms)
# ... and newdesolvationdesolvmap scorer
self.desolv_map_scorer = WeightedMultiTerm()
self.desolv_map_scorer.add_term(NewDesolvationDesolvMap(),
AutoDockTermWeights4().dsolv_weight)
self.desolv_map_scorer.set_molecular_system(self.ms)
# ... and electrostatics scorer
self.estat_map_scorer = WeightedMultiTerm()
self.estat_map_scorer.add_term(Electrostatics(),
AutoDockTermWeights4().estat_weight)
self.estat_map_scorer.set_molecular_system(self.ms)
def _create_atom(self, atom_type):
"""Simple, private helper function for __init__
"""
element = atom_type
name = element + str(0)
at = Atom(name=name, chemicalElement=element)
at._charges = {'gridmap': 1.0}
at.chargeSet = 'gridmap'
at.number = 1
at._coords = [[0., 0., 0.]]
at.conformation = 0
#these 2 would change between maps:
at.autodock_element = element
#volumes are in the scorer
#at.AtVol = self.at_vols.get(element, 0.0)
#print "set AtVol to", at.AtVol
return at
def write_maps(self, filename=None):
# now create the atom maps
for element in self.atom_types:
# set atom.element to the element
self.atom.element = element
self.atom.autodock_element = element
#self.atom.AtVol = self.at_vols.get(element, 0.0)
# score it
score_array = self.atom_map_scorer.get_score_array()
# create filename and write it
filename = self.receptor.name + "." + element + ".map"
self.write_grid_map(score_array, filename)
# create the desolvation map
score_array = self.desolv_map_scorer.get_score_array()
# create filename and write it
filename = self.receptor.name + ".d.map"
self.write_grid_map(score_array, filename)
# create the electrostatics map
score_array = self.estat_map_scorer.get_score_array()
# create filename and write it
filename = self.receptor.name + ".e.map"
self.write_grid_map(score_array, filename)
# now write the fld file
filename = self.receptor.name + ".maps.fld"
self.write_maps_fld(filename)
# now write the xyz file
filename = self.receptor.name + ".maps.xyz"
self.write_xyz_file(filename)
# AutoGrid4
class AutoGridVina(AutoGrid4):
def __init__( self, receptor, atom_types=['A', 'C', 'HD', 'NA', 'OA', 'SA'],
npts=[5, 5, 5], spacing=0.375, center=[0., 0., 0.]):
AutoGrid4.__init__(self, receptor, atom_types, npts, spacing, center)
def setup_scorer(self):
# construct atom_map scorer...
#lenB is required for newHydrogenBonding term
#npts = self.grid_map.npts
#self.ms.lenB = npts[0]*npts[1]*npts[2]
self.atom_map_scorer = AutoDockVinaScorer()
self.atom_map_scorer.set_molecular_system(self.ms)
self.atom_map_scorer.terms[4][0].set_vina_types(self.ms.get_entities(0))#receptor
self.atom_map_scorer.terms[4][0].set_vina_types(self.ms.get_entities(1))#ligand
#self.atom_map_scorer.terms[4][0].set_vina_types(self.receptor.allAtoms)
def _create_atom(self, atom_type):
"""Simple, private helper function for __init__
"""
element = atom_type
name = element + str(0)
at = Atom(name=name, chemicalElement=element)
at._charges = {'gridmap': 1.0}
at.chargeSet = 'gridmap'
at.number = 1
at._coords = [[0., 0., 0.]]
at.conformation = 0
#these 2 would change between maps:
at.autodock_element = element
return at
def write_maps(self, filestem=None, fld=1, xyz=1):
# now create the atom maps
if filestem is None:
filestem = self.receptor.name
for element in self.atom_types:
# set atom.element to the element
self.atom.element = element
self.atom.autodock_element = element
try:
self.atom_map_scorer.terms[4][0].set_vina_types(AtomSet(self.atom))
except:
self.atom.is_hydrophobic = self.atom.element in ['A','C', 'HD']
# score it
score_array = self.atom_map_scorer.get_score_array()
# create filename and write it
filename = filestem + "." + element + ".map"
self.write_grid_map(score_array, filename)
# now possibly write the fld file
if fld:
fld_filename = filestem + ".maps.fld"
self.write_maps_fld(fld_filename)
# now possibly write the xyz file
if xyz:
xyz_filename = self.receptor.name + ".maps.xyz"
self.write_xyz_file(xyz_filename)
# AutoGrid4
if __name__ == '__main__':
print "Test are in Tests/test_AutoGrid.py"
```
#### File: MGLToolsPckgs/PyAutoDock/electrostatics.py
```python
import math
from scorer import DistDepPairwiseScorer
class ElectrostaticsRefImpl(DistDepPairwiseScorer):
"""reference implementation of the Electrostatics class
Notes
======
* For now, the MolecularSystem has the responsibility of
supplying charges. This could change in the future if the
chargeCalculators migrate away from MolKit. This requires
a reduced dependency on the Atoms.
* The electrostatics calculation depends on relative distance
not absolute coords. Hopefully, we won't need coords in this
class.
* A GridMap might be represencted as a 'subset' in this class
by defining psuedo-atoms at each grid point.
"""
def __init__(self, ms=None):
DistDepPairwiseScorer.__init__(self)
# add the required attributes of this subclass to the dict
self.required_attr_dictA.setdefault('charge', False)
self.required_attr_dictB.setdefault('charge', False)
if ms is not None:
self.set_molecular_system(ms)
self.use_non_bond_cutoff = False
def get_dddp(self, distance):
"""return distance dependent dielectric permittivity
weight to be remove to WeightedMultiTermDistDepPairwiseScorer
Reference
==========
Mehler & Solmajer (1991) Protein Engineering vol.4 no.8, pp. 903-910.
Basically, this describes a sigmoidal function from a low
dielectric (like organic solvent) at small distance (<5Ang)
asymptoticly to dielectric of water at large distance (30Ang).
epsilon(r) = A + (B/[1+ k*exp(-lambda*B*r)]) (equation 6)
where, A, lambda, and k are parameters supplied by the paper,
B = epsilon0 - A (so B is also a parameter)
epsilon0 is the dielectric constant of water at 25C (78.4)
Two sets of parameters are given in the paper:
{'A' : -8.5525, 'k' : 7.7839, 'lambda_' : 0.003627} [Conway]
{'A' : -20.929, 'k' : 3.4781, 'lambda_' : 0.001787} [Mehler&Eichele]
"""
epsilon0 = 78.4 # dielectric constant of water at 25C
lambda_ = 0.003627 # supplied parameter
A = -8.5525 # supplied parameter
k = 7.7839 # supplied parameter
B = epsilon0 - A
# epsilon is a unitless scaling factor
epsilon = A + B / (1.0 + k*math.e**(-lambda_*B*distance))
return epsilon
def _f(self, at_a, at_b, dist):
"""Return electrostatic potential in kcal/mole.
Here's how the 332. unit conversion factor is calculated:
q = 1.60217733E-19 # (C) charge on electron
eps0 = 8.854E-12 # (C^2/J*m) vacuum permittivity
J_per_cal = 4.18400 # Joules per calorie
avo = 6.02214199E23 # Avogadro's number
factor = (q*avo*q*1E10 )/(4.0*math.pi*eps0*J_per_cal*1000)
"""
q1 = at_a.charge;
q2 = at_b.charge;
epsilon = self.get_dddp(dist)
factor = 332. # 4*pi*esp0*units conversions
if dist != 0.0:
return (factor*q1*q2) / (epsilon*dist) # kcal/mole
else: return 0.
Electrostatics = ElectrostaticsRefImpl
# ElectrostaticsRefImpl
if __name__ == '__main__':
pass
# test_scorer.run_test()
```
#### File: MGLToolsPckgs/PyAutoDock/InternalEnergy.py
```python
import numpy.oldnumeric as Numeric
from MolKit.molecule import Atom
from PyAutoDock.MolecularSystem import MolecularSystem
from PyAutoDock.scorer import WeightedMultiTerm
from PyAutoDock.vanDerWaals import VanDerWaals, NewVanDerWaals
from PyAutoDock.vanDerWaals import HydrogenBonding
from PyAutoDock.vanDerWaals import NewHydrogenBonding, NewHydrogenBonding12_10
from PyAutoDock.electrostatics import Electrostatics
from PyAutoDock.desolvation import NewDesolvation, Desolvation
class InternalEnergy(WeightedMultiTerm):
"""
TODO:
* sort out how the ms should be configured for internal energy.
Should the ie_scorer get its own ms, or should a single ms
be configured for a AutoDockScorer and then reconfigured for
internal energy.
* Unittest need independent/validated data.
* there a 4x nested loop down in get_bonded_matrix
"""
def __init__(self, exclude_one_four=False, weed_bonds=False):
WeightedMultiTerm.__init__(self)
self.exclude_one_four = exclude_one_four
self.weed_bonds = weed_bonds
def add_term(self, term, weight=1.0, symmetric=True):
"""add the term and weight as a tuple to the list of terms.
"""
term.symmetric = symmetric
if hasattr(self, 'ms'):
term.set_molecular_system(self.ms)
self.terms.append( (term, weight) )
def print_intramolecular_energy_analysis(self, filename=None):
"""
NOTE:For use ONLY with (autodock-like) 4 term scorers
"""
num_atoms = len(self.ms.get_entities(0))
ctr = 1
dbm = self.get_diagonal_bonded_matrix(self.get_bonded_matrix())
elec_sa = self.terms[0][0].get_score_array()*self.terms[0][1]*dbm
vdw_sa = self.terms[1][0].get_score_array()*self.terms[1][1]*dbm
hb_sa = self.terms[2][0].get_score_array()*self.terms[2][1]*dbm
dsolv_sa = self.terms[3][0].get_score_array()*self.terms[3][1]*dbm
dist_a = self.ms.get_dist_mat(0,0)
if filename is not None:
fptr = open(filename, 'w')
for i in range(num_atoms):
for j in range(i+1, num_atoms):
if dbm[i][j]==0: continue
elec = round(elec_sa[i][j],4)
vdw = round(vdw_sa[i][j],4)
hb = round(hb_sa[i][j],4)
dsolv = round(dsolv_sa[i][j],4)
dist = round(dist_a[i][j],2)
tot = elec + vdw + hb + dsolv
vdwhb = vdw + hb
ostr = "%d % 2d-%2d % 6.2f % +7.4f % +6.4f % +6.4f % +6.4f" %(ctr,i+1,j+1,dist, tot,elec,vdwhb,dsolv)
print ostr
if filename:
ostr += '\n'
fptr.write(ostr)
ctr += 1
if filename:
fptr.close()
def get_score_array(self):
bonded_matrix = self.get_bonded_matrix()
#score_array = WeightedMultiTerm.get_score_array(self)
diagonal_bonded_matrix = self.get_diagonal_bonded_matrix(bonded_matrix)
mask = diagonal_bonded_matrix
#have to get each score_array and apply appropriate mask
t = self.terms[0]
if t[0].symmetric is False:
mask = bonded_matrix
array = t[0].get_score_array() * t[1] * mask
if len(self.terms)>1:
for term, weight in self.terms[1:]:
mask = diagonal_bonded_matrix
if term.symmetric is False:
mask = bonded_matrix
array = array + term.get_score_array() * weight * mask
#return score_array which is already filtered by bonded_matrix
return array
def get_score_per_term(self):
bonded_matrix = self.get_bonded_matrix()
diagonal_bonded_matrix = self.get_diagonal_bonded_matrix(bonded_matrix)
scorelist = []
for term, weight in self.terms:
mask = diagonal_bonded_matrix
if term.symmetric is False:
mask = bonded_matrix
#scorelist.append( weight*term.get_score() )
#term_array = weight*term.get_score_array()*bonded_matrix
term_array = weight*term.get_score_array()*mask
scorelist.append(Numeric.add.reduce(Numeric.add.reduce(term_array)))
return scorelist
def get_score(self):
return Numeric.add.reduce(Numeric.add.reduce(self.get_score_array()))
def get_diagonal_bonded_matrix(self, mask):
#make it zero on and below the diagonal
for i in range(len(mask[0])):
for j in range(0, i):
mask[i][j] = 0
return mask
def get_bonded_matrix(self, entities=None):
"""return array of floats 1. means non-bonded, 0. means bonded
bonded means 1-1, 1-2, or 1-3
"""
if entities is None:
entities = self.ms.get_entities(self.ms.configuration[0])
atoms = entities.findType(Atom)
lenAts = len(atoms)
# initialize an lenAts-by-lenAts array of False
#mat = [[False]*lenAts]*lenAts
mask = Numeric.ones((lenAts, lenAts), 'f')
for a1 in atoms:
# mark 1-1 interactions (yourself)
ind1 = atoms.index(a1)
mask[ind1,ind1] = 0.
# mark 1-2 interactions (your one-bond neighbors)
for b in a1.bonds:
a2 = b.atom1
if id(a2)==id(a1):
a2 = b.atom2
ind2 = atoms.index(a2)
mask[ind1,ind2] = 0.
mask[ind2,ind1] = 0.
# mark 1-3 interactions (your neighbors' neighbors)
for b2 in a2.bonds:
a3 = b2.atom1
if id(a3)==id(a2): a3 = b2.atom2
if id(a3)==id(a1): continue
ind3 = atoms.index(a3)
mask[ind1,ind3] = 0.
mask[ind3,ind1] = 0.
if self.exclude_one_four:
for b3 in a3.bonds:
a4 = b3.atom1
if id(a4)==id(a3):
a4 = b3.atom2
if id(a4)==id(a2): continue
if id(a4)==id(a1): continue
ind4 = atoms.index(a4)
mask[ind1,ind4] = 0.
mask[ind4,ind1] = 0.
if self.weed_bonds:
mask = self.weedbonds(mask)
return mask
def weedbonds(self, mask):
#mask = self.get_bonded_matrix(entities)
entities = self.ms.get_entities(self.ms.configuration[0])
atoms = entities.findType(Atom)
lenAts = len(atoms)
mols = atoms.top.uniq()
for m in mols:
if not hasattr(m, 'torTree'):
continue
l = []
atL = m.torTree.rootNode.atomList
#print 'setting 0 for rootNode atomList:', atL
for i in atL:
for j in atL:
mask[i][j] = 0
for n in m.torTree.torsionMap:
atL = n.atomList[:]
atL.extend(n.bond)
#print 'setting 0 for atomList:', atL
for i in atL:
for j in atL:
mask[i][j] = 0
print
return mask
def print_mask(self, mask):
I, J = mask.shape
for i in range(I):
for j in range(J):
print int(mask[i][j]),
print
####
#### Unittests (to be moved away later)
####
###import unittest
###from PyAutoDock.Tests.test_scorer import ScorerTest
###from MolKit import Read
###class InternalEnergyTest(ScorerTest):
### def setUp(self):
### pass
### def tearDown(self):
### pass
### def test_d1_new(self):
### """InternalEnergy refactored to subclass WeightedMultiTerm
### """
### # create the MolecularSystem
### filename = 'Tests/Data/d1.pdbqs'
### d1 = Read(filename)
### d1[0].buildBondsByDistance()
### ms = MolecularSystem()
### ms.add_entities(d1.allAtoms) # only add it once
### # create the InternalEnergy term
### iec = InternalEnergy()
### iec.add_term( VanDerWaals(), 0.1485 )
### # put the MolecularSystem and the scorer together
### print "MS?", isinstance(ms, MolecularSystem)
### iec.set_molecular_system(ms)
###
### score = iec.get_score()
### score_array = iec.get_score_array()
### #print "Internal Energy of %s: %14.10f\n" % (filename, score)
###
### #self.assertFloatEqual( score, 0.116998674, 4)
### #3/23/2005: diagonal result is HALF of previous value
### self.assertFloatEqual( score, 0.116998674/2.0, 4)
### def test_d1_all_terms(self):
### # create the MolecularSystem
### filename = 'Tests/Data/d1.pdbqs'
### d1 = Read(filename)
### d1[0].buildBondsByDistance()
### ms = MolecularSystem()
### ms.add_entities(d1.allAtoms) # only add it once
### # create the InternalEnergy term
### iec = InternalEnergy()
### iec.add_term( VanDerWaals(), 0.1485 )
### iec.add_term( HydrogenBonding(), 0.0656, symmetric=False )
### iec.add_term( Electrostatics(), 0.1146 )
### iec.add_term( Desolvation(), 0.1711, symmetric=False )
### # put the MolecularSystem and the scorer together
### iec.set_molecular_system(ms)
###
### score = iec.get_score()
### print "Internal Energy of %s: %14.10f\n" % (filename, score)
### #score_array = iec.get_score_array()
### score_list = iec.get_score_per_term()
### print "VanDerWaals=", score_list[0]
### #self.assertFloatEqual( score_list[0], 0.117, 4)
### #3/23/2005: diagonal result is HALF of previous value
### self.assertFloatEqual( score_list[0], 0.117/2.0, 4)
### #??hb was -0.2411... now is -0.2400....????
### #self.assertFloatEqual( score_list[1],-0.2411, 4)
### print "HydrogenBonding=", score_list[1]
### #3/23/2005: diagonal result is NOT HALF of previous value???
### self.assertFloatEqual( score_list[1],-0.2400, 4)
### print "Electrostatics=", score_list[2]
### #self.assertFloatEqual( score_list[2], 0.6260, 4)
### #3/23/2005: diagonal result is HALF of previous value
### self.assertFloatEqual( score_list[2], 0.6260/2., 4)
### print "Desolvation=", score_list[3]
### #self.assertFloatEqual( score_list[3], 1.416, 4)
### #3/23/2005: diagonal result is NOT HALF of previous value!!!
### #BECAUSE AD3 DESOLVATION IS NOT SYMMETRIC!!!!
### self.assertFloatEqual( score_list[3], 1.416, 4)
### #3/23/2005: diagonal result is NOT HALF of previous value
### #because HydrogenBonding and Desolvation were not..
### #self.assertFloatEqual( score, 1.9179/2., 4)
### newsum = 0.117/2. -0.2400 + .6260/2. + 1.416
### self.assertFloatEqual( score, newsum, 4)
### def test_d1_new_terms(self):
### # create the MolecularSystem
### filename = 'Tests/Data/d1.pdbqt'
### filename = 'Tests/Data/piece_d1.pdbqt'
### d1 = Read(filename)
### d1[0].buildBondsByDistance()
### ms = MolecularSystem()
### ms.add_entities(d1.allAtoms) # only add it once
### # create the InternalEnergy terms
### iec = InternalEnergy(exclude_one_four=True)
### iec.add_term( NewVanDerWaals(), 1. )
### iec.add_term( NewHydrogenBonding12_10(), 1. ) #this is hydrogenbonding
### #iec.add_term( NewHydrogenBonding(), 0.0656 )
### iec.add_term( Electrostatics(), 0.0091 )
### iec.add_term( NewDesolvation(), 0.0174 )
### # put the MolecularSystem and the scorer togethern
### iec.set_molecular_system(ms)
###
### score = iec.get_score()
### # correct scores from
### #score=0.0959013722
### print "Internal Energy of %s: %14.10f\n" % (filename, score)
### #score_array = iec.get_score_array()
### score_list = iec.get_score_per_term()
### #print "VanDerWaals=", score_list[0]
### #self.assertFloatEqual( score_list[0], 0.117, 4)
### #print "HydrogenBonding=", score_list[1]
### #self.assertFloatEqual( score_list[1],-0.2411, 4)
### #print "Electrostatics=", score_list[2]
### #self.assertFloatEqual( score_list[2], 0.6260, 4)
### #print "Desolvation=", score_list[3]
### #self.assertFloatEqual( score_list[3], 1.416, 4)
### #without the Desolvation term the total is 0.5019
### #self.assertFloatEqual( score, 0.5019, 4)
### #self.assertFloatEqual( score, 1.9179, 4)
### #VanDerWaals= 0.0282212653592
### #HydrogenBonding= -0.00653238892803
### #Electrostatics= 0.0497082608073
### #Desolvation= 0.0245042349353
### print "NewVanDerWaals=", score_list[0]
### #self.assertFloatEqual( score_list[0], 0.117, 4)
### print "NewHydrogenBonding12_10=", score_list[1]
### #self.assertFloatEqual( score_list[1],-0.2411, 4)
### print "Electrostatics=", score_list[2]
### #self.assertFloatEqual( score_list[2], 0.6260, 4)
### print "NewDesolvation=", score_list[3]
### #self.assertFloatEqual( score_list[3], 1.416, 4)
### def test_piece_d1_new_terms(self):
### # create the MolecularSystem
### filename = 'Tests/Data/piece_d1.pdbqt'
### d1 = Read(filename)
### d1[0].buildBondsByDistance()
### ms = MolecularSystem()
### ms.add_entities(d1.allAtoms) # only add it once
### # create the InternalEnergy terms
### iec = InternalEnergy(exclude_one_four=True)
### #iec.add_term( NewVanDerWaals(), 1. )
### iec.add_term( NewVanDerWaals(), 1. )
### iec.add_term( NewHydrogenBonding12_10(), 1. ) #this is hydrogenbonding
### #iec.add_term( NewHydrogenBonding(), 0.0656 )
### iec.add_term( Electrostatics(), 1. )
### iec.add_term( NewDesolvation(), 1. )
### # put the MolecularSystem and the scorer togethern
### iec.set_molecular_system(ms)
###
### score = iec.get_score()
### score_list = iec.get_score_per_term()
###
### # correct scores from @@ where are these from, again??
### #ie_score = -0.4292339075
### #vdw_score = -0.427359240096
### #hbond_score = 0.0
### #estat_score = -0.00255480130265
### #dsolv_score = 0.0006801339114
### #9/24 weightless scores:
### ie_score = -2.66669923187 #changed 9/24
### vdw_score = -2.7696645502 #changed 9/24
### hbond_score = 0.0
### estat_score = -0.280747395895 #changed 9/24
### dsolv_score = 0.383712714226 #changed 9/24
### #print "score_list="
### #for ix, t in enumerate(score_list):
### #print ix,':', t
### #print " total=", Numeric.add.reduce(score_list)
### # check (pre)-calculated and returned values...
### #3/23/2005: diagonal results are HALF of previous values
### self.assertAlmostEqual(vdw_score/2.0, score_list[0])
### self.assertAlmostEqual(hbond_score/2.0, score_list[1])
### self.assertAlmostEqual(estat_score/2.0, score_list[2])
### self.assertAlmostEqual(dsolv_score/2.0, score_list[3])
### self.assertAlmostEqual(ie_score/2.0, score)
### def test_no_terms(self):
### """InternalEnergy with no terms
### """
### # create the MolecularSystem
### filename = 'Tests/Data/d1.pdbqs'
### d1 = Read(filename)[0]
### d1.buildBondsByDistance()
### ms = MolecularSystem()
### ms.add_entities(d1.allAtoms)
### ms.add_entities(d1.allAtoms)
###
### # create the InternalEnergy term
### iec = InternalEnergy()
### # self.add_term( VanDerWaals(), 0.1485 )
### # put the MolecularSystem and the scorer togethern
### iec.set_molecular_system(ms)
###
### self.assertRaises( IndexError, iec.get_score )
###if __name__ == '__main__':
### unittest.main()
```
#### File: MGLToolsPckgs/PyAutoDock/MolecularSystem.py
```python
from MolKit.molecule import AtomSet, Atom
from MolecularSystemAdapter import Adapters
import numpy.oldnumeric as Numeric
from math import sqrt
import types
class AbstractMolecularSystem:
"""This class defines the interface that a MolecularSystem must support
for use with a Scorer or other object(s). This class maintains a list of
sets of entities (like Atoms).
The get_supported_attributes method returns the list of attributes that
each Entity supports.
A distance matrix is maintained pairwise by set and pairwise by entities
within the set. NB: is actually the distance, **not** distance-squared.
The reason for this is that for clients (like WeightedMultiTerm scorers)
who must get_dist_mat repeatedly, forcing them to take the sqrt for each
term is a false economy.
An index is returned when adding a set of entities (by the add_entities method).
This index for an entity set can also be found using the get_entity_set_index method.
The molecular system attribute configuration is a 2-tuple of validated
entity_set_index. In its use, the Autodock scorer uses the first as the Receptor
and second as the Ligand.
This class is intended to abstract any number of underlying molecular
representations such as MolKit, mmLib, MMTK, or just a PDB file. The
underlying molecular representation is abstracted as a list of entities
which support the 'supported_attributes'. So, for instance, if your molecular
representation doesn't have charges, its abstraction as a specialized
implementation of this interface (ie the subclass of MolecularSystemBase)
may have to calculate per entity charges.
"""
def __init__(self): pass
def add_entities(self, entity_set, coords_access_func=None): pass
def get_entity_set_index(self, entity_set): pass
def set_coords(self, entity_set_index, coords): pass
def get_dist_mat(self, ix, jx): pass
def clear_dist_mat(self, ix): pass
def get_supported_attributes(self): pass
def check_required_attributes(self, entity_set_index, attribute_list): pass
# @@ do we want to support the following interface??
def get_coords(self, entity_set_index): pass
# @@ or do we want to support the following interface??
def get_entities(self, entity_set_num): pass
def set_configuration(self, ix=None, jx=None ): pass
class MolecularSystem(AbstractMolecularSystem):
"""concrete subclass implementation of AbstractMolecularSystem
"""
def __init__(self, e_set=None, coords_access_func=None):
AbstractMolecularSystem.__init__(self)
self.entity_sets = []
self._dist_mats = {}
# key is entity_set_index: values is dict
# with key second entity_set_index, value distance mat
# _dist_mat holds the square of distances between pairs of
# entities, Distance matrices get computed only when needed
self.configuration = (None, None)
self.coords_access_func_list = []
if e_set is not None:
self.add_entities(e_set, coords_access_func)
# single entity_set results in configuration of (0,0)
# self.configuration = (0, None)
def get_entity_set_index(self, entity_set):
return self.entity_sets.index(entity_set)
def _validate_entity_set_index(self, entity_set_ix):
assert (entity_set_ix < len(self.entity_sets)), \
"Invalid entity_set_index: %d; only %d entity_sets." % \
(entity_set_ix, len(self.entity_sets) )
def get_supported_attributes(self):
raise NotImplementedError
# for check_required_attributes
# the hydrogen bonding term has the required attr of bonds
# for subsetA, so when we implement this make sure that
# 1. bonds is on the attribute_list when Hbonding is involved
# 2. that subsetA does have bonds (or build them!)
#
# this also raises the issue that not all atom_sets need all attributes
# to support a specific scorer term.
#
# also, for desolvation subsetA needs AtVols
def check_required_attributes(self, entity_set_index, attribute_list):
"""Check that all the elements of the given entity_set have all
the attributes in the attribute_list.
"""
# get_entities will validate entity_set_index
entities = self.get_entities( entity_set_index)
if type(entities) == types.GeneratorType:
# @@ figure out how to check generator attributes !!
return
# check each attribute
typeList = [types.ListType, types.DictType]#, types.InstanceType]
from mglutil.util.misc import isInstance
for attr in attribute_list:
# get returns the subset of entities
# for which the expression is true
ents = entities.get( lambda x: hasattr(x, attr))
if ents==None or len(ents)!=len(entities):
raise AttributeError, \
"All Entities do not have required Entity attribute (%s) " % attr
ent0 = entities[0]
if type(getattr(ent0, attr)) in typeList \
or isInstance(getattr(ent0, attr)) is True:
if len(getattr(ent0, attr))==0:
raise ValueError, \
"Required Entity attribute (%s) has zero length" % attr
def _compute_distance_matrix(self, ix, jx):
"""Compute the distance matrix for the given sets
This method should be called from within the class by get_dist_mat
which knows when it's really necessary.
"""
# straight forward distance matrix calculation
mat = []
for c1 in self.get_coords(ix):
l = []
cx, cy, cz = c1
mat.append(l)
for c2 in self.get_coords(jx):
c2x, c2y, c2z = c2
d = cx-c2x, cy-c2y, cz-c2z
l.append(sqrt( d[0]*d[0]+d[1]*d[1]+d[2]*d[2]) )
return mat
def check_distance_cutoff(self, ix, jx, cutoff):
"""check if a distance in the distance matrix for the specified sets
is below a user specified cutoff.
If the distance matrix does not exist if is computed up to the first encounter
of a distance below the cutoff. If such a distance is encountered it is
returned. If the matrix exists the minimum distance is returned if it is below
the cutoff. If distance are all above the cutoff, None is returned.
"""
mat = self._dist_mats[ix][jx]
if mat is None:
mat = self._dist_mats[jx][ix]
result = None
if mat is None:
mat = []
for e1 in self.get_entities(ix):
l = []
cx, cy, cz = e1.coords
mat.append(l)
for e2 in self.get_entities(jx):
c2x, c2y, c2z = e2.coords
d = cx-c2x, cy-c2y, cz-c2z
dist = sqrt( d[0]*d[0]+d[1]*d[1]+d[2]*d[2])
if dist < cutoff:
return dist
l.append( dist)
#if the whole dist matrix is ok, save it
self._dist_mats[ix][jx] = mat
else:
mini = min( map( min, mat))
if mini < cutoff:
result = mini
return result
def get_dist_mat(self, ix, jx):
"""return the distance matrix for the given two sets
"""
mat = self._dist_mats[ix][jx]
tmat = self._dist_mats[jx][ix]
if not mat:
if tmat:
# we just transpose
#mat = Numeric.swapaxes(Numeric.array(tmat), 0, 1).tolist()
mat = [] #eg: 3x4->4x3
for j in xrange(len(tmat[0])):
mat.append([])
for i in xrange(len(tmat)):
mat[j].append(tmat[i][j])
else:
# we must compute
mat = self._compute_distance_matrix(ix,jx)
self._dist_mats[ix][jx] = mat
return mat
def clear_dist_mat(self, ix):
"""clear all distance-squared matrices for the given entity_set
"""
# first clear all the pairs where entity_set is the first key
for set in self._dist_mats[ix].keys():
self._dist_mats[ix][set] = None
# now clear all matrices where entity_set is the second key
for set in self._dist_mats.keys():
self._dist_mats[set][ix] = None
def set_configuration(self, ix=None, jx=None ):
"""For now this is a 2-tuple of entity_set_index that describes
for a scorer which two entity sets are being considered with respect to
one another.
"""
if ix is not None:
self._validate_entity_set_index(ix)
self.configuration = tuple( [ix, self.configuration[1]] )
if jx is not None:
self._validate_entity_set_index(jx)
self.configuration = tuple( [self.configuration[0], jx] )
def add_entities(self, entity_set, coords_access_func=None):
"""add a MolKit.EntitySet to the MolecularSystem
Returns the entity_set_num for the new EntitySet. First two calls to
add_entities set the configuration to use those EntitySets.
"""
entity_set_ix = len(self.entity_sets)
# initialize the dictionary of distance matricies for this set
self._dist_mats[entity_set_ix] = {}
# create an adapter for this entity_set ...
adapter = Adapters[str(entity_set.__class__)](entity_set)
# adapter = MolecularSystemAdapter( entity_set)
# ... and add it to the entity_sets list
self.entity_sets.append(adapter)
# add the coords_access_func
self.coords_access_func_list.append(coords_access_func)
# create a new dict for every set vs. this one
for ix, set in enumerate(self.entity_sets):
self._dist_mats[ix][entity_set_ix] = None
self._dist_mats[entity_set_ix][ix] = None
# set the configuration (only on the first two calls)
if entity_set_ix == 0:
self.set_configuration( ix = entity_set_ix)
# single entity_set results in configuration of (0,0)
self.set_configuration( jx = entity_set_ix)
elif entity_set_ix == 1:
self.set_configuration( jx = entity_set_ix)
return entity_set_ix
def get_entities(self, entity_set_ix=0):
"""return the specified entity_set.
entity_set_ix is an integer that indexes into self.entity_sets"""
# make sure the entity_set_index is valid
self._validate_entity_set_index(entity_set_ix)
return self.entity_sets[entity_set_ix].get_iterator()
# @@ ISSUE: should the MolecularSystem maintain the coordinates
# @@ as state. OR, should this actually change the values in whatever
# @@ underlying Molecule representation that there is ??
#
# for now set_coords changes the MolKit values
def set_coords(self, entity_set_ix, coords, coords_set_func=None):
"""provide new coords for the specified entitySet.
entity_set_ix is the index of an existing entitySet.
coords is a list (of proper length) of anything you want to use
to update coordinate with the coords_set_func you supply.
"""
# validate input
self._validate_entity_set_index(entity_set_ix)
# assert <that coords is a list of coordinates>
# check compatibility
assert len(coords)==len(self.get_entities(entity_set_ix))
if coords_set_func:
for ex, e in enumerate(self.get_entities(entity_set_ix)):
coords_set_func(e, coords[ex])
else:
#NB: this is MolKit AtomSet specific
self.get_entities(entity_set_ix).updateCoords(coords)
# clear distance matrix
self.clear_dist_mat(entity_set_ix)
def get_coords(self, entity_set_ix=0):
"""return the coordinates of the specified entity_set.
DEPRECATED: use get_entities().coords instead.
entity_set_ix is an integer that indexes into self.entity_sets
"""
# raise DeprecationWarning, "use get_entities().coords instead"
# validate input
self._validate_entity_set_index(entity_set_ix)
# get the coordinates accessor function
accessor = self.coords_access_func_list[entity_set_ix]
if accessor:
coords = [accessor(e) for e in self.get_entities(entity_set_ix)]
else:
#in case getattr hasnot been overridden:
coords = [e.coords for e in self.get_entities(entity_set_ix)]
return coords
# MolecularSystem
if __name__ == '__main__':
print "unittests in Tests/test_MolecularSystem.py"
```
#### File: MGLToolsPckgs/pyglf/glf.py
```python
import _glf
import new
new_instancemethod = new.instancemethod
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import types
try:
_object = types.ObjectType
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
del types
glfGet3DSolidStringTriangles = _glf.glfGet3DSolidStringTriangles
GLF_ERROR = _glf.GLF_ERROR
GLF_OK = _glf.GLF_OK
GLF_YES = _glf.GLF_YES
GLF_NO = _glf.GLF_NO
GLF_CONSOLE_MESSAGES = _glf.GLF_CONSOLE_MESSAGES
GLF_TEXTURING = _glf.GLF_TEXTURING
GLF_CONTOURING = _glf.GLF_CONTOURING
GLF_LEFT_UP = _glf.GLF_LEFT_UP
GLF_LEFT_CENTER = _glf.GLF_LEFT_CENTER
GLF_LEFT_DOWN = _glf.GLF_LEFT_DOWN
GLF_CENTER_UP = _glf.GLF_CENTER_UP
GLF_CENTER_CENTER = _glf.GLF_CENTER_CENTER
GLF_CENTER_DOWN = _glf.GLF_CENTER_DOWN
GLF_RIGHT_UP = _glf.GLF_RIGHT_UP
GLF_RIGHT_CENTER = _glf.GLF_RIGHT_CENTER
GLF_RIGHT_DOWN = _glf.GLF_RIGHT_DOWN
GLF_CENTER = _glf.GLF_CENTER
GLF_LEFT = _glf.GLF_LEFT
GLF_RIGHT = _glf.GLF_RIGHT
GLF_UP = _glf.GLF_UP
GLF_DOWN = _glf.GLF_DOWN
GLF_CONSOLE_CURSOR = _glf.GLF_CONSOLE_CURSOR
glfInit = _glf.glfInit
glfClose = _glf.glfClose
glfLoadFont = _glf.glfLoadFont
glfLoadBMFFont = _glf.glfLoadBMFFont
glfUnloadFont = _glf.glfUnloadFont
glfUnloadBMFFont = _glf.glfUnloadBMFFont
glfUnloadFontD = _glf.glfUnloadFontD
glfUnloadBMFFontD = _glf.glfUnloadBMFFontD
glfDrawWiredSymbol = _glf.glfDrawWiredSymbol
glfDrawWiredString = _glf.glfDrawWiredString
glfDrawSolidSymbol = _glf.glfDrawSolidSymbol
glfDrawSolidString = _glf.glfDrawSolidString
glfDraw3DWiredSymbol = _glf.glfDraw3DWiredSymbol
glfDraw3DWiredString = _glf.glfDraw3DWiredString
glfDraw3DSolidSymbol = _glf.glfDraw3DSolidSymbol
glfDraw3DSolidString = _glf.glfDraw3DSolidString
glfStartBitmapDrawing = _glf.glfStartBitmapDrawing
glfStopBitmapDrawing = _glf.glfStopBitmapDrawing
glfDrawBSymbol = _glf.glfDrawBSymbol
glfDrawBString = _glf.glfDrawBString
glfDrawBMaskSymbol = _glf.glfDrawBMaskSymbol
glfDrawBMaskString = _glf.glfDrawBMaskString
glfDrawWiredSymbolF = _glf.glfDrawWiredSymbolF
glfDrawWiredStringF = _glf.glfDrawWiredStringF
glfDrawSolidSymbolF = _glf.glfDrawSolidSymbolF
glfDrawSolidStringF = _glf.glfDrawSolidStringF
glfDraw3DWiredSymbolF = _glf.glfDraw3DWiredSymbolF
glfDraw3DWiredStringF = _glf.glfDraw3DWiredStringF
glfDraw3DSolidSymbolF = _glf.glfDraw3DSolidSymbolF
glfDraw3DSolidStringF = _glf.glfDraw3DSolidStringF
glfGetStringBoundsF = _glf.glfGetStringBoundsF
glfGetStringBounds = _glf.glfGetStringBounds
glfSetSymbolSpace = _glf.glfSetSymbolSpace
glfGetSymbolSpace = _glf.glfGetSymbolSpace
glfSetSpaceSize = _glf.glfSetSpaceSize
glfGetSpaceSize = _glf.glfGetSpaceSize
glfSetSymbolDepth = _glf.glfSetSymbolDepth
glfGetSymbolDepth = _glf.glfGetSymbolDepth
glfSetCurrentFont = _glf.glfSetCurrentFont
glfSetCurrentBMFFont = _glf.glfSetCurrentBMFFont
glfGetCurrentFont = _glf.glfGetCurrentFont
glfGetCurrentBMFFont = _glf.glfGetCurrentBMFFont
glfSetAnchorPoint = _glf.glfSetAnchorPoint
glfSetContourColor = _glf.glfSetContourColor
glfEnable = _glf.glfEnable
glfDisable = _glf.glfDisable
glfSetConsoleParam = _glf.glfSetConsoleParam
glfSetConsoleFont = _glf.glfSetConsoleFont
glfConsoleClear = _glf.glfConsoleClear
glfPrint = _glf.glfPrint
glfPrintString = _glf.glfPrintString
glfPrintChar = _glf.glfPrintChar
glfConsoleDraw = _glf.glfConsoleDraw
glfSetCursorBlinkRate = _glf.glfSetCursorBlinkRate
glfStringCentering = _glf.glfStringCentering
glfGetStringCentering = _glf.glfGetStringCentering
glfBitmapStringCentering = _glf.glfBitmapStringCentering
glfBitmapGetStringCentering = _glf.glfBitmapGetStringCentering
glfStringDirection = _glf.glfStringDirection
glfGetStringDirection = _glf.glfGetStringDirection
glfSetRotateAngle = _glf.glfSetRotateAngle
glfSetBRotateAngle = _glf.glfSetBRotateAngle
cvar = _glf.cvar
```
#### File: MGLToolsPckgs/sff/amber.py
```python
import _prmlib as prmlib
import re
import os
import numpy.oldnumeric as Numeric
from types import StringType
realType = Numeric.Float
intType = Numeric.Int
pyArrayInt = prmlib.PyArray_INT
pyArrayDouble = prmlib.PyArray_DOUBLE
getpat = re.compile( 'parmstruct_(\w+)_get')
parmattrs = {}
for x in dir( prmlib):
match = getpat.match( x)
if match:
parmattrs[ match.group( 1) ] = None
parmbuffers = {
'AtomNames': (StringType, lambda x: x.Natom * 4 + 81, None),
'Charges': (realType, lambda x: x.Natom, pyArrayDouble ),
'Masses': (realType, lambda x: x.Natom, pyArrayDouble),
'Iac': (intType, lambda x: x.Natom, pyArrayInt),
'Iblo': (intType, lambda x: x.Natom, pyArrayInt),
'Cno': (intType, lambda x: x.Ntype2d, pyArrayInt),
'ResNames': (StringType, lambda x: x.Nres * 4 + 81, None),
'Ipres': (intType, lambda x: x.Nres + 1, pyArrayInt),
'Rk': (realType, lambda x: x.Numbnd, pyArrayDouble),
'Req': (realType, lambda x: x.Numbnd, pyArrayDouble),
'Tk': (realType, lambda x: x.Numang, pyArrayDouble),
'Teq': (realType, lambda x: x.Numang, pyArrayDouble),
'Pk': (realType, lambda x: x.Nptra, pyArrayDouble),
'Pn': (realType, lambda x: x.Nptra, pyArrayDouble),
'Phase': (realType, lambda x: x.Nptra, pyArrayDouble),
'Solty': (realType, lambda x: x.Natyp, pyArrayDouble),
'Cn1': (realType, lambda x: x.Nttyp, pyArrayDouble),
'Cn2': (realType, lambda x: x.Nttyp, pyArrayDouble),
'Boundary': (intType, lambda x: x.Nspm, pyArrayInt),
'BondHAt1': (intType, lambda x: x.Nbonh, pyArrayInt),
'BondHAt2': (intType, lambda x: x.Nbonh, pyArrayInt),
'BondHNum': (intType, lambda x: x.Nbonh, pyArrayInt),
'BondAt1': (intType, lambda x: x.Nbona, pyArrayInt),
'BondAt2': (intType, lambda x: x.Nbona, pyArrayInt),
'BondNum': (intType, lambda x: x.Nbona, pyArrayInt),
'AngleHAt1': (intType, lambda x: x.Ntheth, pyArrayInt),
'AngleHAt2': (intType, lambda x: x.Ntheth, pyArrayInt),
'AngleHAt3': (intType, lambda x: x.Ntheth, pyArrayInt),
'AngleHNum': (intType, lambda x: x.Ntheth, pyArrayInt),
'AngleAt1': (intType, lambda x: x.Ntheta, pyArrayInt),
'AngleAt2': (intType, lambda x: x.Ntheta, pyArrayInt),
'AngleAt3': (intType, lambda x: x.Ntheta, pyArrayInt),
'AngleNum': (intType, lambda x: x.Ntheta, pyArrayInt),
'DihHAt1': (intType, lambda x: x.Nphih, pyArrayInt),
'DihHAt2': (intType, lambda x: x.Nphih, pyArrayInt),
'DihHAt3': (intType, lambda x: x.Nphih, pyArrayInt),
'DihHAt4': (intType, lambda x: x.Nphih, pyArrayInt),
'DihHNum': (intType, lambda x: x.Nphih, pyArrayInt),
'DihAt1': (intType, lambda x: x.Nphia, pyArrayInt),
'DihAt2': (intType, lambda x: x.Nphia, pyArrayInt),
'DihAt3': (intType, lambda x: x.Nphia, pyArrayInt),
'DihAt4': (intType, lambda x: x.Nphia, pyArrayInt),
'DihNum': (intType, lambda x: x.Nphia, pyArrayInt),
'ExclAt': (intType, lambda x: x.Nnb, pyArrayInt),
'HB12': (realType, lambda x: x.Nphb, pyArrayDouble),
'HB10': (realType, lambda x: x.Nphb, pyArrayDouble),
'Box': (realType, lambda x: 3, pyArrayDouble),
'AtomSym': (StringType, lambda x: x.Natom * 4 + 81, None),
'AtomTree': (StringType, lambda x: x.Natom * 4 + 81, None),
'TreeJoin': (intType, lambda x: x.Natom, pyArrayInt),
'AtomRes': (intType, lambda x: x.Natom, pyArrayInt),
'N14pairs': (intType, lambda x: x.Natom, pyArrayInt),
'N14pairlist': (intType, lambda x: 10*x.Natom, pyArrayInt),
}
def checkbuffersize( parmobj, attr, value):
attrlen = parmbuffers[ attr][ 1]( parmobj)
if attr in ['AtomNames', 'AtomSym', 'AtomTree']:
attrlen = parmobj.Natom * 4
elif attr == 'ResNames':
attrlen = parmobj.Nres * 4
elif attr == 'Ipres':
attrlen = parmobj.Nres
elif attr == 'N14pairlist':
from operator import add
sum = reduce( add, parmobj.N14pairs )
attrlen = sum
if sum!=len(value):
print 'WARNING: N14pairlist length'
attrlen = len(value)
if len( value) < attrlen:
raise ValueError( attr, attrlen, len( value))
class AmberParm:
def __init__( self, name, parmdict=None):
"""
name - string
parmdict - map
"""
import types
self.name = name
if parmdict:
parmptr = self._parmptr_ = prmlib.parmcalloc()
for name in parmattrs.keys():
value = parmdict[ name]
try:
bufdesc = parmbuffers[ name]
except KeyError:
pass
else:
if bufdesc[ 0] != StringType\
and not isinstance( value, StringType):
value = Numeric.array( value).astype(bufdesc[ 0])
self.__dict__[ name] = value
if name == 'Box':
self.Box[:] = value
else:
getattr( prmlib, 'parmstruct_%s_set' % name)( parmptr, value)
else:
assert os.path.exists( name )
self._parmptr_ = parmptr = prmlib.readparm( name)
for attr in filter( lambda x: not parmbuffers.has_key( x),
parmattrs.keys()):
value = getattr( prmlib, 'parmstruct_%s_get' % attr)( parmptr)
self.__dict__[ attr] = value
for attr in filter( lambda x: parmbuffers.has_key( x),
parmattrs.keys()):
# these _get() functions must not be called from anywhere else
#print "attr:", attr,
value = getattr( prmlib, 'parmstruct_%s_get' % attr)( parmptr)
#print "value: ", value
if value is None:
value = ()
else:
bufdesc = parmbuffers[ attr]
if bufdesc[ 0] != StringType:
value = prmlib.createNumArr(value, bufdesc[ 1]( self), bufdesc[2])
self.__dict__[ attr] = value
if __debug__:
for attr in parmbuffers.keys():
val = getattr(self, attr)
if isinstance(val, Numeric.ArrayType) or isinstance(val, StringType):
checkbuffersize(self, attr, val)
def __setattr__( self, name, value):
if parmattrs.has_key( name):
raise AttributeError( 'constant parm attribute')
self.__dict__[ name] = value
def __del__( self):
prmlib.parmfree( self._parmptr_)
delattr( self, '_parmptr_')
def asDict(self):
# return the content of the parm structure as a python dict
d = {}
for k in self.__dict__.keys():
if k[0]=='_': continue
if parmbuffers.has_key(k):
value = list(getattr(self, k))
else:
value = getattr(self, k)
d[k] = value
return d
import threading
amberlock = threading.RLock()
import struct
class BinTrajectory:
## WARNING nothing is done about byte order
def __init__(self, filename):
import os
assert os.path.isfile(filename)
self.filename = filename
self.typecode = 'f'
if prmlib.UseDouble:
self.typecode = 'd'
self.coordSize = struct.calcsize(self.typecode)
self.intSize = struct.calcsize('i')
self.fileHandle = None
def getNumberOfAtoms(self, filename):
f = open(filename, 'rb')
lenstr = f.read(struct.calcsize('i'))
f.close()
return struct.unpack('i', lenstr)[0]
def closeFile(self):
self.fileHandle.close()
self.fileHandle = None
def getNextConFormation(self):
# open file if necessary
if self.fileHandle is None:
self.fileHandle = open(self.filename)
# read the number of atoms as an integer
lenstr = self.fileHandle.read(self.intSize)
if len(lenstr) < self.intSize: #EOF reached
self.closeFile()
return None
nba = struct.unpack('i', lenstr)[0]
size = 3 * nba * self.coordSize
# read the coordinates for nba atoms
crdstr = self.fileHandle.read( size )
if len(crdstr) != size: #EOF reached
self.closeFile()
return None
c = Numeric.array( struct.unpack( '%dd'%3*nba, crdstr),
self.typecode )
c.shape = (-1, 3)
return c
class Amber94:
from MolKit import parm94_dat
def __init__(self, atoms, parmtop=None, prmfile=None, dataDict={}):
from MolKit.amberPrmTop import Parm
self.atoms = atoms
self.parmtop = parmtop
if prmfile:
self.oprm = AmberParm( prmfile )
else:
if self.parmtop is None:
# create parmtop info
if not len(dataDict):
self.parmtop = Parm()
else:
#dataDict is a dictionary with possible keys:
#allDictList, ntDictList, ctDictList
#whose values are lists of python files such as
#found in MolKit/data...which end in dat.py
#dataDict['allDictList']=[all_amino94_dat]
#if len(list)>1, the first is updated by the rest
self.parmtop = apply(Parm, (), dataDict)
self.parmtop.processAtoms(atoms, self.parm94_dat)
#this read is broken
#self.parmtop.loadFromFile(prmfile)
else:
assert isinstance(parmtop, Parm)
# create the C-data structure
self.oprm = AmberParm( 'test', self.parmtop.prmDict )
from operator import add
coords = self.atoms.coords[:]
lcoords = reduce( add, coords)
self.coords = Numeric.array( lcoords).astype(realType )
# create Numeric array for frozen
self.frozen = Numeric.zeros( self.oprm.Natom).astype(intType)
# create Numeric array for constrained
self.constrained = Numeric.zeros( self.oprm.Natom). astype(intType)
# create Numeric array for anchor
self.anchor = Numeric.zeros( 3*self.oprm.Natom).astype(realType)
# create Numeric array for minv (md)
self.minv = Numeric.zeros( 3*self.oprm.Natom).astype(realType )
# create Numeric array for v (md)
self.mdv = Numeric.zeros( 3*self.oprm.Natom).astype(realType)
# create Numeric array for f (md)
self.mdf = Numeric.zeros( 3*self.oprm.Natom).astype( realType )
# is the number of variables
self.nbVar = Numeric.array([3*self.oprm.Natom]).astype(intType)
# will contain the value of the objective function at the end
self.objFunc = Numeric.zeros( 1).astype(realType )
# return when sum of squares of gradient is less than dgrad
drms = 0.1
self.dgrad = Numeric.array([drms*3*self.oprm.Natom]).astype(realType)
# expected decrease in the function on the first iteration
self.dfpred = Numeric.array( [10.0,]).astype( realType )
#
self.maxIter = Numeric.array([500,]).astype(intType)
#
self.energies = Numeric.zeros(20).astype(realType )
# filename used to save trajectory
self.filename = None
self.sff_opts = prmlib.init_sff_options()
def setMinimizeOptions(self, **kw):
# WARNING when cut it set mme_init needs to be called to allocate a
# list of non-bonded paires of the proper size
for k,v in kw.items():
assert k in ['cut', 'nsnb', 'ntpr', 'scnb', 'scee',
'mme_init_first', 'dield', 'verbosemm',
'wcons']
#prmlib.mm_options(k, v)
#setattr(prmlib.cvar, k, v)
prmlib.mm_options(k, v, self.sff_opts)
def setMdOptions(self, **kw):
#nb: for the moment set verbosemm for verbosemd
for k,v in kw.items():
assert k in ['t', 'dt', 'tautp', 'temp0', 'boltz2', 'verbosemd',
'ntwx','vlimit', 'ntpr_md', 'zerov', 'tempi', 'idum' ]
#prmlib.md_options(k, v)
#setattr(prmlib.cvar, k, v)
prmlib.md_options(k, v, self.sff_opts)
def setCallback(self, func, frequency):
assert callable(func)
prmlib.set_callback(func, frequency, 0)
def freezeAtoms(self, atomIndices):
assert len(atomIndices)==len(self.atoms), 'atomIndices wrong length'
self.frozen = Numeric.array(atomIndices).astype(intType)
def constrainAtoms(self, atomIndices, anchor):
atlen = len(self.atoms)
assert len(atomIndices)==atlen, 'atomIndices wrong length'
#this is not right:
#constNum = Numeric.add.reduce(atomIndices)
#anchors have garbage for non-constrained atoms
assert len(anchor)==atlen*3, 'anchor wrong length'
self.constrained = Numeric.array(atomIndices).astype(intType)
self.anchor = Numeric.array(anchor).astype(realType)
def minimize(self, drms=None, maxIter=None, dfpred=None):
if drms is not None: self.dgrad[0] = drms*3*self.oprm.Natom
if maxIter is not None: self.maxIter[0] = maxIter
if dfpred is not None: self.dfpred[0] = dfpred
prmlib.mme_init(self.frozen, self.constrained, self.anchor,
None, self.oprm._parmptr_, self.sff_opts)
amberlock.acquire()
result_code = -6
try:
# add new thread here
result_code = prmlib.conjgrad( self.coords, self.nbVar, self.objFunc,
prmlib.mme_fun, self.dgrad, self.dfpred, self.maxIter,
self.oprm._parmptr_, self.energies, self.sff_opts )
finally:
amberlock.release()
return result_code
def md(self, maxStep, filename=None):
self.filename = filename
if filename is not None:
f = open(filename, 'w')
else:
f = None
prmlib.mme_init(self.frozen, self.constrained, self.anchor,
f, self.oprm._parmptr_, self.sff_opts)
amberlock.acquire()
result_code = -6
try:
# add new thread here
result_code = prmlib.md( 3*self.oprm.Natom, maxStep, self.coords,
self.minv, self.mdv, self.mdf,
prmlib.mme_fun, self.energies,
self.oprm._parmptr_ , self.sff_opts)
finally:
amberlock.release()
if filename is not None:
f.close()
return result_code
```
#### File: MGLToolsPckgs/symserv/utils.py
```python
def saveInstancesMatsToFile(filename, matrices):
"""
save a list of instance matrices to a file
status = saveInstancesMatsToFile(filename, matrices)
status will be 1 if it worked
"""
f = open(filename, 'w')
if not f:
return 0
for mat in matrices:
for v in mat.flatten():
f.write("%f "%v)
f.write("\n")
f.close()
return 1
import numpy
def readInstancesMatsFromFile(filename):
"""
read a list of instance matrices from a file
matrices = readInstancesMatsFromFile(filename)
"""
f = open(filename)
if not f:
return None
data = f.readlines()
f.close()
mats = []
for line in data:
mats.append( map(float, line.split()) )
mats = numpy.array(mats)
mats.shape = (-1,4,4)
return mats
```
#### File: MGLToolsPckgs/ViewerFramework/basicCommand.py
```python
import os, sys, subprocess
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.util.callback import CallBackFunction
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser, \
LoadButton, kbScrolledListBox
from mglutil.util.packageFilePath import findFilePath, \
findModulesInPackage, getResourceFolderWithVersion
import types, Tkinter, Pmw, os, sys, traceback
from string import join
import tkMessageBox
from ViewerFramework.VFCommand import Command, CommandGUI
import warnings
import string
commandslist=[]
cmd_docslist={}
def findAllVFPackages():
"""Returns a list of package names found in sys.path"""
packages = {}
for p in ['.']+sys.path:
flagline = []
if not os.path.exists(p) or not os.path.isdir(p):
continue
files = os.listdir(p)
for f in files:
pdir = os.path.join(p, f)
if not os.path.isdir(pdir):
continue
if os.path.exists( os.path.join( pdir, '__init__.py')) :
fptr =open("%s/__init__.py" %pdir)
Lines = fptr.readlines()
flagline =filter(lambda x:x.startswith("packageContainsVFCommands"),Lines)
if not flagline ==[]:
if not packages.has_key(f):
packages[f] = pdir
return packages
class UndoCommand(Command):
"""pops undo string from the stack and executes it in the ViewerFrameworks
scope
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : UndoCommand
\nCommand : Undo
\nSynopsis:\n
None <- Undo()
"""
def __init__(self, func=None):
Command.__init__(self, func)
self.ctr = 1 # used to assure unique keys for _undoArgs
self._undoArgs = {} # this dict is used to save large Python objects
# that we do not want to turn into strings
def get_ctr(self):
#used to build unique '_undoArg_#' strings
#cannot simply use len(self_undoArgs)+1
#because some entries may have been removed
# for instance, using len(self_undoArgs)+1 only
# add 1: _undoArg_1, add another: _undoArg_2
# remove _undoArg_1
# next addition would replicate _undoArg_2
if not len(self._undoArgs):
self.ctr = 1
else:
self.ctr += 1
return self.ctr
def saveUndoArg(self, arg):
"""Add arg to self._undoArgs under a unique name and returns this name
"""
name = '_undoArg_%d'%len(self._undoArgs)
i = 1
while self._undoArgs.has_key(name):
name = '_undoArg_%d'%(self.get_ctr())
i += 1
self._undoArgs[name] = arg
return name
def validateUserPref(self, value):
try:
val = int(value)
if val >-1:
return 1
else:
return 0
except:
return 0
def onAddCmdToViewer(self):
doc = """Number of commands that can be undone"""
if self.vf.hasGui:
TButton = self.vf.GUI.menuBars['Toolbar']._frame.toolbarButtonDict['Undo']
self.balloon = Pmw.Balloon(self.vf.GUI.ROOT)
self.balloon.bind(TButton, 'Undo')
self.setLabel()
self.vf.userpref.add( 'Number of Undo', 100,
validateFunc=self.validateUserPref,
doc=doc)
def doit(self):
if len(self.vf.undoCmdStack):
command = self.vf.undoCmdStack.pop()[0]
localDict = {'self':self.vf}
localDict.update( self._undoArgs ) # add undoArgs to local dict
exec( command, sys.modules['__main__'].__dict__, localDict)
# remove _undoArg_%d used by this command from self._undoArgs dict
ind = command.find('_undoArg_')
while ind != -1 and ind < len(command)-10:
name = command[ind: ind+9]
end = ind+9
# add digits following string
while command[end].isdigit():
name += command[end]
end +=1
nodes = self._undoArgs[name]
del self._undoArgs[name]
new_start = ind + len(name)
ind = command[new_start:].find('_undoArg_')
if ind!=-1:
ind = ind + new_start
#exec( command, self.vf.__dict__ )
self.setLabel()
def guiCallback(self, event=None):
self.doitWrapper(topCommand=0, log=0, busyIdle=1)
def __call__(self, **kw):
"""None<---Undo()
"""
self.doitWrapper(topCommand=0, log=0, busyIdle=1)
def addEntry(self, undoString, menuString):
self.vf.undoCmdStack.append( (undoString, menuString) )
maxLen = self.vf.userpref['Number of Undo']['value']
if maxLen>0 and len(self.vf.undoCmdStack)>maxLen:
self.vf.undoCmdStack = self.vf.undoCmdStack[-maxLen:]
self.vf.undo.setLabel()
def setLabel(self):
"""change menu entry label to show command name"""
if not self.vf.hasGui: return
cmdmenuEntry = self.GUI.menu[4]['label']
if len(self.vf.undoCmdStack)==0:
state = 'disabled'
label = 'Undo '
if self.vf.GUI.menuBars.has_key('Toolbar'):
TButton = self.vf.GUI.menuBars['Toolbar']._frame.toolbarButtonDict['Undo']
TButton.disable()
#if hasattr(self,'balloon'):
# self.balloon.destroy()
#self.balloon = Pmw.Balloon(self.vf.GUI.ROOT)
#self.balloon.bind(TButton, 'Undo')
#rebind other functions from toolbarbutton
TButton.bind("<Enter>", TButton.buttonEnter, '+')
TButton.bind("<Leave>", TButton.buttonLeave, '+')
TButton.bind("<ButtonPress-1>", TButton.buttonDown)
TButton.bind("<ButtonRelease-1>", TButton.buttonUp)
else:
state='normal'
label = 'Undo ' + self.vf.undoCmdStack[-1][1]
if self.vf.GUI.menuBars.has_key('Toolbar'):
TButton = self.vf.GUI.menuBars['Toolbar']._frame.toolbarButtonDict['Undo']
TButton.enable()
#if hasattr(self,'balloon'):
# self.balloon.destroy()
#self.balloon = Pmw.Balloon(self.vf.GUI.ROOT)
self.balloon.bind(TButton, label)
#rebind other functions from toolbarbutton
TButton.bind("<Enter>", TButton.buttonEnter, '+')
TButton.bind("<Leave>", TButton.buttonLeave, '+')
TButton.bind("<ButtonPress-1>", TButton.buttonDown)
TButton.bind("<ButtonRelease-1>", TButton.buttonUp)
self.vf.GUI.configMenuEntry(self.GUI.menuButton, cmdmenuEntry,
label=label, state=state)
self.GUI.menu[4]['label']=label
class RemoveCommand(Command):
def loadCommands(self):
for key in self.vf.removableCommands.settings:
try:
self.vf.browseCommands.doit(key, self.vf.removableCommands.settings[key][0],
self.vf.removableCommands.settings[key][1])
except Exception, inst:
print __file__, inst
def guiCallback(self):
idf = InputFormDescr(title='Remove Command')
idf.append({'name':'cmd',
'widgetType':kbScrolledListBox,
'wcfg':{'items':self.vf.removableCommands.settings.keys(),
'listbox_exportselection':0,
'listbox_selectmode':'extended',
'labelpos':'nw',
'label_text':'Available commands:',
#'dblclickcommand':self.loadCmd_cb,
#'selectioncommand':self.displayCmd_cb,
},
'gridcfg':{'sticky':'wesn', 'row':-1}})
val = self.vf.getUserInput(idf, modal=1, blocking=1)
if val:
self.vf.removableCommands.settings.pop(val['cmd'][0])
self.vf.removableCommands.saveAllSettings()
txt = "You need to restart for the changes to take effect."
tkMessageBox.showinfo("Restart is Needed", txt)
class ResetUndoCommand(Command):
""" Class to reset Undo()
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : ResetUndoCommand
\nCommand : resetUndo
\nSynopsis:\n
None<---resetUndo()
"""
def doit(self):
self.vf.undoCmdStack = []
self.vf.undo._undoArgs = {} # reset dict used to save large Python objects
self.vf.undo.setLabel()
for command in self.vf.commands:
if hasattr(command, 'command'): # added to handle 'computeSheet2D' case
command.undoStack = []
def __call__(self, **kw):
"""None<---resetUndo()
"""
apply( self.doitWrapper, (), kw )
class BrowseCommandsCommand(Command):
"""Command to load dynamically either modules or individual commands
in the viewer.
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : BrowseCommandsCommand
\nCommand : browseCommands
\nSynopsis:\n
None <-- browseCommands(module, commands=None, package=None, **kw)
\nRequired Arguements:\n
module --- name of the module(eg:colorCommands)
\nOptional Arguements:\n
commnads --- one list of commands to load
\npackage --- name of the package to which module belongs(eg:Pmv,Vision)
"""
def __init__(self, func=None):
Command.__init__(self, func)
self.allPack = {}
self.packMod = {}
self.allPackFlag = False
self.txtGUI = ""
def doit(self, module, commands=None, package=None, removable=False):
# if removable:
# self.vf.removableCommands.settings[module] = [commands, package]
# self.vf.removableCommands.saveAllSettings()
# If the package is not specified the default is the first library
global commandslist,cmd_docslist
if package is None: package = self.vf.libraries[0]
importName = package + '.' + module
try:
mod = __import__(importName, globals(), locals(),
[module])
except:
if self.cmdForms.has_key('loadCmds') and \
self.cmdForms['loadCmds'].f.winfo_toplevel().wm_state() == \
'normal':
self.vf.warningMsg("ERROR: Could not load module %s"%module,
parent = self.cmdForms['loadCmds'].root)
elif self.vf.loadModule.cmdForms.has_key('loadModule') and \
self.vf.loadModule.cmdForms['loadModule'].f.winfo_toplevel().wm_state() == \
'normal':
self.vf.warningMsg("ERROR: Could not load module %s"%module,
parent = self.vf.loadModule.cmdForms['loadModule'].root)
else:
self.vf.warningMsg("ERROR: Could not load module %s"%module)
traceback.print_exc()
return 'ERROR'
if commands is None:
if hasattr(mod,"initModule"):
if self.vf.hasGui :
mod.initModule(self.vf)
else :
#if there is noGUI and if we want to have multiple session of mv
#need to instanciate new commands, and not use the global dictionay commandList
if hasattr(mod, 'commandList'):
for d in mod.commandList:
d['cmd'] = d['cmd'].__class__()
#print "load all comands ", d['cmd'], d['name'], d['gui']
self.vf.addCommand( d['cmd'], d['name'], d['gui'])
else : print mod
if hasattr(mod, 'commandList'):
for x in mod.commandList:
cmd=x['name']
c=x['cmd']
#print 'CCCCCCC', cmd
if cmd not in cmd_docslist:
if hasattr(c,'__doc__'):
cmd_docslist[cmd]=c.__doc__
if x['gui']:
if x['gui'].menuDict:
if len(self.txtGUI) < 800:
self.txtGUI += "\n"+x['gui'].menuDict['menuButtonName']
if x['gui'].menuDict['menuCascadeName']:
self.txtGUI += "->"+ x['gui'].menuDict['menuCascadeName']
self.txtGUI += "->"+x['gui'].menuDict['menuEntryLabel']
if cmd not in commandslist:
commandslist.append(cmd)
#print 'ZZZZZZZZZZZZ', mod
else:
if self.cmdForms.has_key('loadCmds') and \
self.cmdForms['loadCmds'].f.winfo_toplevel().wm_state() == \
'normal':
self.vf.warningMsg("ERROR: Could not load module %s"%module,
parent = self.cmdForms['loadCmds'].root)
elif self.vf.loadModule.cmdForms.has_key('loadModule') and \
self.vf.loadModule.cmdForms['loadModule'].f.winfo_toplevel().wm_state() == \
'normal':
self.vf.warningMsg("ERROR: Could not load module %s"%module,
parent = self.vf.loadModule.cmdForms['loadModule'].root)
else:
self.vf.warningMsg("ERROR: Could not load module %s"%module)
return "ERROR"
else:
if not type(commands) in [types.ListType, types.TupleType]:
commands = [commands,]
if not hasattr(mod, 'commandList'):
return
for cmd in commands:
d = filter(lambda x: x['name'] == cmd, mod.commandList)
if len(d) == 0:
self.vf.warningMsg("Command %s not found in module %s.%s"%
(cmd, package, module))
continue
d = d[0]
if cmd not in cmd_docslist:
if hasattr(d['cmd'],'__doc__'):
cmd_docslist[cmd]=d['cmd'].__doc__
if cmd not in commandslist:
commandslist.append(cmd)
if not self.vf.hasGui :
#if there is noGUI and if we want to have multiple session of mv
#need to instanciate new commands, and not use the global dictionay commandList
#print "load specific comands ", d['cmd'], d['name'], d['gui']
d['cmd'] = d['cmd'].__class__()
self.vf.addCommand(d['cmd'], d['name'], d['gui'])
def __call__(self, module, commands=None, package=None, **kw):
"""None<---browseCommands(module, commands=None, package=None, **kw)
\nmodule --- name of the module(eg:colorCommands)
\ncommnads --- one list of commands to load
\npackage --- name of the package to which module belongs(eg:Pmv,Vision)
"""
kw['commands'] = commands
kw['package'] = package
apply(self.doitWrapper, (module,), kw )
def buildFormDescr(self, formName):
import Tkinter
if not formName == 'loadCmds': return
idf = InputFormDescr(title='Load Modules and Commands')
pname = self.vf.libraries
#when Pvv.startpvvCommnads is loaded some how Volume.Pvv is considered
#as seperate package and is added to packages list in the widget
#To avoid this packages having '.' are removed
for p in pname:
if '.' in p:
ind = pname.index(p)
del pname[ind]
idf.append({'name':'packList',
'widgetType':kbScrolledListBox,
'wcfg':{'items':pname,
#'defaultValue':pname[0],
'listbox_exportselection':0,
'labelpos':'nw',
'label_text':'Select a package:',
#'dblclickcommand':self.loadMod_cb,
'selectioncommand':self.displayMod_cb
},
'gridcfg':{'sticky':'wesn'}})
idf.append({'name':'modList',
'widgetType':kbScrolledListBox,
'wcfg':{'items':[],
'listbox_exportselection':0,
'labelpos':'nw',
'label_text':'Select a module:',
#'dblclickcommand':self.loadMod_cb,
'selectioncommand':self.displayCmds_cb,
},
'gridcfg':{'sticky':'wesn', 'row':-1}})
idf.append({'name':'cmdList',
'widgetType':kbScrolledListBox,
'wcfg':{'items':[],
'listbox_exportselection':0,
'listbox_selectmode':'extended',
'labelpos':'nw',
'label_text':'Available commands:',
#'dblclickcommand':self.loadCmd_cb,
'selectioncommand':self.displayCmd_cb,
},
'gridcfg':{'sticky':'wesn', 'row':-1}})
# idf.append({'name':'docbutton',
# 'widgetType':Tkinter.Checkbutton,
# #'parent':'DOCGROUP',
# 'defaultValue':0,
# 'wcfg':{'text':'Show documentation',
# 'onvalue':1,
# 'offvalue':0,
# 'command':self.showdoc_cb,
# 'variable':Tkinter.IntVar()},
# 'gridcfg':{'sticky':'nw','columnspan':3}})
idf.append({'name':'DOCGROUP',
'widgetType':Pmw.Group,
'container':{'DOCGROUP':"w.interior()"},
'collapsedsize':0,
'wcfg':{'tag_text':'Description'},
'gridcfg':{'sticky':'wnse', 'columnspan':3}})
idf.append({'name':'doclist',
'widgetType':kbScrolledListBox,
'parent':'DOCGROUP',
'wcfg':{'items':[],
'listbox_exportselection':0,
'listbox_selectmode':'extended',
},
'gridcfg':{'sticky':'wesn', 'columnspan':3}})
idf.append({'name':'allPacks',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Show all packages',
'command':self.allPacks_cb},
'gridcfg':{'sticky':'ew'}})
idf.append({'name':'loadMod',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Load selected module',
'command':self.loadMod_cb},
'gridcfg':{'sticky':'ew', 'row':-1}})
# idf.append({'name':'loadCmd',
# 'widgetType':Tkinter.Button,
# 'wcfg':{'text':'Load Command',
# 'command':self.loadCmd_cb},
# 'gridcfg':{'sticky':'ew', 'row':-1}})
idf.append({'name':'dismiss',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Dismiss',
'command':self.dismiss_cb},
'gridcfg':{'sticky':'ew', 'row':-1}})
# idf.append({'name':'dismiss',
# 'widgetType':Tkinter.Button,
# 'wcfg':{'text':'DISMISS',
# 'command':self.dismiss_cb,
# },
# 'gridcfg':{'sticky':Tkinter.E+Tkinter.W,'columnspan':3}})
return idf
def guiCallback(self):
self.vf.GUI.ROOT.config(cursor='watch')
self.vf.GUI.ROOT.update()
if self.allPack == {}:
self.allPack = findAllVFPackages()
val = self.showForm('loadCmds', force=1,modal=0,blocking=0)
ebn = self.cmdForms['loadCmds'].descr.entryByName
# docb=ebn['docbutton']['widget']
# var=ebn['docbutton']['wcfg']['variable'].get()
# if var==0:
# dg=ebn['DOCGROUP']['widget']
# dg.collapse()
self.vf.GUI.ROOT.config(cursor='')
def dismiss_cb(self, event=None):
self.cmdForms['loadCmds'].withdraw()
def allPacks_cb(self, event=None):
ebn = self.cmdForms['loadCmds'].descr.entryByName
packW = ebn['packList']['widget']
if not self.allPackFlag:
packName = self.allPack.keys()
packW.setlist(packName)
ebn['allPacks']['widget'].configure(text='Show default packages')
self.allPackFlag = True
else:
packName = self.vf.libraries
packW.setlist(packName)
ebn['allPacks']['widget'].configure(text='Show all packages')
self.allPackFlag = False
ebn['modList']['widget'].clear()
ebn['cmdList']['widget'].clear()
# def showdoc_cb(self,event=None):
# #when a show documentation is on and a module is selected then
# #expands dg else dg is collapsed
# ebn = self.cmdForms['loadCmds'].descr.entryByName
# docb=ebn['docbutton']['widget']
# var=ebn['docbutton']['wcfg']['variable'].get()
# dg=ebn['DOCGROUP']['widget']
# docw=ebn['doclist']['widget']
# packW = ebn['packList']['widget']
# psel=packW.getcurselection()
# if var==0:
# dg.collapse()
# if var==1 and psel:
# if docw.size()>0:
# dg.expand()
def displayMod_cb(self, event=None):
#print "displayMod_cb"
# c = self.cmdForms['loadCmds'].mf.cget('cursor')
# self.cmdForms['loadCmds'].mf.configure(cursor='watch')
# self.cmdForms['loadCmds'].mf.update_idletasks()
ebn = self.cmdForms['loadCmds'].descr.entryByName
# docb=ebn['docbutton']['widget']
# var=ebn['docbutton']['wcfg']['variable'].get()
# dg = ebn['DOCGROUP']['widget']
# dg.collapse()
packW = ebn['packList']['widget']
packs = packW.getcurselection()
if len(packs) == 0:
return
packName = packs[0]
if not self.packMod.has_key(packName):
package = self.allPack[packName]
self.packMod[packName] = findModulesInPackage(package,"^def initModule",fileNameFilters=['Command'])
self.currentPack = packName
modNames = []
for key, value in self.packMod[packName].items():
pathPack = key.split(os.path.sep)
if pathPack[-1] == packName:
newModName = map(lambda x: x[:-3], value)
#for mname in newModName:
#if "Command" not in mname :
#ind = newModName.index(mname)
#del newModName[ind]
modNames = modNames+newModName
else:
pIndex = pathPack.index(packName)
prefix = join(pathPack[pIndex+1:], '.')
newModName = map(lambda x: "%s.%s"%(prefix, x[:-3]), value)
#for mname in newModName:
#if "Command" not in mname :
#ind = newModName.index(mname)
#del newModName[ind]
modNames = modNames+newModName
modNames.sort()
modW = ebn['modList']['widget']
modW.setlist(modNames)
# and clear contents in self.libraryGUI
cmdW = ebn['cmdList']['widget']
cmdW.clear()
m = __import__(packName, globals(), locals(),[])
d = []
docstring=m.__doc__
#d.append(m.__doc__)
docw = ebn['doclist']['widget']
docw.clear()
#formatting documentation.
if docstring!=None :
if '\n' in docstring:
x = string.split(docstring,"\n")
for i in x:
if i !='':
d.append(i)
if len(d)>8:
docw.configure(listbox_height=8)
else:
docw.configure(listbox_height=len(d))
else:
x = string.split(docstring," ")
#formatting documenation
if len(x)>10:
docw.configure(listbox_height=len(x)/10)
else:
docw.configure(listbox_height=1)
docw.setlist(d)
# self.cmdForms['loadCmds'].mf.configure(cursor=c)
#when show documentation on after selcting a package
#dg is expanded to show documenttation
#if var==1 and docw.size()>0:
if docw.size()>0:
dg.expand()
def displayCmds_cb(self, event=None):
#print "displayCmds_cb"
global cmd_docslist
self.cmdForms['loadCmds'].mf.update_idletasks()
ebn = self.cmdForms['loadCmds'].descr.entryByName
dg = ebn['DOCGROUP']['widget']
dg.collapse()
cmdW = ebn['cmdList']['widget']
cmdW.clear()
# docb=ebn['docbutton']['widget']
# var=ebn['docbutton']['wcfg']['variable'].get()
modName = ebn['modList']['widget'].getcurselection()
if modName == (0 or ()): return
else:
modName = modName[0]
importName = self.currentPack + '.' + modName
try:
m = __import__(importName, globals(), locals(),['commandList'])
except:
return
if not hasattr(m, 'commandList'):
return
cmdNames = map(lambda x: x['name'], m.commandList)
cmdNames.sort()
if modName:
self.var=1
d =[]
docstring =m.__doc__
import string
docw = ebn['doclist']['widget']
docw.clear()
if docstring!=None :
if '\n' in docstring:
x = string.split(docstring,"\n")
for i in x:
if i !='':
d.append(i)
#formatting documenation
if len(d)>8:
docw.configure(listbox_height=8)
else:
docw.configure(listbox_height=len(d))
else:
d.append(docstring)
x = string.split(docstring," ")
#formatting documenation
if len(x)>10:
docw.configure(listbox_height=len(x)/10)
else:
docw.configure(listbox_height=1)
docw.setlist(d)
CmdName=ebn['cmdList']['widget'].getcurselection()
cmdW.setlist(cmdNames)
#when show documentation is on after selcting a module or a command
#dg is expanded to show documenttation
#if var==1 and docw.size()>0:
if docw.size()>0:
dg.expand()
def displayCmd_cb(self, event=None):
#print "displayCmd_cb"
global cmd_docslist
self.cmdForms['loadCmds'].mf.update_idletasks()
ebn = self.cmdForms['loadCmds'].descr.entryByName
dg = ebn['DOCGROUP']['widget']
dg.collapse()
# docb=ebn['docbutton']['widget']
# var=ebn['docbutton']['wcfg']['variable'].get()
modName = ebn['modList']['widget'].getcurselection()
if modName == (0 or ()): return
else:
modName = modName[0]
importName = self.currentPack + '.' + modName
try:
m = __import__(importName, globals(), locals(),['commandList'])
except:
self.warningMsg("ERROR: Cannot find commands for %s"%modName)
return
if not hasattr(m, 'commandList'):
return
cmdNames = map(lambda x: x['name'], m.commandList)
cmdNames.sort()
if modName:
self.var=1
d =[]
docstring =m.__doc__
import string
docw = ebn['doclist']['widget']
docw.clear()
if docstring!=None :
if '\n' in docstring:
x = string.split(docstring,"\n")
for i in x:
if i !='':
d.append(i)
#formatting documenation
if len(d)>8:
docw.configure(listbox_height=8)
else:
docw.configure(listbox_height=len(d))
else:
d.append(docstring)
x = string.split(docstring," ")
#formatting documenation
if len(x)>10:
docw.configure(listbox_height=len(x)/10)
else:
docw.configure(listbox_height=1)
docw.setlist(d)
cmdW = ebn['cmdList']['widget']
CmdName=ebn['cmdList']['widget'].getcurselection()
cmdW.setlist(cmdNames)
if len(CmdName)!=0:
for i in m.commandList:
if i['name']==CmdName[0]:
c = i['cmd']
if CmdName[0] in cmdNames:
ind= cmdNames.index(CmdName[0])
cmdW.selection_clear()
cmdW.selection_set(ind)
d =[]
docstring=c.__doc__
docw = ebn['doclist']['widget']
docw.clear()
if CmdName[0] not in cmd_docslist.keys():
cmd_docslist[CmdName[0]]=d
import string
if docstring!=None :
if '\n' in docstring:
x = string.split(docstring,"\n")
for i in x:
if i !='':
d.append(i)
if len(d)>8:
docw.configure(listbox_height=8)
else:
docw.configure(listbox_height=len(d))
else:
d.append(docstring)
x = string.split(docstring," ")
if len(x)>10:
docw.configure(listbox_height=len(x)/10)
else:
docw.configure(listbox_height=1)
docw.setlist(d)
#when show documentation is on after selcting a module or a command
#dg is expanded to show documenttation
#if var==1 and docw.size()>0:
if docw.size()>0:
dg.expand()
def loadMod_cb(self, event=None):
ebn = self.cmdForms['loadCmds'].descr.entryByName
selMod = ebn['modList']['widget'].getcurselection()
if len(selMod)==0: return
else:
self.txtGUI = ""
apply(self.doitWrapper, ( selMod[0],),
{'commands':None, 'package':self.currentPack, 'removable':True})
self.dismiss_cb(None)
if self.txtGUI:
self.txtGUI = "\n Access this command via:\n"+self.txtGUI
tkMessageBox.showinfo("Load Module", selMod[0]+" loaded successfully!\n"+self.txtGUI)
# def loadCmd_cb(self, event=None):
# ebn = self.cmdForms['loadCmds'].descr.entryByName
# selCmds = ebn['cmdList']['widget'].getcurselection()
# selMod = ebn['modList']['widget'].getcurselection()
# if len(selCmds)==0: return
# else:
# apply(self.doitWrapper, (selMod[0],), {'commands':selCmds,
# 'package':self.currentPack})
class loadModuleCommand(Command):
"""Command to load dynamically modules to the Viewer import the file called name.py and execute the function initModule defined in that file Raises a ValueError exception if initModule is not defined
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : loadModuleCommand
\nCommand : loadModule
\nSynopsis:\n
None<--loadModule(filename, package=None, **kw)
\nRequired Arguements:\n
filename --- name of the module
\nOptional Arguements:\n
package --- name of the package to which filename belongs
"""
active = 0
def doit(self, filename, package):
# This is NOT called because we call browseCommand()"
if package is None:
_package = filename
else:
_package = "%s.%s"%(package, filename)
try:
mod = __import__( _package, globals(), locals(), ['initModule'])
if hasattr(mod, 'initModule') or not callable(mod.initModule):
mod.initModule(self.vf)
else:
self.vf.warningMsg('module %s has not initModule function')
except ImportError:
self.vf.warningMsg('module %s could not be imported'%_package)
## if package is None:
## _package = filename
## else:
## _package = "%s.%s"%(package, filename)
## module = self.vf.tryto( __import__ , _package, globals(), locals(),
## [filename])
## if module=='ERROR':
## print '\nWARNING: Could not load module %s' % filename
## return
def __call__(self, filename, package=None, **kw):
"""None<---loadModule(filename, package=None, **kw)
\nRequired Arguements:\n
filename --- name of the module
\nOptional Arguements:\n
package --- name of the package to which filename belongs
"""
if package==None:
package=self.vf.libraries[0]
if not kw.has_key('redraw'):
kw['redraw'] = 0
kw['package'] = package
apply(self.vf.browseCommands, (filename,), kw)
#apply( self.doitWrapper, (filename, package), kw )
def loadModule_cb(self, event=None):
# c = self.cmdForms['loadModule'].mf.cget('cursor')
# self.cmdForms['loadModule'].mf.configure(cursor='watch')
# self.cmdForms['loadModule'].mf.update_idletasks()
ebn = self.cmdForms['loadModule'].descr.entryByName
moduleName = ebn['Module List']['widget'].get()
package = ebn['package']['widget'].get()
if moduleName:
self.vf.browseCommands(moduleName[0], package=package, redraw=0)
# self.cmdForms['loadModule'].mf.configure(cursor=c)
def loadModules(self, package, library=None):
modNames = []
doc = []
self.filenames={}
self.allPack={}
self.allPack=findAllVFPackages()
if package is None: return [], []
if not self.filenames.has_key(package):
pack=self.allPack[package]
#finding modules in a package
self.filenames[pack] =findModulesInPackage(pack,"^def initModule",fileNameFilters=['Command'])
# dictionary of files keys=widget, values = filename
for key, value in self.filenames[pack].items():
pathPack = key.split(os.path.sep)
if pathPack[-1] == package:
newModName = map(lambda x: x[:-3], value)
#for mname in newModName:
#if not modulename has Command in it delete from the
#modules list
#if "Command" not in mname :
#ind = newModName.index(mname)
#del newModName[ind]
#if "Command" in mname :
if hasattr(newModName,"__doc__"):
doc.append(newModName.__doc__)
else:
doc.append(None)
modNames = modNames + newModName
else:
pIndex = pathPack.index(package)
prefix = join(pathPack[pIndex+1:], '.')
newModName = map(lambda x: "%s.%s"%(prefix, x[:-3]), value)
#for mname in newModName:
#if not modulename has Command in it delete from the
#modules list
#if "Command" not in mname :
#ind = newModName.index(mname)
#del newModName[ind]
if hasattr(newModName,"__doc__"):
doc.append(newModName.__doc__)
else:
doc.append(None)
modNames = modNames + newModName
modNames.sort()
return modNames, doc
def package_cb(self, event=None):
ebn = self.cmdForms['loadModule'].descr.entryByName
pack = ebn['package']['widget'].get()
names, docs = self.loadModules(pack)
w = ebn['Module List']['widget']
w.clear()
for n,d in map(None, names, docs):
w.insert('end', n, d)
def buildFormDescr(self, formName):
"""create the cascade menu for selecting modules to be loaded"""
if not formName == 'loadModule':return
ifd = InputFormDescr(title='Load command Modules')
names, docs = self.loadModules(self.vf.libraries[0])
entries = map(lambda x: (x, None), names)
pname=self.vf.libraries
for p in pname:
if '.' in p:
ind = pname.index(p)
del pname[ind]
ifd.append({
'name':'package',
'widgetType': Pmw.ComboBox,
'defaultValue': pname[0],
'wcfg':{ 'labelpos':'nw', 'label_text':'Package:',
'selectioncommand': self.package_cb,
'scrolledlist_items':pname
},
'gridcfg':{'sticky':'ew', 'padx':2, 'pady':1}
})
ifd.append({'name': 'Module List',
'widgetType':ListChooser,
'wcfg':{
'title':'Choose a module',
'entries': entries,
'lbwcfg':{'width':27,'height':10},
'command':self.loadModule_cb,
'commandEvent':"<Double-Button-1>"
},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W}
})
ifd.append({'name': 'Load Module',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Load Module',
'command': self.loadModule_cb,
'bd':6},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W},
})
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Dismiss',
'command': self.Dismiss_cb},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W}})
return ifd
def Dismiss_cb(self):
self.cmdForms['loadModule'].withdraw()
self.active = 0
def guiCallback(self, event=None):
if self.active: return
self.active = 1
form = self.showForm('loadModule', force=1,modal=0,blocking=0)
form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
class loadCommandCommand(loadModuleCommand):
"""Command to load dynamically individual commands in the Viewer.
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : loadCommandCommand
\nCommand : loadCommand
\nSynopsis:\n
None <- loadCommand(moduleName, commandsName, package=None,
gui=None)
\nRequired Arguements:\n
moduleName --- name of the module to be loaded
commandsName --- name of the Command or list of Commands
\nOptional Arguements:\n
package --- name of the package to which filename belongs
"""
active = 0
def doit(self, module, commands, package=None, gui=None):
"""Load a command instance with the given alias and gui"""
if package is None:
package = self.vf.libraries[0]
if not type(commands)!=types.ListType:
commands = [commands,]
for command in commands:
cmd, name, gui = self.getDefaults(package, module, command)
if cmd is None:
print 'Could not add %s.%s.%s'%(package, module, command)
continue
self.vf.addCommand( cmd, name, gui )
def guiCallback(self, event=None):
if self.active: return
self.active = 1
form = self.showForm('loadCommand', force=1,modal=0,blocking=0)
form.root.protocol('WM_DELETE_WINDOW',self.Dismiss_cb)
def package_cb(self, event=None):
# Get Package.
ebn = self.cmdForms['loadCommand'].descr.entryByName
pack = ebn['package']['widget'].get()
# Get Modules for the new package and update the listChooser.
names, docs = self.loadModules(pack)
mw = ebn['Module List']['widget']
mw.clear()
for n in names:
mw.insert('end',n)
mw.set(names[0])
# Get Commands for the first module and update the listChooser
cw = ebn['Command List']['widget']
cw.clear()
cmds = self.getModuleCmds(modName=names[0],
package=pack)
if cmds==None:
return
for cmd in map(lambda x: x[0],cmds):
cw.insert('end', cmd)
def Dismiss_cb(self):
self.cmdForms['loadCommand'].withdraw()
self.active = 0
def __call__(self, moduleName, commandsName,
package=None, gui=None, **kw):
"""None <- loadCommand(moduleName, commandsName, package=None,
gui=None)
\nRequired Arguements:\n
moduleName --- name of the module to be loaded
commandsName --- name of the Command or list of Commands
\nOptional Arguements:\n
package --- name of the package to which filename belongs
"""
kw['package'] = package
#kw['gui'] = gui
#apply(self.doitWrapper, (moduleName, commandsName), kw)
kw['commands']=commandsName
apply(self.vf.browseCommands, (moduleName,), kw)
def getDefaults(self, package, filename, commandName):
if package is None: _package = filename
else: _package = "%s.%s"%(package, filename)
mod = self.vf.tryto(__import__,_package, globals(), locals(),
[filename])
if mod=='ERROR':
print '\nERROR: Could not load module %s.%s' % (_package,
filename)
return None,None,None
for d in mod.commandList:
if d['name']==commandName:
break
if d['name']!=commandName:
print '\nERROR: command %s not found in module %s.%s\n' % \
(commandName, package, filename)
return None,None,None
return d['cmd'], d['name'], d['gui']
def loadCmd_cb(self, event=None):
# c = self.cmdForms['loadCommand'].mf.cget('cursor')
# self.cmdForms['loadCommand'].mf.configure(cursor='watch')
# self.cmdForms['loadCommand'].mf.update_idletasks()
ebn = self.cmdForms['loadCommand'].descr.entryByName
module = ebn['Module List']['widget'].get()
commands = ebn['Command List']['widget'].get()
package = ebn['package']['widget'].get()
if commands:
kw = {'package': package}
#apply(self.doitWrapper, (module, commands), kw)
kw['commands'] = commands
apply(self.vf.browseCommands, (module[0],), kw)
# self.cmdForms['loadCommand'].mf.configure(cursor=c)
def getModuleCmds(self, modName=None, package=None):
""" Callback method of the module chooser to get the corresponding
commands:
"""
filename = modName
if package is None: _package = filename
else: _package = "%s.%s"%(package, filename)
try:
mod = __import__(_package,globals(),locals(),['commandList'])
except:
self.vf.warningMsg("ERROR: Could not load module %s "%filename)
return "ERROR"
if hasattr(mod,"initModule"):
mod.initModule(self.vf)
else:
self.vf.warningMsg("ERROR: Could not load module %s"%filename)
return
if not hasattr(mod, 'commandList'):
cmdEntries = []
else:
cmdsName = map(lambda x: x['name'], mod.commandList)
cmdsName.sort()
cmdEntries = map(lambda x: (x,None), cmdsName)
return cmdEntries
def modChooser_cb(self, event=None):
"""CallBack method that gets called when clicking on an entry
of the mocule cjooser."""
ebn = self.cmdForms['loadCommand'].descr.entryByName
modChooser = ebn['Module List']['widget']
filename = modChooser.get()[0]
package = ebn['package']['widget'].get()
cmdEntries = self.getModuleCmds(modName=filename, package=package)
cmdChooser = ebn['Command List']['widget']
cmdChooser.clear()
#cmdEntries should be a list if there are no commands for a module then getModuleCmds returns None or Error in that case cmdEntries is made equal to emptylist
if cmdEntries=="ERROR" or cmdEntries==None:
cmdEntries=[]
map(cmdChooser.add, cmdEntries)
def buildFormDescr(self, formName):
"""Create the pulldown menu and Listchooser to let for the
selection of commands."""
if not formName == 'loadCommand': return
ifd = InputFormDescr(title='Load Individual Commands')
moduleNames, docs = self.loadModules(self.vf.libraries[0])
moduleNames.sort()
moduleEntries = map(lambda x: (x, None), moduleNames)
pname = self.vf.libraries
for p in pname:
if '.' in p:
ind = pname.index(p)
del pname[ind]
ifd.append({
'name':'package',
'widgetType': Pmw.ComboBox,
'defaultValue': pname[0],
'wcfg':{ 'labelpos':'nw', 'label_text':'Package:',
'selectioncommand': self.package_cb,
'scrolledlist_items':pname
},
'gridcfg':{'columnspan':2,'sticky':'ew', 'padx':2, 'pady':1}
})
ifd.append({'name': 'Module List',
'widgetType':ListChooser,
'wcfg':{'title':'Choose a module',
'entries': moduleEntries,
'lbwcfg':{ 'width':25,
'height':10,
'exportselection':0},
'command':self.modChooser_cb,
},
'gridcfg':{'sticky':'ew'}
} )
CmdEntries = []
ifd.append({'name': 'Command List',
'widgetType':ListChooser,
'wcfg':{'title':'Choose a command',
'mode':'multiple',
'entries': CmdEntries,
'command':self.loadCmd_cb,
'commandEvent':"<Double-Button-1>",
'lbwcfg':{'width':25,'height':10,
'exportselection':0}
},
'gridcfg':{'row':-1,'sticky':'we'}
} )
ifd.append({'name': 'Load Command',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Load Command',
'bd':6, 'command': self.loadCmd_cb},
'gridcfg':{'columnspan':2,'sticky':'ew'},
})
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Dismiss',
'command': self.Dismiss_cb},
'gridcfg':{'columnspan':2,'sticky':'ew'}})
return ifd
class loadMacroCommand(Command):
"""Command to load dynamically macro commands.
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : loadMacroCommand
\nCommand : loadMacro
\nSynopsis:\n
None<---loadMacro(macroName, macroFile, menuBar='menuRoot',
menuButton='Macros', menuEntry=None, cascade=None, **kw)
"""
active = 0
def getMacros(self, file):
"""load all macro functions from a given file"""
names = []
macros = []
doc = []
#if not os.path.exists(file) : return names, macros, doc
_dir, file = os.path.split(file)
if file[-3:]=='.py': file = file[:-3]
import sys
sys.path.insert(0, _dir)
m = __import__(file, globals(), locals(), [])
sys.path = sys.path[1:]
#m.__dict__['self'] = self.vf
setattr(m, 'self', self.vf)
import types
for key, value in m.__dict__.items():
if type(value) == types.FunctionType:
names.append(key)
macros.append(value)
doc.append(value.__doc__)
return names, macros, doc
def loadMacLib_cb(self, filename):
"""Call back function for 'Open Macro library' button"""
ebn = self.cmdForms['loadMacro'].descr.entryByName
ebn['openMacLib']['widget'].button.configure(relief='sunken')
names, macros, docs = self.getMacros(filename)
self.macroFile = filename
self.macNames = names
self.macMacros = macros
self.macDoc = docs
# Get a handle to the listchooser widget
lc = ebn['macros']['widget']
lc.clear()
if len(names) == len(docs):
entries = map(lambda x, y: (x, y), names, docs)
else:
entries = map(lambda x: (x, None), names)
map(lc.add, entries)
ebn['openMacLib']['widget'].button.configure(relief='raised')
# set cascade name to libary Name - "mac"
w = ebn['cascade']['widget']
w.delete(0, 'end')
w.insert(0, os.path.split(filename)[1][:-3])
def setDefaultEntryName(self, event=None):
"""Call back function for the listchooser showing macros.
gets the name of the currently selected macro and puts it in the entry
type in"""
# enable add button
ebn = self.cmdForms['loadMacro'].descr.entryByName
ebn['loadMacro']['widget'].configure(state='normal')
# put default name into name entry
val = ebn['macros']['widget'].get()
w = ebn['menuentry']['widget']
w.delete(0, 'end')
w.insert(0, val[0])
#self.selectedMac = val[0]
def loadMacro_cb(self, event=None):
ebn = self.cmdForms['loadMacro'].descr.entryByName
bar = ebn['menubar']['widget'].get()
menub = ebn['menubutton']['widget'].get()
name = ebn['menuentry']['widget'].get()
cascade = ebn['cascade']['widget'].get()
if cascade=='': cascade=None
lc = ebn['macros']['widget']
macNames = lc.get()
if len(macNames) != 0: macName = macNames[0]
#macIndex = self.macNames.index(self.selectedMac)
#macFunc = self.macMacros[macIndex]
self.doitWrapper(macName, self.macroFile, menuBar=bar,
menuButton=menub,
menuEntry=name, cascade=cascade)
###self.addMacro(macFunc, bar, menub, name, cascade)
ebn['openMacLib']['widget'].button.configure(relief='raised')
def dismiss_cb(self):
self.cmdForms['loadMacro'].withdraw()
self.active = 0
def buildFormDescr(self, formName):
if not formName=='loadMacro': return None
ifd = InputFormDescr(title='Load Macros')
if len(self.vf.libraries) is None:
modu = __import__('ViewerFramework')
else:
modu = __import__(self.vf.libraries[0])
idir = os.path.split(modu.__file__)[0] + '/Macros'
if not os.path.exists(idir):
idir = None
# 0
ifd.append({'widgetType':LoadButton,
'name':'openMacLib',
'wcfg':{'buttonType':Tkinter.Button,
'title':'Open Macro Library...',
'types':[('Macro Module Library', '*Mac.py'),
('Any Python Function', '*.py')],
'callback':self.loadMacLib_cb,
'idir':idir,
'widgetwcfg':{'text':'Open Macro Library'}},
'gridcfg':{'sticky':'we'}})
# 1
ifd.append({'name':'macros',
'widgetType':ListChooser,
'wcfg':{'title':'Choose a macro',
'command':self.setDefaultEntryName,
'title':'Choose a macro'},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W}} )
# 2
ifd.append({'widgetType':Tkinter.Entry,
'name':'menubar',
'defaultValue':'menuRoot',
'wcfg':{'label':'menu bar'},
'gridcfg':{'sticky':Tkinter.E}
})
# 3
ifd.append({'widgetType':Tkinter.Entry,
'name':'menubutton',
'defaultValue':'Macros',
'wcfg':{'label':'menu button'},
'gridcfg':{'sticky':Tkinter.E}
})
# 4
ifd.append({'widgetType':Tkinter.Entry,
'name':'menuentry',
'defaultValue':'',
'wcfg':{'label':'menu entry'},
'gridcfg':{'sticky':Tkinter.E}
})
# 5
ifd.append({'widgetType':Tkinter.Entry,
'name':'cascade',
'defaultValue':'',
'wcfg':{'label':'cascade'},
'gridcfg':{'sticky':Tkinter.E}
})
# 6
ifd.append({'name': 'loadMacro',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Load Macro',
'bd':6,'command': self.loadMacro_cb},
'gridcfg':{'sticky':Tkinter.E+Tkinter.W},
})
# 7
ifd.append({'widgetType':Tkinter.Button,
'wcfg':{'text':'Dismiss',
'command': self.dismiss_cb}})
return ifd
def guiCallback(self, event=None):
if self.active: return
self.active = 1
val = self.showForm("loadMacro", force=1,modal=0,blocking=0)
ebn = self.cmdForms['loadMacro'].descr.entryByName
ebn['loadMacro']['widget'].configure(state='disabled')
def __call__(self, macroName, macroFile, menuBar='menuRoot',
menuButton='Macros', menuEntry=None, cascade=None, **kw):
"""None<---loadMacro(macroName, macroFile, menuBar='menuRoot',
menuButton='Macros', menuEntry=None, cascade=None, **kw)
"""
self.doitWrapper(macroName, macroFile, menuBar=menuBar,
menuButton=menuButton, menuEntry=menuEntry,
cascade=cascade)
def doit(self, macroName, macroFile, menuBar='menuRoot',
menuButton='Macros', menuEntry=None, cascade=None):
if not hasattr(self, 'macroFile') or macroFile != self.macroFile:
names, macros, docs = self.getMacros(macroFile)
else:
names = self.macNames
macros = self.macMacros
docs = self.macDoc
if len(names) == 0 or len(macros)==0 or len(docs)==0: return
macIndex = names.index(macroName)
macro = macros[macIndex]
from VFCommand import Command, CommandGUI
c = Command(func=macro)
g = CommandGUI()
if cascade:
g.addMenuCommand(menuBar, menuButton, menuEntry,
cascadeName=cascade)
else:
g.addMenuCommand(menuBar, menuButton, menuEntry)
self.vf.addCommand(c, macro.__name__, g)
## class loadMacroCommand(Command):
## """
## Command to load dynamically macro commands.
## Using the Gui the user can open a macro file. The macros available in
## that file are then displayed in a list chooser. When a macro is selected
## in the listchooser, its documentation string is deisplayed and a default
## name for the macro in the viewer is suggested. The user can also specify
## a menuBar, a menuButton as well as an optional cascade name.
## """
## active = 0
## def getMacros(self, file):
## """load all macro functions from file"""
## self.file = file
## _dir, file = os.path.split(file)
## if file[-3:]=='.py': file = file[:-3]
## import sys
## sys.path.insert(0, _dir)
## m = __import__(file, globals(), locals(), [])
## sys.path = sys.path[1:]
## m.__dict__['self'] = self.vf
## import types
## names = []
## macros = []
## doc = []
## for key,value in m.__dict__.items():
## if type(value)==types.FunctionType:
## names.append(key)
## macros.append(value)
## doc.append(value.__doc__)
## return names, macros, doc
## def loadMacLib_cb(self, filename):
## """Call back function for 'Open Macro library' button"""
## # self.ifd[0]['widget'] is the 'Open Macro Library' button
## self.ifd[0]['widget'].configure(relief='sunken')
## #file = os.path.split(filename)[1][:-3]
## names, macros, docs = self.getMacros(filename)
## self.macNames = names
## self.macMacros = macros
## self.macDoc = docs
## # Get a handle to the listchooser widget
## lc = self.ifd[1]['widget']
## lc.clear()
## if len(names) == len(docs):
## entries = map(lambda x, y: (x, y), names, docs)
## else:
## entries = map(lambda x: (x, None), names)
## map(lc.add, entries)
## self.ifd[0]['widget'].configure(relief='raised')
## # set cascade name to libary Name - "mac"
## w = self.ifd[5]['widget']
## w.delete(0, 'end')
## w.insert(0, os.path.split(filename)[1][:-3])
## def setDefaultEntryName(self, event=None):
## """Call back function for the listchooser showing macros.
## gets the name of the currently selected macro and puts it in the entry
## type in"""
## # enable add button
## self.ifd.entryByName['Load Macro']['widget'].configure(state='normal')
## # put default name into name entry
## val = self.ifd[1]['widget'].get()
## w = self.ifd[4]['widget']
## w.delete(0, 'end')
## w.insert(0, val[0])
## self.selectedMac = val[0]
## def addMacro(self, macro, menuBar, menuButton, name, cascade=None):
## from VFCommand import Command, CommandGUI
## c = Command(func=macro)
## g = CommandGUI()
## if cascade:
## g.addMenuCommand(menuBar, menuButton, name, cascadeName=cascade)
## else:
## g.addMenuCommand(menuBar, menuButton, name)
## self.vf.addCommand(c, macro.__name__, g)
## ## g.register(self.vf)
## self.log(file=self.file, macroName=macro.__name__, menuBar=menuBar,
## menuButton=menuButton, name=name, cascade=cascade)
## def loadMacro_cb(self, event=None):
## bar = self.ifd[2]['widget'].get()
## menub = self.ifd[3]['widget'].get()
## name = self.ifd[4]['widget'].get()
## cascade = self.ifd[5]['widget'].get()
## if cascade=='': cascade=None
## macIndex = self.macNames.index(self.selectedMac)
## macFunc = self.macMacros[macIndex]
## self.addMacro(macFunc, bar, menub, name, cascade)
## self.ifd[0]['widget'].configure(relief='raised')
## def customizeGUI(self):
## """create the cascade menu for selecting modules to be loaded"""
## self.selectedMac = ''
## # create the for descriptor
## ifd = self.ifd = InputFormDescr(title='Load macro commands')
## if len(self.vf.libraries) is None:
## modu = __import__('ViewerFramework')
## else:
## modu = __import__(self.vf.libraries[0])
## idir = os.path.split(modu.__file__)[0] + '/Macros'
## if not os.path.exists(idir):
## idir = None
## ifd.append( {'widgetType':'OpenButton', 'text':'Open Macro library ...',
## 'types':[('Macro Module Library', '*Mac.py'),
## ('Any Python Function', '*.py')],
## 'idir':idir,
## 'title':'Open Macro File',
## 'callback': self.loadMacLib_cb } )
## ifd.append({'title':'Choose a macro',
## 'widgetType':ListChooser,
## 'wcfg':{
## 'command':self.setDefaultEntryName,
## 'title':'Choose a macro'},
## 'gridcfg':{'sticky':Tkinter.E+Tkinter.W}} )
## ifd.append({'widgetType':Tkinter.Entry,
## 'defaultValue':'menuRoot',
## 'wcfg':{'label':'menu bar'},
## 'gridcfg':{'sticky':Tkinter.E}
## })
## ifd.append({'widgetType':Tkinter.Entry,
## 'defaultValue':'Macros',
## 'wcfg':{'label':'menu button'},
## 'gridcfg':{'sticky':Tkinter.E}
## })
## ifd.append({'widgetType':Tkinter.Entry,
## 'defaultValue':'',
## 'wcfg':{'label':'menu entry'},
## 'gridcfg':{'sticky':Tkinter.E}
## })
## ifd.append({'widgetType':Tkinter.Entry,
## 'defaultValue':'',
## 'wcfg':{'label':'cascade'},
## 'gridcfg':{'sticky':Tkinter.E}
## })
## ifd.append({'name': 'Load Macro',
## 'widgetType':Tkinter.Button,
## 'text':'Load Macro',
## 'wcfg':{'bd':6},
## 'gridcfg':{'sticky':Tkinter.E+Tkinter.W},
## 'command': self.loadMacro_cb})
## ifd.append({'widgetType':Tkinter.Button,
## 'text':'Dismiss',
## 'command': self.Dismiss_cb})
## def Dismiss_cb(self):
## #self.cmdForms['loadMacro'].withdraw()
## self.ifd.form.destroy()
## self.active = 0
## def guiCallback(self, event=None, file=None):
## if self.active: return
## self.active = 1
## self.customizeGUI()
## self.form = self.vf.getUserInput(self.ifd, modal=0, blocking=0)
## self.ifd.entryByName['Load Macro']['widget'].configure(state='disabled')
## if file: self.loadMacLib_cb(file)
## def __call__(self, file=None, macroName=None, menuBar='menuRoot',
## menuButton='Macros', name=None, cascade=None):
## """file=None, macroName=None, menuBar='menuRoot', menuButton='Macros',
## name=None, cascade=None"""
## if not macroName: self.guiCallback(file=file)
## else:
## if file[-3:]=='.py': file = file[:-3]
## names, macros, docs = self.getMacros(file)
## i = names.index(macroName)
## if name==None: name=macroName
## self.addMacro(macros[i], menuBar, menuButton, name, cascade)
class ShellCommand(Command):
"""Command to show/Hide the Python shell.
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : ShellCommand
\nCommand : Shell
\nSynopsis:\n
None<---Shell()
"""
def onAddCmdToViewer(self):
if self.vf.hasGui:
self.vf.GUI.pyshell.top.protocol('WM_DELETE_WINDOW',
self.vf.Shell.onDestroy)
def show(self):
self.vf.GUI.pyshell.top.deiconify()
def hide(self):
self.vf.GUI.pyshell.top.withdraw()
def __call__(self, *args):
"""None<---Shell()
"""
if args[0]:
self.show()
self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(1)
else:
self.hide()
self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(0)
def guiCallback(self):
on = self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].get()
if on: self.show()
else: self.hide()
def onDestroy(self):
self.vf.GUI.toolbarCheckbuttons['Shell']['Variable'].set(0)
self.hide()
ShellCommandGUI = CommandGUI()
ShellCommandGUI.addToolBar('Shell', icon1='PyShell.gif',
balloonhelp='Python IDLE Shell', index=1)
class SaveSessionCommand(Command):
"""Command to allow the user to save the session as it is in a file.
It logs all the transformation.
\nPackage : Pmv
\nModule : customizationCommands.py
\nClass : SaveSessionCommand
"""
def logString(self, *args, **kw):
"""return None as log string as we don't want to log this
"""
pass
def guiCallback(self, event=None):
### FIXME all the logs should be in a stack and not in a file.
if self.vf.logMode == 'no':
self.vf.warningMsg("No log information because logMode was set to no.")
return
newfile = self.vf.askFileSave(types = [
('Pmv sesion files', '*.psf'),
('all files', '*.py')],
defaultextension=".psf",
title = 'Save Session in File:')
if not newfile is None:
self.doitWrapper(newfile, redraw=0)
def doit(self, filename):
#print "SaveSessionCommand.doit"
ext = os.path.splitext(filename)[1].lower()
if ext=='.psf':
self.vf.saveFullSession(filename)
else:
import shutil
# get the current log.
if hasattr(self.vf, 'logAllFile'):
logFileName = self.vf.logAllFile.name
self.vf.logAllFile.close()
if filename!=logFileName:
shutil.copy(logFileName, filename)
self.vf.logAllFile = open(logFileName,'a')
# Add to it the transformation log.
logFile = open(filename,'a')
vi = self.vf.GUI.VIEWER
code = vi.getViewerStateDefinitionCode('self.GUI.VIEWER')
code.extend( vi.getObjectsStateDefinitionCode('self.GUI.VIEWER') )
if code:
for line in code:
logFile.write(line)
if vi.GUI.contourTk.get():
controlpoints=vi.GUI.curvetool.getControlPoints()
sensitivity=vi.GUI.d1scalewheel.get()
logFile.write("self.GUI.VIEWER.GUI.curvetool.setControlPoints(%s)" %controlpoints)
logFile.write("\n")
logFile.write("self.GUI.VIEWER.GUI.curvetool.setSensitivity(%s)" %sensitivity)
#sceneLog = self.vf.Exit.logScene()
#for l in sceneLog:
# l1 = l+'\n'
# logFile.write(l1)
logFile.close()
if hasattr(self.vf, 'recentFiles'):
self.vf.recentFiles.add(filename, 'readSourceMolecule')
# SaveSessionCommand Command GUI
SaveSessionCommandGUI = CommandGUI()
SaveSessionCommandGUI.addMenuCommand(
'menuRoot', 'File', 'Current Session', index=2,
cascadeName='Save', cascadeIndex=2, separatorAboveCascade=1)
SaveSessionCommandGUI.addToolBar('Save', icon1='filesave.gif',
type='ToolBarButton',
balloonhelp='Save Session', index=1)
class ExitCommand(Command):
"""Command to destroy application
\nPackage : ViewerFramework
\nModule : basicCommand.py
\nClass : ExitCommand
\nCommand : Exit
\nSynopsis:\n
None<---Exit(ask)
\nask = Flag when set to 1 a form asking you if you really want to quit
will popup, it will quit directly if set to 0
"""
def onAddCmdToViewer(self):
#print "ExitComand.onAddCmdToViewer"
import warnings
if self.vf.hasGui:
self.vf.GUI.ROOT.protocol('WM_DELETE_WINDOW',self.askquit)
def logObjectTransformations(self, object):
warnings.warn( "logObjectTransformations is deprecated",
DeprecationWarning, stacklevel=2)
log = []
# FIXME won't work with instance matrices
mat = object.GetMatrix(object)
import numpy.oldnumeric as Numeric
log.append("self.transformObject('rotation', '%s', matrix=%s,log=0)"%(object.fullName,tuple(object.rotation)))
log.append("self.transformObject('translation', '%s', matrix=%s, log=0 )"%(object.fullName, tuple(object.translation)))
log.append("self.transformObject('scale', '%s', matrix=%s, log=0 )"%(object.fullName,tuple(object.scale)))
log.append("self.transformObject('pivot', '%s', matrix=%s, log=0 )"%(object.fullName,tuple(object.pivot)))
return log
def logObjectMaterial(self, object):
warnings.warn("logObjectMaterial is deprecated",
DeprecationWarning, stacklevel=2)
log = []
from opengltk.OpenGL import GL
log.append("from opengltk.OpenGL import GL")
mat = object.materials[GL.GL_FRONT]
log.append("self.setObject('%s', materials=%s, propName='ambi', matBind=%d)" % (object.fullName, repr(mat.prop[0])[6:-5],mat.binding[0]))
log.append("self.setObject('%s', materials=%s, propName='diff', matBind=%d)" % (object.fullName, repr(mat.prop[1])[6:-5],mat.binding[1]))
log.append("self.setObject('%s', materials=%s, propName='emis', matBind=%d)" % (object.fullName, repr(mat.prop[2])[6:-5],mat.binding[2]))
log.append("self.setObject('%s', materials=%s, propName='spec', matBind=%d)" % (object.fullName, repr(mat.prop[3])[6:-5],mat.binding[3]))
log.append("self.setObject('%s', materials=%s, propName='shini', matBind=%d)" % (object.fullName, repr(mat.prop[4])[6:-5],mat.binding[4]))
mat = object.materials[GL.GL_BACK]
log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='ambi', matBind=%d)" % (object.fullName, repr(mat.prop[0])[6:-5],mat.binding[0]))
log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='diff', matBind=%d)" % (object.fullName, repr(mat.prop[1])[6:-5],mat.binding[1]))
log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='spec', matBind=%d)" % (object.fullName, repr(mat.prop[2])[6:-5],mat.binding[2]))
log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='emis', matBind=%d)" % (object.fullName, repr(mat.prop[3])[6:-5],mat.binding[3]))
log.append("self.setObject('%s', materials=%s, polyFace=GL.GL_BACK,propName='shini', matBind=%d)" % (object.fullName, repr(mat.prop[4])[6:-5],mat.binding[4]))
return log
def logCameraTransformations(self, camera):
warnings.warn("logCameraTransformations is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setCamera('%s', \n"%camera.name
logStr = logStr + "rotation=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),\n"%tuple(camera.rotation)
logStr=logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.translation)
logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.scale)
logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.pivot)
logStr = logStr + "lookAt=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.lookAt)
logStr = logStr + "lookFrom=(%9.3f, %9.3f, %9.3f),\n"%tuple(camera.lookFrom)
logStr = logStr + "direction=(%9.3f, %9.3f, %9.3f))"%tuple(camera.direction)
return logStr+'\n'
def logCameraProp(self, camera):
warnings.warn("logCameraProp is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setCamera('%s', \n"%camera.name
logStr = logStr + "width=%d, height=%d, rootx=%d, rooty=%d,"%\
(camera.width, camera.height, camera.rootx, camera.rooty)
logStr = logStr + "fov=%f, near=%f, far=%f,"%\
(camera.fovy, camera.near, camera.far)
logStr = logStr + "color=(%6.3f,%6.3f,%6.3f,%6.3f))"%\
tuple(camera.backgroundColor)
return logStr+'\n'
def logLightTransformations(self, light):
warnings.warn("logLightTransformations is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setLight('%s', \n"%light.name
logStr = logStr + "rotation=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),\n"%tuple(light.rotation)
logStr = logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.translation)
logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.scale)
logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f),\n"%tuple(light.pivot)
logStr = logStr + "direction=(%9.3f,%9.3f,%9.3f,%9.3f))"%tuple(light.direction)
return logStr+'\n'
def logLightProp(self, light):
warnings.warn("logLightProp is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setLight('%s', \n"%light.name
logStr = logStr + "enable=%d, visible=%d, length=%f,\n"%\
(light.enabled, light.visible, light.length)
logStr = logStr + "ambient=(%6.3f,%6.3f,%6.3f,%6.3f),\n"%\
tuple(light.ambient)
logStr = logStr + "specular=(%6.3f,%6.3f,%6.3f,%6.3f),\n"%\
tuple(light.specular)
logStr = logStr + "diffuse=(%6.3f,%6.3f,%6.3f,%6.3f))\n"%\
tuple(light.diffuse)
return logStr+'\n'
def logClipTransformations(self, clip):
warnings.warn("logClipTransformations is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setClip('%s', \n"%clip.name
logStr = logStr + "rotation=(%9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f, %9.3f),\n"%tuple(clip.rotation)
logStr = logStr + "translation=(%9.3f, %9.3f, %9.3f),\n"%tuple(clip.translation)
logStr = logStr + "scale=(%9.3f, %9.3f, %9.3f),\n"%tuple(clip.scale)
logStr = logStr + "pivot=(%9.3f, %9.3f, %9.3f))\n"%tuple(clip.pivot)
return logStr+'\n'
def logClipProp(self, clip):
warnings.warn("logClipProp is deprecated",
DeprecationWarning, stacklevel=2)
logStr = "self.setClip('%s', \n"%clip.name
logStr = logStr + "visible=%d, lineWidth=%f,\n"%\
(clip.visible, clip.lineWidth)
logStr = logStr + "color=(%6.3f,%6.3f,%6.3f,%6.3f))\n"%\
tuple(clip.color)
return logStr+'\n'
def logAddClipPlanes(self, object):
warnings.warn("logAddClipPlanes is deprecated",
DeprecationWarning, stacklevel=2)
log = []
for c in object.clipP:
log.append("self.addClipPlane('%s','%s', %d, %d)\n"%\
(object.fullName, c.name, object.clipSide[c.num], 0))
for c in object.clipPI:
log.append("self.addClipPlane('%s','%s', %d, %d)\n"%\
(object.fullName, c.name, object.clipSide[c.num], 1))
return log
def logScene(self):
warnings.warn("logScene is deprecated",
DeprecationWarning, stacklevel=2)
log = []
vi = self.vf.GUI.VIEWER
for c in vi.cameras:
if c._modified:
log.append(self.logCameraTransformations(c))
log.append(self.logCameraProp(c))
for l in vi.lights:
if l._modified:
log.append(self.logLightTransformations(l))
log.append(self.logLightProp(l))
for c in vi.clipP:
if c._modified:
log.append(self.logClipTransformations(c))
log.append(self.logClipProp(c))
root = self.vf.GUI.VIEWER.rootObject
for o in root.AllObjects():
if not o.transformIsIdentity():
log.extend(self.logObjectTransformations(o))
if o._modified:
log.extend(self.logAddClipPlanes(o))
log.extend(self.logObjectMaterial(o))
# Trigger a Viewer Redraw at the end.
log.append("self.GUI.VIEWER.Redraw()")
return log
def savePerspective(self):
if self.vf.resourceFile:
rcFile = os.path.join(os.path.split(self.vf.resourceFile)[0], "perspective")
else:
rcFolder = getResourceFolderWithVersion()
rcFile = os.path.join(rcFolder, "ViewerFramework", "perspective")
try:
rcFile = open(rcFile, 'w')
except Exception, inst: #to avoid "IOError: [Errno 116] Stale NFS file handle" error message when running the tests
return
if self.vf.GUI.floatCamVariable.get():
rcFile.write("self.GUI.floatCamera()\n")
geom = self.vf.GUI.vwrCanvasFloating.geometry()
dum,x0,y0 = geom.split('+')
w,h = [int(x) for x in dum.split('x')]
rcFile.write("self.setCameraSize(%s, %s, xoffset=%s, yoffset=%s)\n"%(w,h,x0,y0))
xywh = self.vf.GUI.getGeom()
#make sure that xywh are within screen coordinates
if xywh[0]+xywh[2] > self.vf.GUI.ROOT.winfo_screenwidth() or\
xywh[1]+xywh[3] > self.vf.GUI.ROOT.winfo_screenheight():
rcFile.write("#"+str(xywh)+"\n")
else:
rcFile.write("self.GUI.setGeom"+str(xywh)+"\n")
# txt = self.vf.GUI.MESSAGE_BOX.tx.get().split("\n")
# if len(txt) > 5:
# txt = txt[5:]
# linesToWrite = []
# for line in txt:
# if line.startswith("self.browseCommands"):
# linesToWrite.append(line)
# linesToWrite = set(linesToWrite)
# for line in linesToWrite:
# line = line.replace('log=0','log=1')
# rcFile.write(line)
# rcFile.write("\n")
rcFile.close()
def __call__(self, ask, **kw):
"""None <- Exit(ask, **kw)
\nask = Flag when set to 1 a form asking you if you really want to quit
will popup, it will quit directly if set to 0.
"""
kw['redraw'] = 0
kw['log'] = 0
kw['busyIdle'] = 0
kw['setupUndo'] = 0
apply(self.doitWrapper, (ask,),kw)
def doit(self, ask):
#print "ExitComand.quit_cb"
logPref = self.vf.userpref['Transformation Logging']['value']
if logPref == 'continuous':
if hasattr(self.vf.GUI,'pendingLog') and self.vf.GUI.pendingLog:
self.vf.log(self.vf.GUI.pendingLog[-1])
if self.vf.userpref.has_key('Save Perspective on Exit'):
logPerspective = self.vf.userpref['Save Perspective on Exit']['value']
if logPerspective == 'yes':
self.savePerspective()
elif logPref == 'final':
#changed 10/24/2005-RH
##code = self.logScene()
#vi = self.vf.GUI.VIEWER
#code = vi.getViewerStateDefinitionCode('self.GUI.VIEWER')
#code.extend( vi.getObjectsStateDefinitionCode('self.GUI.VIEWER') )
#if code:
# for line in code:
# self.vf.log(line)
if hasattr(self.vf, 'logAllFile'):
self.vf.saveSession(self.vf.logAllFile.name)
if ask:
## from ViewerFramework.gui import InputFormDescr
# from mglutil.gui.InputForm.Tk.gui import InputFormDescr
# self.idf = InputFormDescr(title='Do you wish to Quit?')
# self.idf.append({'widgetType':Tkinter.Button,
# 'wcfg':{'text':'QUIT',
# 'width':10,
# 'command':self.quit_cb},
# 'gridcfg':{'sticky':'we'}})
#
# self.idf.append({'widgetType':Tkinter.Button,
# 'wcfg':{'text':'CANCEL',
# 'width':10,
# 'command':self.cancel_cb},
# 'gridcfg':{'sticky':'we', 'row':-1}})
# val = self.vf.getUserInput(self.idf, modal=1, blocking=0,
# okcancel=0)
self.vf.GUI.ROOT.after(10,self.askquit)
else:
self.quit_cb()
def quit_cb(self):
#print "ExitComand.quit_cb"
self.vf.GUI.softquit_cb()
def cancel_cb(self):
form = self.idf.form
form.root.destroy()
return
def guiCallback(self):
#print "ExitComand.guiCallback"
self.doitWrapper(1, redraw=0, log=0)
def askquit(self):
#print "ExitComand.askquit"
import tkMessageBox
ok = tkMessageBox.askokcancel("Quit?","Do you Wish to Quit?")
if ok:
if hasattr(self.vf, 'openedSessions'):
import shutil
for folder in self.vf.openedSessions:
print 'removing session directory', folder
shutil.rmtree(folder)
self.afterDoit = None
self.vf.GUI.ROOT.after(10,self.vf.GUI.quit_cb)
class customAnimationCommand(Command):
"""Command to start Custom Animation notebook widget
"""
def __init__(self, func=None):
Command.__init__(self, func)
self.root = None
self.animNB = None
def guiCallback(self):
self.startCustomAnim_cb()
def __call__(self, **kw):
"""None <- customAnimation"""
add = kw.get('add', None)
if add is None:
add = 1
else: assert add in (0, 1)
if self.vf.GUI.toolbarCheckbuttons.has_key('customAnimation'):
self.vf.GUI.toolbarCheckbuttons['customAnimation']['Variable'].set(add)
self.startCustomAnim_cb()
def startCustomAnim_cb(self):
on = self.vf.GUI.toolbarCheckbuttons['customAnimation']['Variable'].get()
if on:
if not self.animNB:
from Pmv.scenarioInterface.animationGUI import AnimationNotebook
self.root = Tkinter.Toplevel()
self.root.title('Custom Animation')
self.root.protocol("WM_DELETE_WINDOW", self.hide_cb)
vi = self.vf.GUI.VIEWER
self.animNB = AnimationNotebook(self.vf, self.root)
else:
self.show_cb()
else:
self.hide_cb()
def hide_cb(self):
if self.root:
self.root.withdraw()
self.vf.GUI.toolbarCheckbuttons['customAnimation']['Variable'].set(0)
def show_cb(self, event=None):
if self.root:
self.root.deiconify()
self.vf.GUI.toolbarCheckbuttons['customAnimation']['Variable'].set(1)
def onAddCmdToViewer(self):
if self.vf.hasGui:
# add a page for scenario
page = self.scenarioMaster = self.vf.GUI.toolsNoteBook.add("AniMol")
from Pmv.scenarioInterface.animationGUI import AnimationNotebook
self.animNB = AnimationNotebook(self.vf, page)
button = self.vf.GUI.toolsNoteBook.tab(1)
button.configure(command=self.adjustWidth)
def adjustWidth(self):
self.vf.GUI.toolsNoteBook.selectpage(1)
self.vf.GUI.workspace.configurepane('ToolsNoteBook',size=self.animNB.master.winfo_width())
```
#### File: MGLToolsPckgs/ViewerFramework/hostApp.py
```python
from ViewerFramework.VFCommand import Command
from ViewerFramework.VF import LogEvent
import traceback,sys
class HostApp:
"""
support a host application in which ViewerFramework is embedded
handle log event and execute interpreted command in the host app
"""
def __init__(self, vf, hostApp, debug=0):
self.vf = vf # ViewerFramework which is embedded
self.driver = None # is set by self._setDriver
self.debug=debug
# redirect stderr to file
# open file for logging commands executed by self.vf
if self.debug == 1 :
self.vf.pmvstderr=open('/tmp/pmvstderr','w')
sys.stderr=self.vf.pmvstderr
self.vf.abclogfiles=open('/tmp/logEvent','w')
print 'logEvent',self.vf.abclogfiles
else:
self.vf.pmvstderr=None
self.vf.abclogfiles = None
# create host application driver
# this driver creates the connection between VF and the host application
self.hostname = hostApp
self._setDriver(hostApp)
# register the function to be called when a log string is generated by VF
# this function will create an equivalent cmd for the hot application
# and have the host app run this command
self.vf.registerListener(LogEvent, self.handleLogEvent)
#Variable for the server-client mode
self.servers = [] # list of (host, portNum) used to connect PMV server applications
self._stop = False # set to True to stop executing commands sent by servers
self.thread=None # the thread used to apply the command from the server
def _setDriver(self,hostApp):
"""
Define the host application and call the approriate command interpreter
setDriver(hostApp)
hostApp is case in-sensitive string which can be 'Blender' or 'c4d'
raises ValueError if the hostApp is invalid
"""
#from mglutil.hostappInterface import appliDriver
from Pmv.hostappInterface import appliDriver
#currently hostApp have to be c4d,blender or maya
self.driver=appliDriver.HostPmvCommand(soft=hostApp.lower())
def handleLogEvent(self, event):
"""
Function call everytime the embeded pmv create a log event, cf a command is execute with the keyword log=1
"""
import sys
mesgcmd='' #the message command string
lines=event.logstr.split('\n') #the last log event ie the last command string
for line in lines :
#parse and interprete the pmv command to generate the appropriate host appli command
func,arg=self.driver.parseMessageToFunc(line)
temp=self.driver.createMessageCommand(func,arg,line)
mesgcmd+=temp
if self.debug ==1 :
self.vf.abclogfiles.write("################\n"+self.hostname+"_CMD\n"+mesgcmd+'\n')
self.vf.abclogfiles.flush()
self.vf.pmvstderr.flush()
#try to exec the command generated, using keywords dictionary
try:
exec(mesgcmd, {'self':self.vf,'mv':self.vf,'pmv':self.vf})
except :
import sys,traceback
tb=traceback.format_exc()
raise ValueError(tb)
if self.debug ==1:
# tb = traceback.extract_tb(sys.exc_traceback)
self.vf.abclogfiles.write("exeption\n"+str(tb)+"\n")
self.vf.abclogfiles.flush()
######Dedicated function for the client-server mode#################
def runServerCommandLoop(self):
"""
Infinite loop which call the viewerframework runservercommand
"""
while not self._stop:
self.vf.runServerCommands()
def setServer(self,address,port):
"""
Define the server,portnumeber of the server
"""
self.servers=[address,port]
def start(self):
"""
Connect to the server and start the thread which permit the execution of the server command
"""
self.vf.socketComm.connectToServer(self.servers[0],self.servers[1],self.vf.server_cb)
from Queue import Queue
self.vf.cmdQueue = Queue(-1)
import thread
self._stop=False
if self.thread==None :
self.thread=thread.start_new(self.runServerCommandLoop, ())
if self.debug ==1:
sys.stderr.write('ok thread\n')
self.vf.pmvstderr.flush()
def stop(self):
#stop the infinite loop and diconect from the server
self._stop=True
self.vf.socketComm.disconnectFromServer(self.servers[0],self.servers[1])
```
#### File: MGLToolsPckgs/ViewerFramework/imdCommands.py
```python
from ViewerFramework.VFCommand import Command
from Pmv.moleculeViewer import EditAtomsEvent
import struct
import numpy
from numpy import matrix
import sys, os
from socket import *
if os.name == 'nt': #sys.platform=='win32':
mswin = True
else:
mswin = False
HEADERSIZE=8
IMDVERSION=2
IMD_DISCONNECT=0 #//!< close IMD connection, leaving sim running 0
IMD_ENERGIES=1 #//!< energy data block 1
IMD_FCOORDS=2 #//!< atom coordinates 2
IMD_GO=3 #//!< start the simulation 3
IMD_HANDSHAKE=4 #//!< endianism and version check message 4
IMD_KILL=5 #//!< kill the simulation job, shutdown IMD 5
IMD_MDCOMM=6 #//!< MDComm style force data 6
IMD_PAUSE=7 #//!< pause the running simulation 7
IMD_TRATE=8 #//!< set IMD update transmission rate 8
IMD_IOERROR=9 #//!< indicate an I/O error 9
class vmdsocket:
def __init__(self):
self.addr=None #!< address of socket provided by bind()
self.port=None
self.addrlen=None #!< size of the addr struct
self.sd=None #< socket descriptor
class File2Send:
def __init__(self):
self.data=None
self.length=None
self.buffer=None
#Convert a 32-bit integer from host to network byte order.
def imd_htonl(self,h) :
return htonl(h)
#Convert a 32-bit integer from network to host byte order.
def imd_ntohl(self,n) :
return ntohl(n)
def fill(self, data):
self.data = data
self.length = len(data)#self.imd_htonl(len(data))
def swap_header(self) :
#pass
#self.imdtype = self.imd_ntohl(self.imdtype)
self.length = self.imd_ntohl(self.length )
def getBinary(self):
"""Returns the binary message (so far) with typetags."""
length = struct.pack(">i", int(self.length))
if len(self.data) == 0 :
return length
for l in self.data:
length += struct.pack(">i", len(l))
for i in l :
length += struct.pack(">c", i)
self.buffer = length
return length
class Bonds2Send(File2Send):
def getBinary(self):
"""Returns the binary message (so far) with typetags."""
length = struct.pack(">i", int(self.length))
if len(self.data) == 0 :
return length
for l in self.data:
print l
for j in range(len(l)):
length += struct.pack(">i", int(l[j]))
self.buffer = length
return length
class IMDheader:
def __init__(self):
self.imdtype=None
self.length=None
self.buffer=None
#Convert a 32-bit integer from host to network byte order.
def imd_htonl(self,h) :
return htonl(h)
#Convert a 32-bit integer from network to host byte order.
def imd_ntohl(self,n) :
return ntohl(n)
def fill_header(self, IMDType, length):
self.imdtype = IMDType#self.imd_htonl(IMDType)
self.length = length# self.imd_htonl(length)
def swap_header(self) :
self.imdtype = self.imd_ntohl(self.imdtype)
self.length = self.imd_ntohl(self.length )
def getBinary(self):
"""Returns the binary message (so far) with typetags."""
types = struct.pack(">i", int(self.imdtype))
length = struct.pack(">i", int(self.length))
return types + length
class IMDEnergies:
def __init__(self):
self.buffer = None
self.tstep = None #//!< integer timestep index
self.T = None #//!< Temperature in degrees Kelvin
self.Etot = None #//!< Total energy, in Kcal/mol
self.Epot = None #//!< Potential energy, in Kcal/mol
self.Evdw = None #//!< Van der Waals energy, in Kcal/mol
self.Eelec = None #//!< Electrostatic energy, in Kcal/mol
self.Ebond = None #//!< Bond energy, Kcal/mol
self.Eangle = None #//!< Angle energy, Kcal/mol
self.Edihe = None #//!< Dihedral energy, Kcal/mol
self.Eimpr = None #//!< Improper energy, Kcal/mol
self.len = 9*12+1*4 #number of element->9 float (12bit) 1 int (4bit)
class IMD(Command):
""" This class implements method to connect to a server."""
def checkDependencies(self, vf):
import thread
def init(self,hostname,
mode,
IMDwait_,
IMDport_,
IMDmsg_,
IMDlogname_,
length
):
self.current_buffer = None
self.current_send_buffer = None
self.mol = None
self.slot = None
self.imd_coords = numpy.zeros((length,3),'f')
self.pause = False
self.gui = False
self.ffreq = 30
self.rates = 1
blen = 1024
hname=""
str=""
IMDport=IMDport_
if ( IMDlogname_ == 0 ) :
IMDlog = sys.stderr
else :
IMDlog = open ( IMDlogname_, "w")
if ( IMDlog == 0 ) :
IMDlog.write("MDDriver > Bad filename, using stderr\n")
IMDmsg = IMDmsg_
#IMDmsg < 0 force to display to stderr (IMDlog=stderr)
if( IMDmsg < 0) :
IMDmsg = -IMDmsg
IMDlog = sys.stderr
IMDlog.write("MDDriver > Negative IMDmsg - Setting IMDlog=stderr \n")
if (IMDmsg > 1) :
IMDlog.write("MDDriver > ---- Entering in %s\n"%sys._getframe().f_code.co_name)
IMDwait = IMDwait_ # IMDwait = 1 -> blocking
IMDignore = 0
#if ( self.vmdsock_init() ):
# IMDlog.write("MDDriver > Unable to initialize socket interface for IMD.\n")
IMDignore = 1;
self.sock = self.vmdsock_create();
self.vmdsock_connect(self.sock , hostname, IMDport)
#before handshacking do we need to send the files
if self.mindy:
self.sendFiles()
print "fileSend"
IMDswap = self.imd_recv_handshake(self.sock);
print "IMDswap",IMDswap
"""
if ( IMDswap == 0 ){
fprintf(IMDlog, "MDDriver > Same endian machines\n");
}
else if ( IMDswap == 1 ) {
fprintf(IMDlog, "MDDriver > Different endian machines\n");
}
else {
fprintf(IMDlog,
"MDDriver > Unknown endian machine - disconnecting\n");
if (sock) {
imd_disconnect(sock);
vmdsock_shutdown(sock);
vmdsock_destroy(sock);
sock = 0;
if (IMDmsg > 1)
fprintf( IMDlog, "MDDriver > ---- Leaving %s\n", __FUNCTION__);
"""
imd_event = -1;
#return ( IMDlog )
def vmdsock_create(self) :
s=vmdsocket()
#open socket using TCP/IP protocol family, using a streaming type and the
#default protocol. This is connection-oriented, sequenced, error-controlled
#and full-duplex
#ref Wall p.380
s.sd = socket(AF_INET, SOCK_STREAM) #no PF_INET in python
if s.sd is None :
print "Failed to open socket."
# TODO: provide error detail using errno
return None
return s
def vmdsock_connect(self, vmdsocket, host, port) :
#vmdsock_connect(sock, hostname, IMDport)
s = vmdsocket
host = gethostbyname(host)
s.port = port
s.addr = host
s.sd.connect( ( host, port))
def vmdsock_write(self,s, header, size) :#s, header, HEADERSIZE
header.swap_header()
buf = header.getBinary()
s.sd.send(buf)
#return len(buf)
def vmdsock_read(self,s, ptr, size) :#socket, header, HEADERSIZE=8
buf = s.sd.recv(size)
if isinstance(ptr,IMDheader):
ptr.buffer=buf
ptr.imdtype=struct.unpack(">i", buf[0:4])[0]
ptr.length =struct.unpack(">i", buf[4:])[0]
elif isinstance(ptr,IMDEnergies):
ptr.buffer= buf
ptr.tstep = ntohl(struct.unpack(">i", buf[0:4])[0]) #//!< integer timestep index
rest=buf[4:]
ptr.T = struct.unpack("f", rest[0:4])[0] #//!< Temperature in degrees Kelvin
rest=rest[4:]
ptr.Etot = struct.unpack("f", rest[0:4])[0] #//!< Total energy, in Kcal/mol
rest=rest[4:]
ptr.Epot = struct.unpack("f", rest[0:4])[0] #//!< Potential energy, in Kcal/mol
rest=rest[4:]
ptr.Evdw = struct.unpack("f",rest[0:4])[0] #//!< Van der Waals energy, in Kcal/mol
rest=rest[4:]
ptr.Eelec = struct.unpack("f", rest[0:4])[0] #//!< Electrostatic energy, in Kcal/mol
rest=rest[4:]
ptr.Ebond = struct.unpack("f", rest[0:4])[0] #//!< Bond energy, Kcal/mol
rest=rest[4:]
ptr.Eangle = struct.unpack("f", rest[0:4])[0] #//!< Angle energy, Kcal/mol
rest=rest[4:]
ptr.Edihe = struct.unpack("f", rest[0:4])[0] #//!< Dihedral energy, Kcal/mol
rest=rest[4:]
ptr.Eimpr = struct.unpack("f", rest[0:4])[0] #//!< Improper energy, Kcal/mol
elif isinstance(ptr,numpy.ndarray):
self.current_buffer = buf[:]
rest=buf[:]
#print "len",int(ptr.shape[0])
for i in range(int(ptr.shape[0])):
for j in range(3):
#print i,j,struct.unpack("f", rest[0:4])
try :
ptr[i][j]=float(struct.unpack("f", rest[0:4])[0])
rest=rest[4:]
except :
pass#print i,j, rest[0:4]
#print "ok"
#return len(buf)
def vmdsock_selread(self,vmdsocket, sec):
pass
#s = vmdsocket
#fd_set rfd;
#struct timeval tv;
#int rc;
#
#FD_ZERO(&rfd);
#FD_SET(s->sd, &rfd);
#memset((void *)&tv, 0, sizeof(struct timeval));
#tv.tv_sec = sec;
#do {
# rc = select(s->sd+1, &rfd, NULL, NULL, &tv);
#while (rc < 0 && errno == EINTR);
#return rc;
def sendOne(self,data,sender):
sender.fill(data)
buf=sender.getBinary()
res=self.sock.sd.send(buf)
print "res",res
def sendFiles(self):
#first get the pdb/psf
try :
from MDTools.md_AtomGroup import Molecule
except :
print "no MDTools package, cancel action"
return
m = self.m =Molecule(self.pdbFile,self.psfFile)
s2Send = File2Send()
b2Send = Bonds2Send()
#need to send pdb
print "pdb"
self.sendOne(m.pdbLines,s2Send)
#need to send the parmaFile
o = open(self.paraFile,'r')
data = o.readlines()
o.close()
print "param"
self.sendOne(data,s2Send)
#need to send psf file
print "psf"
self.sendOne(m.psfAtomsLines,s2Send)
self.sendOne(m._bonds,b2Send)
self.sendOne(m._angles,b2Send)
self.sendOne(m._dihedrals,b2Send)
self.sendOne(m._impropers,b2Send)
self.sendOne([],s2Send)
#need then to send fixed atoms
print "atomsF"
self.sendOne([],s2Send)
def imd_pause(self):
header=IMDheader()
header.fill_header(IMD_PAUSE, 0)
self.pause = not self.pause
return (self.imd_writen(self.sock, header, HEADERSIZE) != HEADERSIZE)
def imd_go(self):
#swap ?
header=IMDheader()
header.fill_header(IMD_GO, 0)
#print "type", header.imdtype
header.swap_header()
print "type", header.imdtype
return (self.imd_writen(self.sock, header, HEADERSIZE) != HEADERSIZE)
def imd_send_fcoords(self,n,coords):
size = HEADERSIZE+12*n
header=IMDheader()
header.fill_header(IMD_FCOORDS, n)
#header.swap_header()
buf = header.getBinary()
#need to pack coords (float*3)
self.current_send_buffer = buf + self.packFloatVectorList(coords)
self.sock.sd.send(self.current_send_buffer)
def imd_send_mdcomm(self,n,indices,forces):
"""
send n forces to apply to n atoms of indices indices
"""
#rc=0
size = HEADERSIZE+16*n
header=IMDheader()
header.fill_header(IMD_MDCOMM, n)
header.swap_header()
buf = header.getBinary()
#need to pack indices (int) and forces (float*3)
indiceBuff = self.packIntegerList(indices)
forcesBuff = self.packFloatVectorList(forces)
buffer = buf + indiceBuff + forcesBuff
self.current_send_buffer = buffer
self.sock.sd.send(buffer)
#return rc
def imd_readn(self,s,ptr,n) : #socket, header, HEADERSIZE=8
#print "readN"#nread=None
nleft = n
self.vmdsock_read(s, ptr, nleft)
return n
"""
while (nleft > 0) :
if ((nread = self.vmdsock_read(s, ptr, nleft)) < 0) {
if (errno == EINTR)
nread = 0; # and call read() again */
else
return -1;
else if (nread == 0)
break; /* EOF */
nleft -= nread;
ptr += nread;
return n-nleft
"""
def imd_writen(self,s,ptr,n) :
nleft = n
nwritten=None
self.vmdsock_write(s, ptr, nleft)
del ptr
return 0
"""
while (nleft > 0):
if ((nwritten = self.vmdsock_write(s, ptr, nleft)) <= 0) :
if (errno == EINTR):
nwritten = 0;
else
return -1
nleft -= nwritten;
ptr += nwritten;
return n
"""
def imd_recv_handshake(self,s) :
buf=None
IMDType=None
#print "handscheck"
# Wait up to 5 seconds for the handshake to come
#if (self.vmdsock_selread(s, 5) != 1) return -1;
#import time
#time.sleep(5.)
# Check to see that a valid handshake was received */
header = self.imd_recv_header_nolengthswap(s);
#print "handscheck rcv"
#print header.imdtype, IMD_HANDSHAKE
if (header.imdtype != IMD_HANDSHAKE) : return -1
#ok send imd_go
#print "imd_go"
self.imd_go()
#if header.length == IMDVERSION :
# if (not self.imd_go(s)) : return 0
#header.swap_header()
#if header.length == IMDVERSION :
# if (not self.imd_go(s)) : return 0
return -1;
"""
# Check its endianness, as well as the IMD version. */
if (buf == IMDVERSION) {
if (!imd_go(s)) return 0;
return -1;
}
imd_swap4((char *)&buf, 4);
if (buf == IMDVERSION) {
if (!imd_go(s)) return 1;
}
#/* We failed to determine endianness. */
return -1;
"""
#/* The IMD receive functions */
def imd_recv_header_nolengthswap(self,socket) :
header=IMDheader()
if (self.imd_readn(socket, header, HEADERSIZE) != HEADERSIZE):
return IMD_IOERROR;
#header.swap_header()
return header;
def imd_recv_header(self,socket) :
header=IMDheader()
if (self.imd_readn(socket, header, HEADERSIZE) != HEADERSIZE):
return IMD_IOERROR;
#header.swap_header()
return header;
def imd_recv_mdcomm(self, n, indices, forces) :
if (self.imd_readn(self.sock, indices, 4*n) != 4*n) : return 1
if (self.imd_readn(self.sock, forces, 12*n) != 12*n) : return 1
return 0;
def imd_recv_energies(self, imdEnergies) :
return (self.imd_readn(self.sock, imdEnergies, 1024)
!= imdEnergies.len);
def imd_recv_fcoords(self, n, coords) :
return (self.imd_readn(self.sock, coords, 12*n) != 12*n);
def getType(self,bytes):
types=""
for i in range(len(bytes)):
types=types+str(ord(bytes[i]))
return types
def readInt(self,data):
if(len(data)<4):
print "Error: too few bytes for int", data, len(data)
rest = data
integer = 0
else:
integer = struct.unpack(">i", data[0:4])[0]
rest = data[4:]
return (integer, rest)
def packIntegerList(self,listeI):
buffer = ''
for i in listeI:
buffer += struct.pack("i", i)
return buffer
def packFloatVectorList(self,listeV):
buffer = ''
for vector in listeV:
for j in vector :
buffer += struct.pack("f", j)
return buffer
def start(self,func=None):
import thread
self.lock = thread.allocate_lock()
if self.pause : self.imd_pause()
thread.start_new(self.listenToImdServer, (func,))
def mindySend(self):
from ARViewer import util
import numpy.oldnumeric as Numeric
coords=[]
for m in self.mol:
if hasattr(self.vf,'art'):
M = m.pat.mat_transfo
vt = []
vt=util.ApplyMatrix(Numeric.array(m.allAtoms.coords),M,transpose=False)
else :
vt = m.allAtoms.coords[:]
coords.extend(vt)
self.imd_send_fcoords(len(coords),coords)
def mindyGet(self):
from ARViewer import util
import numpy.oldnumeric as Numeric
imdheader = self.imd_recv_header(self.sock)
vmd_length = imdheader.length
imdtype = imdheader.imdtype
if imdtype == IMD_FCOORDS:
#print "recv fcoords ",vmd_length
test=self.imd_recv_fcoords(vmd_length,self.imd_coords)
#print self.imd_coords[0]
b=0
n1 = 0
for i,m in enumerate(self.mol) :
n1 += len(m.allAtoms.coords)
try :
#should apply the inverse matrix? to get back to the origin
#before going on the marker..
#but problem of scaleFactor
if hasattr(self.vf,'art'):
M = matrix(m.pat.mat_transfo.reshape(4,4))
vt=util.ApplyMatrix(Numeric.array(self.imd_coords[b:n1]),
Numeric.array(M.I),transpose=False)
#print "update coords but back in CS"
#print vt[0]
if True in numpy.isnan(vt[0]):
vt = map(lambda x: x[0], m.allAtoms._coords)
m.allAtoms.updateCoords(vt, self.slot[i])
#print m.allAtoms.coords[0]
else :
m.allAtoms.updateCoords(self.imd_coords[b:n1], self.slot[i])
except:
print "coord update failed"
b=n1
from Pmv.moleculeViewer import EditAtomsEvent
for i,m in enumerate(self.mol) :
event = EditAtomsEvent('coords', m.allAtoms)
try :
self.vf.dispatchEvent(event)
except:
print "event failed"
def updateMindy(self):
from ARViewer import util
import numpy.oldnumeric as Numeric
imdheader = self.imd_recv_header(self.sock)
vmd_length = imdheader.length
imdtype = imdheader.imdtype
if imdtype == IMD_FCOORDS:
print "recv fcoords ",vmd_length
test=self.imd_recv_fcoords(vmd_length,self.imd_coords)
print self.imd_coords[0]
b=0
n1 = 0
for i,m in enumerate(self.mol) :
n1 += len(m.allAtoms.coords)
try :
#should apply the inverse matrix? to get back to the origin before going on the marker..
if hasattr(self.vf,'art'):
M = matrix(m.pat.mat_transfo.reshape(4,4))
vt=util.ApplyMatrix(Numeric.array(self.imd_coords[b:n1]),numpy.array(M.I))
print "update coords but back in CS"
print vt[0]
m.allAtoms.updateCoords(vt, self.slot[i])
print m.allAtoms.coords[0]
else :
m.allAtoms.updateCoords(self.imd_coords[b:n1], self.slot[i])
except:
print "coord update failed"
b=n1
#print m.allAtoms._coords[0]
#print "ipdate coords events"
from Pmv.moleculeViewer import EditAtomsEvent
for i,m in enumerate(self.mol) :
event = EditAtomsEvent('coords', m.allAtoms)
try :
self.vf.dispatchEvent(event)
except:
print "event failed"
#here we should update from AR....which is apply the marker transformation
#one marker per mol...should have some mol.mat_transfo attributes
#get the maker position transfo
coords=[]
for m in self.mol:
if hasattr(self.vf,'art'):
M = m.pat.mat_transfo
vt = []
vt=util.ApplyMatrix(Numeric.array(m.allAtoms.coords),M)
else :
vt = m.allAtoms.coords[:]
coords.extend(vt)
self.imd_send_fcoords(self.N,coords)
def treatProtocol(self,i):
#import Pmv.hostappInterface.pdb_blender as epmv
if not self.pause:
imdheader = self.imd_recv_header(self.sock)
vmd_length = imdheader.length
imdtype = imdheader.imdtype
#print "TYPE ",imdtype
if imdtype == IMD_ENERGIES:
#print "energie"
ene=IMDEnergies()
test=self.imd_recv_energies(ene)
#print ene.tstep,ene.Etot,ene.Epot,ene.Evdw,ene.Epot,ene.Eelec,ene.Eangle
if imdtype == IMD_MDCOMM:
#receive Force and Atom listes
#print "mdcom",vmd_length
vmd_atoms=numpy.zeros(vmd_length,'i')
vmd_forces=numpy.zeros(vmd_length*3,'f')
test=self.imd_recv_mdcomm(vmd_length,vmd_atoms,vmd_forces)
if imdtype == IMD_FCOORDS: #get the coord
#vmd_coords=numpy.zeros((vmd_length,3),'f')
self.lock.acquire()
test=self.imd_recv_fcoords(vmd_length,self.imd_coords)
#self.imd_coords[:]=vmd_coords[:]#.copy()
self.lock.release()
#self.vf.updateIMD
#epmv.updateCloudObject("1hvr_cloud",self.imd_coords)
#epmv.insertKeys(self.mol.geomContainer.geoms['cpk'],1)
if self.vf.handler.isinited:
if (i % self.ffreq) == 0 :
if self.vf.handler.forceType == "move" :
self.imd_send_fcoords(self.vf.handler.N_forces,self.vf.handler.forces_list)
print "ok",self.vf.handler.N_forces
else :
self.imd_send_mdcomm(self.vf.handler.N_forces, self.vf.handler.atoms_list, self.vf.handler.forces_list)
if self.mindy:
coords=[]
for m in self.mol:
coords.extend(m.allAtoms.coords)
self.imd_send_fcoords(self.N,coords)
def listenToImdServer(self,func):
i=0
while (1):
self.treatProtocol(i)
i = i + 1
commandList = [
{'name':'imd', 'cmd':IMD(),
'gui': None},
]
def initModule(viewer):
for dict in commandList:
# print 'dict',dict
viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])
```
#### File: MGLToolsPckgs/Vision/API.py
```python
import warnings
class VisionInterface:
"""This class provides a mechanism to interface between Vision and
another application (for example, it allows Pmv to add nodes to Vision)
Objects created in the application (e.g. in Pmv) are stored in the
self.objects list. Here we store the object, a name to be used for the
Vision node, and optional keywords if the Vision node needs them. For
example the kw 'constrkw' is used in Vision for saving/restoring properly.
In addition, there is a lookup table to describe the connection between
an object in the application (such as a molecule) and the corresponding
Vision node.
Adding an object to this interface using the add() method will
automatically add the node to Vision -- if Vision is running at this
moment. If Vision is not running, we still add the object to our list and
in the command that starts Vision inside the application (e.g. in Pmv this
would be 'visionCommands') a mechanism has to be implemented to loop over
the objects in our list and add them to Vision -- that's 2 lines of code:
see visionCommands!"""
def __init__(self, ed=None, lib=None):
self.ed = ed # handle to Vision
self.lib = lib # handle to the Vision library
self.objects = [] # list of objects to be added as nodes to Vision
# this contains tuples of (object, name, kw)
self.lookup = {} # lookup table that defines what node class,
# which category. Will be used to assign a
# Vision node to the object
# key: the object
# value: a tuple with the node class and
# category name
def add(self, obj, name, kw=None):
"""Add an object to this API. This will automatically add a node
to a Vision library if Vision is running.
- obj: the appliaction object (such as a molecule)
- name: name to be used for the Vision node
- kw: optional Vision node constructor keywords.
"""
if kw is None:
kw = {}
# find out which Vision node corresponds to this object, based on our
# lookup table
if obj.__class__ in self.lookup.keys():
# add to our list of objects
self.objects.append( (obj, name, kw) )
# add node to Visual Programming Environment library if this exists
if self.ed is not None and self.lib is not None:
self.addNodeToLibrary(obj, name, kw)
return
else: # the class was not found, try to see if a base class is there
for k in self.lookup.keys():
if isinstance(obj, k):
# add to our list of objects
self.objects.append( (obj, name, kw) )
# add node to Visual Programming Environment library if this exists
if self.ed is not None and self.lib is not None:
self.addNodeToLibrary(obj, name, kw)
return
import traceback
traceback.print_exc()
warnings.warn(
"ERROR: Object not found in lookup. Cannot create node")
def remove(self, obj):
"""Delete an object from the list of objects. This also deletes the
node proxy in the category and all node instances in all networks."""
# is the object in our list of objects?
found = None
for i in range(len(self.objects)):
if self.objects[i][0] == obj:
found = self.objects[i][0]
# delete from our list of objects
del self.objects[i]
break
if found is None:
return
node = self.lookup[found.__class__]['node']
cat = self.lookup[found.__class__]['category']
# if Vision was not started yet, return here
if self.ed is None:
return
## STEP 1) Delete node proxy in category
# note: here, the 'node' is not a node instance, but a class,
# therefore we can just pass the object
self.lib.deleteNodeFromCategoryFrame(cat, node, found.name)
## STEP 2) Delete all instances of this node in all networks
for net in self.ed.networks.values():
for n in net.nodes:
if n.__class__ == node:
net.deleteNodes([n])
def setEditor(self, ed):
"""helper method to get a handle to Vision"""
from Vision.VPE import VisualProgramingEnvironment
assert isinstance(ed, VisualProgramingEnvironment)
self.ed = ed
def setLibrary(self, lib):
"""helper method to get a handle to a Vision library"""
from Vision.VPE import NodeLibrary
assert isinstance(lib, NodeLibrary)
self.lib = lib
def addToLookup(self, obj, node, cat):
"""Add a class instance of a Vision node to this list"""
self.lookup[obj] = {'node':node, 'category':cat}
def addNodeToLibrary(self, obj, name, kw=None):
"""add node to Visual Programming Environment library"""
if kw is None:
kw = {}
if obj.__class__ in self.lookup.keys():
o = self.lookup[obj.__class__]
else:
for k in self.lookup.keys():
if isinstance(obj, k):
o = self.lookup[k]
break
node = o['node']
cat = o['category']
self.lib.addNode(node, name, cat, (), kw)
# if a node is added to an empty category, we resize all
if len(self.lib.libraryDescr[cat]['nodes']) == 1:
self.lib.resizeCategories()
```
#### File: MGLToolsPckgs/Vision/flex.py
```python
from NetworkEditor.items import NetworkNode
import numpy.oldnumeric as Numeric
class DistanceMatrix(NetworkNode):
def __init__(self, name='DM', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, in1):
import numpy.oldnumeric as Numeric
l = len(in1)
dm = Numeric.zeros( (l,l), 'd')
in1 = Numeric.array(in1).astype('d')
for i in range(l):
dist = in1[i] - in1
dist = dist*dist
dm[i] = Numeric.sqrt(Numeric.sum(dist, 1))
self.outputData(out1=dm)\n"""
if code: self.setFunction(code)
self.inputPortsDescr.append({'name': 'in1', 'datatype': 'None'})
self.outputPortsDescr.append({'name': 'out1', 'datatype': 'None'})
class DDM(NetworkNode):
def __init__(self, name='DDM', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, in1, in2):
import numpy.oldnumeric as Numeric
result = in1-in2
self.outputData(out1=result)\n"""
if code: self.setFunction(code)
self.inputPortsDescr.append({'name': 'in1', 'datatype': 'None'})
self.inputPortsDescr.append({'name':'in2', 'datatype': 'None'})
self.outputPortsDescr.append({'name':'out1', 'datatype': 'None'})
class Cluster(NetworkNode):
def __init__(self, name='cluster', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, in1, cut_off):
import math
mat = in1
clusters = [[0],] # 1 cluster with first point
l = mat.shape[0]
for i1 in range(1, l):
for c in clusters: # loop over excisting clusters
inclus = 1
for p in c: # check distance to all points in cluster
if math.fabs(mat[i1,p]) > cut_off:
inclus=0
break
if inclus: # all dist. below cut_off --> add to cluster
c.append(i1)
inclus = 1
break
if not inclus: # after trying all clusters we failed -> new cluster
clusters.append([i1])
# make it 1 based so indices match PMV residue indices
#clusters1 = []
#for e in clusters:
# clusters1.append( list ( Numeric.array(e) + 1 ) )
self.outputData(out1=clusters)\n"""
if code: self.setFunction(code)
self.widgetDescr['cut_off'] = {
'class': 'NEDial', 'master': 'node', 'size': 50,
'oneTurn': 4.0, 'type': float, 'showLabel': 1, 'precision': 2,
'labelCfg':{'text':'cut_off'}, 'labelSide':'left'}
self.inputPortsDescr.append({'name':'in1', 'datatype':'None'})
self.inputPortsDescr.append({'datatype':'None', 'name':'cut_off'})
self.outputPortsDescr.append({'name':'out1', 'datatype': 'None'})
class ColorCluster(NetworkNode):
def __init__(self, name='color cluster', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, in1):
from DejaVu.colorTool import RGBRamp, Map
cols = Map(range(len(in1)), RGBRamp() )
l = len(reduce(lambda x,y: x+y, in1))
c = Numeric.zeros( (l,3), 'f' )
i=0
for e in in1:
col = cols[i]
for p in e:
c[p] = col
i = i + 1
self.outputData(out1=c)\n"""
if code: self.setFunction(code)
self.inputPortsDescr.append({'name':'in1', 'datatype': 'None'})
self.outputPortsDescr.append({'name':'out1', 'datatype': 'None'})
class DefaultIndices(NetworkNode):
def __init__(self, name='default indices', **kw):
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, in1):
self.outputData(out1=[range(in1[0])])\n"""
if code: self.setFunction(code)
self.inputPortsDescr.append({'name':'length', 'datatype':'int'})
self.outputPortsDescr.append({'name':'out1', 'datatype':'None'})
from Vision.VPE import NodeLibrary
flexlib = NodeLibrary('Flex', '#AA66AA')
flexlib.addNode(DistanceMatrix, 'DM', 'Input')
flexlib.addNode(DDM, 'DDM', 'Input')
flexlib.addNode(Cluster, 'Cluster', 'Input')
flexlib.addNode(ColorCluster, 'Color Cluster', 'Input')
flexlib.addNode(DefaultIndices, 'indices', 'Input')
```
#### File: MGLToolsPckgs/Vision/Forms.py
```python
import Tkinter, Pmw
import sys, re, os
import string
import webbrowser
from string import join
from Tkinter import *
from types import StringType
import tkFileDialog
from NetworkEditor.customizedWidgets import kbScrolledCanvas
from mglutil.util.callback import CallBackFunction
from mglutil.util.packageFilePath import findAllPackages, findModulesInPackage
from mglutil.gui.InputForm.Tk.gui import InputFormDescr
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser, \
kbScrolledListBox
from mglutil.util.misc import ensureFontCase
VarDict={}
class Dialog:
def __init__(self):
self.panel = None
self.bg = 'royalblue'
self.fg = 'white'
self.buildPanel()
# bind OK button callback
self.panel.protocol("WM_DELETE_WINDOW", self.Ok)
# disable typing stuff in the window
self.textFrame.configure(state='disabled')
## # disable resizing
## self.panel.resizable(height='false', width='false')
def buildPanel(self):
# prevent re-creation
if self.panel is not None:
self.panel.show()
return
root = self.panel = Tkinter.Toplevel()
self.frame = Tkinter.Frame(root, borderwidth=2,
relief='sunken', padx=5, pady=5)
self.frame.pack(side='top', expand=1, fill='both')
txtFrame = Tkinter.Frame(self.frame)
self.textFrame = Tkinter.Text(txtFrame, background=self.bg,
exportselection=1, padx=10, pady=10,)
self.textFrame.tag_configure('big', font=(ensureFontCase('Courier'), 24, 'bold'),
foreground=self.fg)
self.textFrame.tag_configure('medium', font=(ensureFontCase('helvetica'), 14, 'bold'),
foreground=self.fg)
self.textFrame.tag_configure('normal12',
font=(ensureFontCase('helvetica'), 12, 'bold'),
foreground=self.fg)
self.textFrame.tag_configure('normal10',
font=(ensureFontCase('helvetica'), 10, 'bold'),
foreground=self.fg)
self.textFrame.tag_configure('normal8',
font=(ensureFontCase('helvetica'), 8, 'bold'),
foreground=self.fg)
self.textFrame.tag_configure('email', font=(ensureFontCase('times'), 10, 'bold'),
foreground='lightblue')
self.textFrame.tag_configure('http', font=(ensureFontCase('times'), 12, 'bold'),
foreground='lightblue')
self.textFrame.tag_configure('normal10b',
font=(ensureFontCase('helvetica'), 10, 'bold'),
foreground='lightblue')
self.textFrame.pack(side='left', expand=1, fill='both')
# provide a scrollbar
self.scroll = Tkinter.Scrollbar(txtFrame, command=self.textFrame.yview)
self.textFrame.configure(yscrollcommand = self.scroll.set)
self.scroll.pack(side='right', fill='y')
txtFrame.pack(expand=1, fill='both')
# proved an OK button
buttonFrame = Tkinter.Frame(self.frame)
buttonFrame.pack(side='bottom', fill='x')
self.buttonOk = Tkinter.Button(buttonFrame, text=' Ok ',
command=self.Ok)
self.buttonOk.pack(padx=6, pady=6)
def Ok(self, event=None):
self.hide()
def show(self, event=None):
self.panel.deiconify()
def hide(self, event=None):
self.panel.withdraw()
class AboutDialog(Dialog):
def __init__(self):
Dialog.__init__(self)
def buildPanel(self):
Dialog.buildPanel(self) # call base class method
# remove scrollbar
self.scroll.forget()
# add own stuff
self.panel.title('About Vision')
self.textFrame.configure()
self.textFrame.insert('end', 'Vision\n', 'big')
self.textFrame.insert('end',
'A Visual Programming Environment for Python.\n\n',
'medium')
self.textFrame.insert('end',
'<NAME>','normal12')
self.textFrame.insert('end', '\t\ts<EMAIL>\n', 'email')
self.textFrame.insert('end', '<NAME>', 'normal12')
self.textFrame.insert('end', '\t\<EMAIL>\n','email')
self.textFrame.insert('end', '<NAME>', 'normal12')
self.textFrame.insert('end', '\[email protected]\n\n','email')
self.textFrame.insert('end', 'Vision home page:\t', 'normal12')
self.textFrame.insert('end',
'http://mgltools.scripps.edu/\n\n',
'http')
self.textFrame.insert('end', 'The Scripps Research Institute\n'+\
'Molecular Graphics Lab\n'+\
'10550 N Torrey Pines Rd\n'+\
'La Jolla CA 92037 USA\n\n', 'normal10')
self.textFrame.insert('end',
'Python version: %s\t'%sys.version.split()[0],
'normal8')
# handle weird tk version num in windoze python >= 1.6 (?!?)
# Credits for this code go to the people who brought us idlelib!
tkVer = `Tkinter.TkVersion`.split('.')
tkVer[len(tkVer)-1] = str('%.3g'%(
float('.'+tkVer[len(tkVer)-1])))[2:]
if tkVer[len(tkVer)-1] == '':
tkVer[len(tkVer)-1] = '0'
tkVer = string.join(tkVer,'.')
self.textFrame.insert('end', 'Tk version: %s\n'%tkVer,
'normal8')
#self.panel.geometry("+%d+%d" %(self.panel.winfo_rootx()+30,
# self.panel.winfo_rooty()+30))
class AcknowlDialog(Dialog):
def __init__(self):
Dialog.__init__(self)
def buildPanel(self):
Dialog.buildPanel(self) # call base class method
# add own stuff
self.panel.title('Acknowledgements')
self.textFrame.insert('end', 'Vision Acknowledgements\n', 'big')
self.textFrame.insert('end',
'\nThis work is supported by:\n\n', 'medium')
self.textFrame.insert('end',
'Swiss National Science Foundation\n'+\
'Grant No. 823A-61225\n', 'normal12')
self.textFrame.insert('end', 'http://www.snf.ch\n\n', 'http')
self.textFrame.insert('end',
'National Biomedical Computation Resource\n'+\
'Grant No. NBCR/NIH RR08605\n', 'normal12')
self.textFrame.insert('end', 'http://nbcr.sdsc.edu\n\n', 'http')
self.textFrame.insert('end',
'National Partnership for Advanced Computational Infrastructure\n'+\
'Grant No. NPACI/NSF CA-ACI-9619020\n', 'normal12')
self.textFrame.insert('end', 'http://www.npaci.edu\n\n', 'http')
self.textFrame.insert('end',
'The authors would like to thank all the people in the Olson lab\n'+\
'for their support and constructive criticism.\n', 'normal10')
self.textFrame.insert('end', 'http://www.scripps.edu/pub/olson-web\n',
'http')
class RefDialog(Dialog):
def __init__(self):
Dialog.__init__(self)
def buildPanel(self):
Dialog.buildPanel(self) # call base class method
# remove scrollbar
self.scroll.forget()
# add own stuff
self.panel.title('References')
self.textFrame.insert('end', 'Vision References\n\n', 'big')
self.textFrame.insert('end',
'ViPEr, a Visual Programming Environment for Python\n','normal12')
self.textFrame.insert('end',
'<NAME>., <NAME>., and <NAME>. (2002)\n','normal10b')
self.textFrame.insert('end',
'In proceedings of the 10th International Python Conference 2002,\n'+\
'Virginia USA.\n\n','normal10')
self.textFrame.insert('end',
'Integrating biomolecular analysis and visual programming:\n'+\
'flexibility and interactivity in the design of bioinformatics tools\n',
'normal12')
self.textFrame.insert('end',
'<NAME>., <NAME>., <NAME>., Olson, '+\
'A.J., and <NAME>. (2003)\n','normal10b')
self.textFrame.insert('end',
'In proceedings of HICSS-36, Hawaii International conference\n'+\
'on system sciences, 2003, Hawaii.\n\n','normal10')
class ChangeFonts:
def __init__(self, editor=None):
self.panel = None
self.editor = editor # instance of VPE
self.buildPanel()
# bind Cancel button callback on kill window
self.panel.protocol("WM_DELETE_WINDOW", self.Cancel_cb)
def buildPanel(self):
# prevent re-creation
if self.panel is not None:
self.panel.show()
return
root = self.panel = Tkinter.Toplevel()
frame = Tkinter.Frame(root, borderwidth=2,
relief='sunken')#, padx=5, pady=5)
frame.pack(side='top', expand=1, fill='both')
## Font Group ##
fontGroup = Pmw.Group(frame, tag_text='Font Chooser')
fontGroup.pack(fill='both', expand=1, padx=6, pady=6)
f1 = Tkinter.Frame(fontGroup.interior())
f1.pack(side='top', fill='both', expand=1)
f2 = Tkinter.Frame(fontGroup.interior())
f2.pack(side='bottom', fill='both', expand=1)
familyNames=list(root.tk.splitlist(root.tk.call('font','families')))
familyNames.sort()
self.fontChooser = Pmw.ComboBox(
f1,
label_text = 'Font Name',
labelpos = 'n',
scrolledlist_items = familyNames,
selectioncommand = None
)
self.fontChooser.pack(side='left', expand=1, fill='both',
padx=6, pady=6)
sizes = [6,7,8,10,12,14,18,24,48]
self.sizeChooser = Pmw.ComboBox(
f1,
label_text = 'Font Size',
labelpos = 'n',
scrolledlist_items = sizes,
selectioncommand = None,
entryfield_entry_width=4,
)
self.sizeChooser.pack(side='left', expand=1, fill='both',
padx=6, pady=6)
styles = ['normal', 'bold', 'italic', 'bold italic']
self.styleVarTk = Tkinter.StringVar()
for i in range(len(styles)):
b = Tkinter.Radiobutton(
f2,
variable = self.styleVarTk,
text=styles[i], value=styles[i])
b.pack(side='left', expand=1, fill='both')
## End Font Group ## ##########################################
## GUI Group ##
guiGroup = Pmw.Group(frame, tag_text='GUI Component to Apply Font')
guiGroup.pack(fill='both', expand=1, padx=6, pady=6)
group1 = ['All', 'Menus', 'LibTabs', 'Categories']
group2 = ['LibNodes', 'NetTabs', 'Nodes', 'Root']
self.groupVarTk = Tkinter.StringVar()
frame1 = Tkinter.Frame(guiGroup.interior())
frame2 = Tkinter.Frame(guiGroup.interior())
frame1.pack(side='top', fill='both', expand=1)
frame2.pack(side='bottom', fill='both', expand=1)
for i in range(len(group1)):
b = Tkinter.Radiobutton(
frame1,
variable = self.groupVarTk,
text=group1[i], value=group1[i])
b.grid(row=0, column=i, pady=6)
for i in range(len(group2)):
b = Tkinter.Radiobutton(
frame2,
variable = self.groupVarTk,
text=group2[i], value=group2[i])
b.grid(row=0, column=i, pady=6)
buttonFrame = Tkinter.Frame(root, borderwidth=2,
relief='sunken', padx=5, pady=5)
buttonFrame.pack(side='top', expand=1, fill='both')
self.buttonOk = Tkinter.Button(buttonFrame, text=' Ok ',
command=self.Ok_cb)
self.buttonApply = Tkinter.Button(buttonFrame, text=' Apply ',
command=self.Apply_cb)
self.buttonCancel = Tkinter.Button(buttonFrame, text=' Cancel ',
command=self.Cancel_cb)
self.buttonOk.grid(row=0, column=0, padx=6, pady=6)
self.buttonApply.grid(row=0, column=1, padx=6, pady=6)
self.buttonCancel.grid(row=0, column=2, padx=6, pady=6)
# set default values
try:
self.fontChooser.selectitem(ensureFontCase('helvetica'))
self.sizeChooser.selectitem(2) # choose '8'
self.styleVarTk.set('normal')
self.groupVarTk.set('Nodes')
except:
pass
def get(self, event=None):
gui = self.groupVarTk.get()
ft = self.fontChooser.get()
sz = self.sizeChooser.get()
sty = self.styleVarTk.get()
font = (ft, sz, sty)
return (gui, font)
def Ok_cb(self, event=None):
self.Apply_cb()
self.Cancel_cb()
def Apply_cb(self, event=None):
if self.editor is not None:
cfg = self.get()
self.editor.setFont(cfg[0], cfg[1])
from Vision.UserLibBuild import saveFonts4visionFile
saveFonts4visionFile(self.editor.font)
def Cancel_cb(self, event=None):
self.hide()
def show(self, event=None):
self.panel.deiconify()
def hide(self, event=None):
self.panel.withdraw()
class SearchNodesDialog:
"""Search Vision nodes: the string matches either the node name or the
node's document string. Found nodes are displayed in the scrolled canvas of
this widget, and can be drag-and-drop-ed to the network canvas.
A new search clears the previously found nodes"""
def __init__(self, editor=None):
self.panel = None
self.editor = editor # instance of VPE
self.entryVarTk = Tkinter.StringVar() # Entry var
self.cbVarTk = Tkinter.IntVar() # checkbutton var
self.choicesVarTk = Tkinter.StringVar()# radiobutton choices var
self.choices = ['Search current lib only', 'Search all loaded libs',
'Search all packages\non system path (slower)']
self.searchNodes = [] # list of found nodes
self.libNodes = [] # list of nodes displayed in our libCanvas
self.posyForLibNode = 15 # posy for nodes in lib canvas
self.maxxForLibNode = 0 # maxx for nodes in lib canvas
# build GUI
self.buildPanel()
# bind Cancel button callback on kill window
self.panel.protocol("WM_DELETE_WINDOW", self.Cancel_cb)
def buildPanel(self):
# prevent re-creation
if self.panel is not None:
self.panel.show()
return
root = self.panel = Tkinter.Toplevel()
# add menu bar
self.menuBar = Tkinter.Menu(root)
self.optionsMenu = Tkinter.Menu(self.menuBar, tearoff=0)
self.optionsMenu.add_command(label="Hide Search Options",
command=self.showHideOptions_cb)
self.menuBar.add_cascade(label="Options", menu=self.optionsMenu)
root.config(menu=self.menuBar)
frame = Tkinter.Frame(root, borderwidth=2, relief='sunken')
frame.pack(side='top', expand=1, fill='both')
# build infrastructure for search panes with scrolled canvas
sFrame = Tkinter.Frame(frame)
sFrame.pack(expand=1, fill='both')
# add panes
self.searchPane = Pmw.PanedWidget(sFrame, orient='horizontal',
hull_relief='sunken',
hull_width=120, hull_height=120,
)
self.searchPane.pack(expand=1, fill="both")
searchPane = self.searchPane.add("SearchNodes", min=60)
self.searchPane.configurepane("SearchNodes", min=10)
usedPane = self.searchPane.add("UsedNodes", min=10)
# this is the canvas we use to display found nodes
self.searchCanvas = kbScrolledCanvas(
searchPane,
borderframe=1,
#usehullsize=1, hull_width=60, hull_height=80,
#vscrollmode='static',#hscrollmode='static',
vertscrollbar_width=8,
horizscrollbar_width=8,
labelpos='n', label_text="Found Nodes",
)
self.searchCanvas.pack(side='left', expand=1, fill='both')
self.editor.idToNodes[self.searchCanvas] = {}
# this is the canvas we use to display nodes we have drag-and-dropped
# to the network
self.libCanvas = kbScrolledCanvas(
usedPane,
borderframe=1,
#usehullsize=1, hull_width=60, hull_height=80,
#vscrollmode='static',#hscrollmode='static',
vertscrollbar_width=8,
horizscrollbar_width=8,
labelpos='n', label_text="Used Nodes",
)
self.libCanvas.pack(side='right', expand=1, fill='both')
self.editor.idToNodes[self.libCanvas] = {}
lowerFrame = Tkinter.Frame(frame)
lowerFrame.pack() # no expand
# add options buttons
self.optionsGroup = Pmw.Group(lowerFrame, tag_text="Search Options")
self.optionsGroup.grid(row=0,column=0, sticky='we',padx=6, pady=6)
cb = Tkinter.Checkbutton(self.optionsGroup.interior(),
text="Case sensitive", variable=self.cbVarTk)
cb.grid(row=0, column=0, columnspan=2, sticky='we')
for i in range(len(self.choices)):
b = Tkinter.Radiobutton(
self.optionsGroup.interior(),
variable = self.choicesVarTk, value=self.choices[i])
l = Tkinter.Label(self.optionsGroup.interior(),
text=self.choices[i])
b.grid(row=i+1, column=0, sticky='we')
l.grid(row=i+1, column=1, sticky='w')
self.choicesVarTk.set(self.choices[1])
# add Entry
eFrame = Tkinter.Frame(lowerFrame)
eFrame.grid(row=1, column=0, sticky='we')
eLabel = Tkinter.Label(eFrame, text='Search string:')
eLabel.pack(side='left', expand=1, fill='x')
entry = Tkinter.Entry(eFrame, textvariable=self.entryVarTk)
entry.bind('<Return>', self.search)
entry.pack(side='right', expand=1, fill='x')
# add buttons
bFrame = Tkinter.Frame(lowerFrame)
bFrame.grid(row=2, column=0, sticky='we')
button1 = Tkinter.Button(bFrame, text="Search", relief="raised",
command=self.Apply_cb)
button2 = Tkinter.Button(bFrame, text="Dismiss", relief="raised",
command=self.Cancel_cb)
button1.pack(side='left', expand=1, fill='x')
button2.pack(side='right', expand=1, fill='x')
# Pmw Balloon
self.balloons = Pmw.Balloon(master=None, yoffset=10)
# Drag-and-Drop callback for searchCanvas
cb = CallBackFunction(self.editor.startDNDnode, self.searchCanvas)
self.searchCanvas.component('canvas').bind('<Button-1>', cb )
# Drag-and-Drop callback for libCanvas
cb = CallBackFunction(self.editor.startDNDnode, self.libCanvas)
self.libCanvas.component('canvas').bind('<Button-1>', cb )
def Apply_cb(self, event=None):
if self.editor is not None:
self.search()
def Cancel_cb(self, event=None):
self.hide()
def show(self, event=None):
self.panel.deiconify()
def hide(self, event=None):
self.panel.withdraw()
def search(self, event=None):
searchStr = self.entryVarTk.get()
if searchStr is None or len(searchStr) == 0:
return
canvas = self.searchCanvas.component('canvas')
# clear previous matches
if len(self.searchNodes):
for node in self.searchNodes:
self.deleteNodeFromPanel(node)
self.searchNodes = []
self.editor.idToNodes[self.searchCanvas] = {}
posy = 15
maxx = 0
nodes = {}
caseSensitive = self.cbVarTk.get()
if not caseSensitive:
searchStr = string.lower(searchStr)
pat = re.compile(searchStr)
# loop over libraries
choice = self.choicesVarTk.get()
if choice == self.choices[0]: # current lib
lib = self.editor.ModulePages.getcurselection()
libraries = [ (lib, self.editor.libraries[lib]) ]
elif choice == self.choices[1]: # all loaded libs
libraries = self.editor.libraries.items()
else: # all packages on disk
libraries = self.searchDisk()
for libInd in range(len(libraries)):
libName, lib = libraries[libInd]
categories = lib.libraryDescr.values()
# loop over categories
for catInd in range(len(lib.libraryDescr)):
cat = categories[catInd]
for nodeInd in range(len(cat['nodes'])):
node = cat['nodes'][nodeInd]
# match node name
name = node.name
if not caseSensitive:
name = string.lower(node.name)
res = pat.search(name)
if res:
nodes, maxx, posy = self.addNodeToSearchPanel(
node, nodes, maxx, posy)
continue
# match node document string
doc = node.nodeClass.__doc__
if doc is None or doc == '':
continue
if not caseSensitive:
doc = string.lower(doc)
res = pat.search(doc)
if res:
nodes, maxx, posy = self.addNodeToSearchPanel(
node, nodes, maxx, posy)
# update scrolled canvas
canvas.configure(width=60, height=150,
scrollregion=tuple((0,0,maxx,posy)))
self.editor.idToNodes[self.searchCanvas] = nodes
def addNodeToSearchPanel(self, node, nodes, maxx, posy):
from NetworkEditor.items import NetworkNode
sc_canvas = self.searchCanvas
font = self.editor.font['LibNodes']
canvas = sc_canvas.component('canvas')
n1 = NetworkNode(name=node.name)
n1.iconMaster = sc_canvas
n1.buildSmallIcon(sc_canvas, 10, posy, font)
color = node.kw['library'].color
canvas.itemconfigure(n1.id, fill=color)
self.balloons.tagbind(sc_canvas, n1.iconTag,
node.nodeClass.__doc__)
bb = sc_canvas.bbox(n1.id)
w = bb[2]-bb[0]
h = bb[3]-bb[1]
maxx = max(maxx, w)
posy = posy + h + 8
nodes[n1.id] = (n1, node)
self.searchNodes.append(n1)
return nodes, maxx, posy
def addNodeToLibPanel(self, node):
if node in self.libNodes:
return
from NetworkEditor.items import NetworkNode
sc_canvas = self.libCanvas
font = self.editor.font['LibNodes']
canvas = sc_canvas.component('canvas')
n1 = NetworkNode(name=node.name)
n1.iconMaster = sc_canvas
posy = self.posyForLibNode
n1.buildSmallIcon(sc_canvas, 10, posy, font)
color = node.kw['library'].color
canvas.itemconfigure(n1.id, fill=color)
self.balloons.tagbind(sc_canvas, n1.iconTag,
node.nodeClass.__doc__)
bb = sc_canvas.bbox(n1.id)
w = bb[2]-bb[0]
h = bb[3]-bb[1]
self.maxxForLibNode = max(self.maxxForLibNode, w)
posy = posy + h + 8
self.posyForLibNode = posy
self.libNodes.append(node)
nodes = self.editor.idToNodes[self.libCanvas]
nodes[n1.id] = (n1, node)
self.editor.idToNodes[self.libCanvas] = nodes
# update scrolled canvas
maxx = self.maxxForLibNode
canvas.configure(width=60, height=150,
scrollregion=tuple((0,0,maxx,posy)))
def deleteNodeFromPanel(self, node):
canvas = self.searchCanvas.component('canvas')
# unbind proxy node balloon
self.balloons.tagunbind(canvas, node.iconTag)
# delete node icon
canvas.delete(node.textId)
canvas.delete(node.innerBox)
canvas.delete(node.outerBox)
canvas.delete(node.iconTag)
def showHideOptions_cb(self, event=None):
mode = 'show'
try:
index = self.optionsMenu.index("Hide Search Options")
mode = 'hide'
except:
pass
if mode == 'hide':
self.optionsGroup.grid_forget()
self.optionsMenu.entryconfig("Hide Search Options",
label="Show Search Options")
else:
self.optionsGroup.grid(row=0, padx=6, pady=6)
self.optionsMenu.entryconfig("Show Search Options",
label="Hide Search Options")
def searchDisk(self):
libraries = []
packages = findAllPackages()
for packName, packNameWithPath in packages.items():
modNames = self.getModules(packName, packNameWithPath)
if len(modNames):
for modName in modNames:
moduleName = packName+'.'+modName
try:
mod = __import__(
moduleName, globals(), locals(),
modName.split('.')[-1])
libs = self.getLibraries(mod)
for name,lib in libs.items():
lib.modName = moduleName
libraries.append( (name,lib) )
except:
print "Could not import module %s from %s!"%(
modName, os.getcwd() )
return libraries
def getModules(self, packName, packNameWithPath):
modules = findModulesInPackage(packNameWithPath, 'NodeLibrary')
modNames = []
for key, value in modules.items():
pathPack = key.split(os.path.sep)
if pathPack[-1] == packName:
newModName = map(lambda x: x[:-3], value)
modNames = modNames + newModName
else:
pIndex = pathPack.index(packName)
prefix = string.join(pathPack[pIndex+1:], '.')
newModName = map(lambda x: "%s.%s"%(prefix, x[:-3]), value)
modNames = modNames + newModName
modNames.sort()
return modNames
def getLibraries(self, mod):
from Vision.VPE import NodeLibrary
libs = {}
for name in dir(mod):
obj = getattr(mod, name)
if isinstance(obj, NodeLibrary):
obj.varName = name
libs[obj.name] = obj
return libs
class HelpDialog:
def __init__(self, title="Help Dialog", message="", bg=None,
fg=None, font=(ensureFontCase('helvetica'), 8, 'bold'),):
self.panel = None
self.title = title # Title of this Dialog window
self.message = message # Help message
self.bg = bg # Frame background
self.fg = fg # text color
self.font = font # text font
self.buildPanel()
self.panel.title(self.title)
# bind OK button callback
self.panel.protocol("WM_DELETE_WINDOW", self.Ok)
# disable typing stuff in the window
self.textFrame.configure(state='disabled')
def buildPanel(self):
# prevent re-creation
if self.panel is not None:
self.panel.show()
return
root = self.panel = Tkinter.Toplevel()
self.frame = Tkinter.Frame(
root, borderwidth=2, relief='sunken', padx=5, pady=5)
self.frame.pack(side='top', expand=1, fill='both')
txtFrame = Tkinter.Frame(self.frame)
self.textFrame = Tkinter.Text(
txtFrame, exportselection=1, padx=10, pady=10,)
if self.bg is not None:
self.textFrame.configure(bg=self.bg)
self.textFrame.tag_configure('standard', font=self.font)
if self.fg is not None:
self.textFrame.tag_configure('standard', foreground=self.fg)
self.textFrame.pack(side='left', expand=1, fill='both')
# now add the message
self.textFrame.insert('end', self.message, 'standard')
# provide a scrollbar
self.scroll = Tkinter.Scrollbar(txtFrame, command=self.textFrame.yview)
self.textFrame.configure(yscrollcommand = self.scroll.set)
self.scroll.pack(side='right', fill='y')
txtFrame.pack(expand=1, fill='both')
# proved an OK button
buttonFrame = Tkinter.Frame(self.frame)
buttonFrame.pack(side='bottom', fill='x')
self.buttonOk = Tkinter.Button(buttonFrame, text=' Ok ',
command=self.Ok)
self.buttonOk.pack(padx=6, pady=6)
def Ok(self, event=None):
self.hide()
def show(self, event=None):
self.panel.deiconify()
def hide(self, event=None):
self.panel.withdraw()
class BugReport:
def __init__(self, title="Bug Report", message="", bg=None,
fg=None, font=(ensureFontCase('helvetica'), 8, 'bold'),):
self.panel = None
self.title = title # Title of this Dialog window
self.message = message # Help message
self.bg = bg # Frame background
self.fg = fg # text color
self.font = font # text font
self.buildPanel()
self.panel.title(self.title)
# bind OK button callback
self.panel.protocol("WM_DELETE_WINDOW", self.Ok)
def doit(self):
self.showpdbfile_cb()
self.show_upload_page()
def __call__(self):
apply(self.doitWrapper,(),{})
def buildPanel(self):
root = self.panel = Tkinter.Toplevel()
self.frame = Tkinter.Frame(root, background='white',borderwidth=2, relief='sunken', padx=5, pady=5)
self.frame.pack(side='top', expand=1, fill='both')
##### short desc################
self.shortdesctext = Pmw.ScrolledText(self.frame,
label_text='Summary(one line description)',
labelpos='nw',text_padx=20,
text_pady=2,)
self.shortdesctext.pack(side='left', expand=1, fill='both')
self.shortdesctext.grid(sticky='nw',row=0,column=0,columnspan=2)
#########desc text################
self.desctext = Pmw.ScrolledText(self.frame,
label_text='Description',
labelpos='nw',text_padx=20,
text_pady=2,)
self.desctext.pack(side='left', expand=1, fill='both')
self.desctext.grid(sticky='nw',row=1,column=0,columnspan=2)
#pdb file button
self.pdbvar = Tkinter.IntVar()
### pdbfile group####
self.pdbGroup = Pmw.Group(self.frame,tag_text="AttachFile")
self.pdbGroup.pack(side='left',fill='both', expand=1, padx=1, pady=1)
f1 = Tkinter.Frame(self.pdbGroup.interior())
f1.pack(side='top', fill='both', expand=1)
self.pdbGroup.grid(row=3,column=0,columnspan=2,sticky="nesw")
self.pdbfileadd= kbScrolledListBox(f1,items=[],listbox_exportselection=0,listbox_height=1,listbox_width=85)
self.pdbfileadd.pack(expand=1, fill='both')
self.pdbfileadd.grid(sticky='nw',row=0)
self.deletefilebutton=Tkinter.Button(f1,text='Delete Selected',
command=self.delete_selected,state="disabled",width=40)
self.deletefilebutton.pack(side='left', expand=1,fill='both')
self.deletefilebutton.grid(sticky='nw',row=1,column=0,columnspan=1)
self.attachmorebutton=Tkinter.Button(f1,text='Attach File ..',
command=self.attach_more,width=40)
self.attachmorebutton.pack(side='left', expand=1,fill='both')
self.attachmorebutton.grid(sticky='ne',row=1,columnspan=2)
#email-entry
self.email_entrylab=Tkinter.Label(self.frame,text="Enter your email address(optional:to recieve information about submitted bug)")
self.email_entrylab.pack(side='top', fill='both', expand=1)
self.email_entrylab.grid(sticky='nw',row=4,column=0)
self.email_entryvar = Tkinter.StringVar()
self.email_entry=Tkinter.Entry(self.frame,textvariable=self.email_entryvar)
self.email_entry.pack(side='top', fill='both', expand=1)
self.email_entry.grid(sticky='nesw',row=5,column=0,columnspan=2)
###############upload,dismiss buttons################
self.uploadbutton=Tkinter.Button(self.frame,text='UpLoad Bug Report',
command=self.show_upload_page,width=40)
self.uploadbutton.pack(side='left', expand=1,fill='both')
self.uploadbutton.grid(sticky='nw',row=6,column=0,columnspan=1)
self.dismiss=Tkinter.Button(self.frame,text='DISMISS',
command=self.Ok,width=37)
self.dismiss.pack( expand=1,fill='both')
self.dismiss.grid(sticky='ne',row=6,columnspan=2)
pdb_group=self.pdbGroup
pdb_group.expand()
shortdesc_tx=self.shortdesctext
shortdesc_tx.configure(text_height=2)
desc_tx=self.desctext
desc_tx.configure(text_height=8)
def Ok(self, event=None):
self.hide()
def show(self, event=None):
#self.panel.deiconify()
self.buildPanel()
def hide(self, event=None):
#self.panel.withdraw()
self.panel.destroy()
def attach_more(self):
"""for attching files"""
pdb_addw=self.pdbfileadd
pdb_delw=self.deletefilebutton
Filename = tkFileDialog.askopenfilename(filetypes=[('all files','*')],title="ADDFile")
if Filename:
inputfilename = os.path.abspath(Filename)
files=pdb_addw.get()
files=list(files)
files.append(inputfilename)
pdb_addw.setlist(files)
pdb_addw.configure(listbox_height=len(files))
pdb_delw.configure(state="active")
else:
if len(pdb_addw.get())==0:
pdb_delw.configure(state="disabled")
pdb_addw.setlist(pdb_addw.get())
VarDict['attachfile'] = pdb_addw.get()
def delete_selected(self):
"""deletes selected files"""
pdb_addw=self.pdbfileadd
pdb_delw=self.deletefilebutton
files=pdb_addw.get()
lfiles=list(files)
selected_files=pdb_addw.getcurselection()
for s in list(selected_files):
if s in lfiles:
lfiles.remove(s)
pdb_addw.setlist(lfiles)
pdb_addw.configure(listbox_height=len(lfiles))
if len(pdb_addw.get())==0:
pdb_delw.configure(state="disabled")
VarDict['attachfile'] = pdb_addw.get()
def get_description(self):
desc_w =self.desctext
desc_text = self.desctext.get()
shortdesc_w = self.shortdesctext
shortdesc_text =shortdesc_w.get()
VarDict['desc_text'] = desc_text
VarDict['shortdesc_text'] = shortdesc_text
email_ent = self.email_entry.get()
VarDict['email_recipient'] = email_ent
#checking validity of email address
def validateEmail(self,email):
if len(email) > 7:
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
return 1
return 0
def show_upload_page(self):
self.get_description()
sumcont = VarDict['shortdesc_text']
fulldesc = VarDict['desc_text']
desccont = fulldesc
if len(sumcont)<=1 or len(desccont)<=1:
import tkMessageBox
ok = tkMessageBox.askokcancel("Input","Please enter summary and description")
return
from mglutil.TestUtil import BugReport
if VarDict.has_key('attachfile'):
upfile = VarDict['attachfile']
else:
upfile=[]
BR = BugReport.BugReportCommand("Vision")
if self.validateEmail(VarDict['email_recipient']):
idnum = BR.showuploadpage_cb(sumcont,desccont,upfile,email_ent=VarDict['email_recipient'])
else:
idnum = BR.showuploadpage_cb(sumcont,desccont,upfile,email_ent="")
self.Ok()
####################################
#Tk message Box
####################################
root = Tk()
t = Text(root)
t.pack()
def openHLink(event):
start, end = t.tag_prevrange("hlink",
t.index("@%s,%s" % (event.x, event.y)))
webbrowser.open_new('%s' %t.get(start, end))
#print "Going to %s..." % t.get(start, end)
t.tag_configure("hlink", foreground='blue', underline=1)
t.tag_bind("hlink", "<Control-Button-1>", openHLink)
t.insert(END, "BugReport has been Submiited Successfully\n")
t.insert(END, "BugId is %s" %idnum)
t.insert(END,"\nYou can visit Bug at\n")
t.insert(END,"http://mgldev.scripps.edu/bugs/show_bug.cgi?id=%i" %int(idnum),"hlink")
t.insert(END,"\nControl-click on the link to visit this page\n")
t.insert(END,"\n")
```
#### File: scipylib/signal/freqz.py
```python
from NetworkEditor.items import NetworkNode
class freqz(NetworkNode):
mRequiredTypes = {}
mRequiredSynonyms = [
]
def __init__(self, constrkw = {}, name='freqz', **kw):
kw['constrkw'] = constrkw
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, b, a, fs):
from scipy.signal import freqz
from scipy import absolute as abs
from scipy import log10, pi
w,h=freqz(b,a)
self.outputData(f=w/pi*(fs/2.0))
self.outputData(H=10*log10(abs(h)))
"""
self.configure(function=code)
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 'b', 'cast': True, 'datatype': 'None', 'balloon': 'filter numerator', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green'})
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 'a', 'cast': True, 'datatype': 'None', 'balloon': 'filter denominator', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green'})
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 'fs', 'cast': True, 'datatype': 'None', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green'})
self.outputPortsDescr.append(
{'name': 'H', 'datatype': 'None', 'balloon': 'abs(h) frequency response', 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green'})
self.outputPortsDescr.append(
{'name': 'f', 'datatype': 'array', 'balloon': 'abscissa', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'cyan'})
self.widgetDescr['a'] = {
'initialValue': 1.0, 'widgetGridCfgnode': {'rowspan': 1, 'labelSide': 'left', 'column': 1, 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 0}, 'height': 20, 'labelGridCfg': {'rowspan': 1, 'column': 0, 'sticky': 'w', 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 0}, 'width': 60, 'master': 'node', 'increment': 1.0, 'wheelPad': 1, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 0}, 'labelCfg': {'text': 'a'}, 'class': 'NEThumbWheel', 'oneTurn': 10.0}
def beforeAddingToNetwork(self, net):
try:
ed = net.getEditor()
except:
import traceback; traceback.print_exc()
print 'Warning! Could not import widgets'
```
#### File: scipylib/signal/timeRange.py
```python
from NetworkEditor.items import NetworkNode
class timeRange(NetworkNode):
mRequiredTypes = {}
mRequiredSynonyms = [
]
def __init__(self, constrkw = {}, name='timeRange', **kw):
kw['constrkw'] = constrkw
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, t0, t1, fs):
import scipy
data=scipy.arange(t0,t1,1.0/fs)
self.outputData(out0=data)
self.outputData(fs=fs)
"""
self.configure(function=code)
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 't0', 'cast': True, 'datatype': 'float', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green', 'originalDatatype': 'None'})
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 't1', 'cast': True, 'datatype': 'float', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green', 'originalDatatype': 'None'})
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 'fs', 'cast': True, 'datatype': 'float', 'required': True, 'height': 8, 'width': 12, 'shape': 'circle', 'color': 'green', 'originalDatatype': 'None'})
self.outputPortsDescr.append(
{'name': 'out0', 'datatype': 'None', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.outputPortsDescr.append(
{'name': 'fs', 'datatype': 'None', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.widgetDescr['t0'] = {
'initialValue': 0.0, 'widgetGridCfgnode': {'rowspan': 1, 'labelSide': 'left', 'column': 1, 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 0}, 'increment':0.1, 'height': 20, 'labelGridCfg': {'rowspan': 1, 'column': 0, 'sticky': 'w', 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 0}, 'width': 60, 'master': 'node', 'wheelPad': 1, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 0}, 'labelCfg': {'text': 't0'}, 'class': 'NEThumbWheel', 'oneTurn': 10.0}
self.widgetDescr['t1'] = {
'initialValue': 1.0, 'widgetGridCfgnode': {'rowspan': 1, 'labelSide': 'left', 'column': 1, 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 1}, 'increment':0.1, 'height': 20, 'labelGridCfg': {'rowspan': 1, 'column': 0, 'sticky': 'w', 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 1}, 'width': 60, 'master': 'node', 'wheelPad': 1, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 0}, 'labelCfg': {'text': 't1'}, 'class': 'NEThumbWheel', 'oneTurn': 10.0}
self.widgetDescr['fs'] = {
'initialValue': 100, 'widgetGridCfgnode': {'rowspan': 1, 'labelSide': 'left', 'column': 1, 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 2},'increment':5, 'height': 20, 'labelGridCfg': {'rowspan': 1, 'column': 0, 'sticky': 'w', 'ipady': 0, 'ipadx': 0, 'columnspan': 1, 'pady': 0, 'padx': 0, 'row': 2}, 'width': 60, 'master': 'node', 'wheelPad': 1, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 0}, 'labelCfg': {'text': 'fs'}, 'class': 'NEThumbWheel', 'oneTurn': 50.0}
def beforeAddingToNetwork(self, net):
try:
ed = net.getEditor()
except:
import traceback; traceback.print_exc()
print 'Warning! Could not import widgets'
```
#### File: scipylib/signal/waveRead.py
```python
import wave
# import node's base class node
from NetworkEditor.items import NetworkNode
class waveRead(NetworkNode):
mRequiredTypes = {}
mRequiredSynonyms = [
]
def __init__(self, constrkw = {}, name='waveRead', **kw):
kw['constrkw'] = constrkw
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
code = """def doit(self, filename):
if filename and len(filename):
f = wave.open(filename,'rb')
sampleRate= f.getframerate()
channels= f.getnchannels()
datastream= f.readframes( 300000 )
f.close()
self.outputData(data=datastream)
## to ouput data on port sample_rate use
self.outputData(sample_rate=sampleRate)
## to ouput data on port num_channels use
self.outputData(num_channels=channels)
"""
self.configure(function=code)
self.inputPortsDescr.append(
{'singleConnection': True, 'name': 'filename', 'cast': True, 'datatype': 'string', 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
self.outputPortsDescr.append(
{'name': 'data', 'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'cyan'})
self.outputPortsDescr.append(
{'name': 'sample_rate', 'datatype': 'None', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.outputPortsDescr.append(
{'name': 'num_channels', 'datatype': 'None', 'height': 8, 'width': 12, 'shape': 'diamond', 'color': 'white'})
self.widgetDescr['filename'] = {
'initialValue': '', 'labelGridCfg': {'column': 0, 'row': 1}, 'width': 16, 'master': 'node', 'widgetGridCfg': {'labelSide': 'left', 'column': 1, 'row': 1}, 'labelCfg': {'text': 'file:'}, 'class': 'NEEntryWithFileBrowser'}
def beforeAddingToNetwork(self, net):
try:
ed = net.getEditor()
except:
import traceback; traceback.print_exc()
print 'Warning! Could not import widgets'
```
#### File: MGLToolsPckgs/Vision/matplotlibNodes.py
```python
try:
import matplotlib
except:
import warnings
import sys
if sys.platform == 'linux2':
warnings.warn("""to use matplotlib, you need first to install openssl
the mgltools 32 bit linux binaries need openssl version 0.9.7
the mgltools 64 bit linux binaries need openssl version 0.9.8
you can have both openssl versions (0.9.7 and 0.9.8) installed on your computer.
""", stacklevel=2)
import Tkinter
import types
import weakref
import Pmw,math,os, sys
from numpy.oldnumeric import array
from matplotlib.colors import cnames
from matplotlib.lines import Line2D,lineStyles,TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN
#from matplotlib.transforms import Value
from matplotlib import rcParams
#mplversion = int(matplotlib.__version__.split(".")[2])
mplversion = map(int, matplotlib.__version__.split("."))
#print "mplversion:", mplversion
"""
This module implements Vision nodes exposing matplotlib functionatility.
MPLBaseNE:
---------
The class provides a base class for all nodes exposing matplotlib functionality
its purpose is to to create the attributes described below and implement
methods shared by all nodes.
Attributes:
self.figure = None: # node's figure object
# This attribute always points to the matplotlib Figure object which has
# a FigureCanvasTkAgg object in its .canvas attribute
# self.canvas FigureCanvasTkAgg
self.axes = None
# This attribute points to the matplotlib Axes instance used by this node
self.axes.figure # figure in which the axes is currently drawn
Methods:
def createFigure(self, master=None, width=None, height=None, dpi=None,
facecolor=None, edgecolor=None, frameon=None,
packOpts=None, toolbar=True):
# This method is used by all nodes if they need to create a Figure object
# from the matplotlib library and a FigureCanvasTkAgg object for this
# figure.
def setFigure(self, figure):
# This method place the node's axes object into the right Figure
def beforeRemovingFromNetwork(self):
# this method is called when a node is deleted from a network. Its job is
# to delete FigureCanvasTkAgg and Axes when appropriate.
MPLFigure:
-----------
The MPLFigure node allows the creation of a plotting area in which one
or more Axes can be added, where an Axes is a 2D graphical representation
of a data set (i.e. 2D plot). A 'master' can be apecified to embed the figure
in other panels. This node provides control over parameter that apply to the
MPLFigure such, width, height, dpi, etc.
Plotting Node:
-------------
Plotting nodes such as Histogram, Plot, Scatter, Pie, etc. take adtasets and
render them as 2D plots. They alwas own the axes.
If the data to be rendered is the only input to these nodes, they will create
a default Figure, add a default Plot2D to this figure, and draw the data in
this default 2D plot.
"""
from mglutil.util.callback import CallBackFunction
from NetworkEditor.widgets import TkPortWidget, PortWidget
from mglutil.gui.BasicWidgets.Tk.thumbwheel import ThumbWheel
from Vision import UserLibBuild
from NetworkEditor.items import NetworkNode
# make sure Tk is used as a backend
if not 'matplotlib.backends' in sys.modules:
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
from matplotlib.figure import Figure as OriginalFigure
from matplotlib.axes import Axes, Subplot #, PolarSubplot, PolarAxes
from matplotlib.pylab import *
from Vision.colours import get_colours
from Vision.posnegFill import posNegFill
import numpy
from matplotlib.artist import setp
##
## QUESTIONS
## Does this have to be Tk specific or could I use FigureCanvasAgg
## !FigureCanvasAgg is OK
## Should I use FigureManagerBase rather than FigureCanvasAgg ?
## ! FigureCanvas Agg is OK
## how to destroy a figure ?
## ! seems to work
## figure should have a set_dpi method
## ! use figure.dpi.set() for now but might become API later
## how to remove the tool bar ?
## ! John added a note about this
## What option in a Figure can beset without destroying the Figure
## and which ones are constructor only options ?
## ! nothing should require rebuilding a Figure
## Why does add_axes return the axis that already exists if the values for
## building the Axes object are the same ? either this has to change or
## adding an instance of an Axes should be fixed (prefered)
## !John made a note to add an argument to matplotlib
## Pie seems to have a problem when shadow is on !
## !Find out the problem, because shadows are on even when check button is off
## !for ce aspect ratio to square
## Plot lineStyle, color, linewidth etc should be set by a set node that uses
## introspection on the patch? to find otu what can be set ??
## !Use ObjectInspector
## why is figimage not an axes method ?
## !use imshow
from matplotlib.cbook import iterable
try:
from matplotlib.dates import DayLocator, HourLocator, \
drange, date2num
from pytz import timezone
except:
pass
try:
from pytz import common_timezones
except:
common_timezones=[]
#global variables
locations={'best' : 0,
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,}
colors={
'blue' : 'b',
'green' : 'g',
'red' : 'r',
'cyan' : 'c',
'magenta' :'m',
'yellow' :'y',
'black': 'k',
'white' : 'w',
}
markers= {
'square' : 's',
'circle' : 'o',
'triangle up' : '^',
'triangle right' : '>',
'triangle down' : 'v',
'triangle left' : '<',
'diamond' : 'd',
'pentagram' : 'p',
'hexagon' : 'h',
'octagon' : '8',
}
cmaps=['autumn','bone', 'cool','copper','flag','gray','hot','hsv','jet','pink', 'prism', 'spring', 'summer', 'winter']
def get_styles():
styles={}
for ls in Line2D._lineStyles.keys():
styles[Line2D._lineStyles[ls][6:]]=ls
for ls in Line2D._markers.keys():
styles[Line2D._markers[ls][6:]]=ls
#these styles are not recognized
if styles.has_key('steps'):
del styles['steps']
for s in styles.keys():
if s =="nothing":
del styles['nothing']
if s[:4]=='tick':
del styles[s]
return styles
class Figure(OriginalFigure):
# sub class Figure to override add_axes
def add_axes(self, *args, **kwargs):
"""hack to circumvent the issue of not adding an axes if the constructor
params have already been seen"""
if kwargs.has_key('force'):
force = kwargs['force']
del kwargs['force']
else:
force = False
if iterable(args[0]):
key = tuple(args[0]), tuple(kwargs.items())
else:
key = args[0], tuple(kwargs.items())
if not force and self._seen.has_key(key):
ax = self._seen[key]
self.sca(ax)
return ax
if not len(args): return
if isinstance(args[0], Axes):
a = args[0]
# this is too early, if done here bbox is 0->1
#a.set_figure(self)
a.figure = self
else:
rect = args[0]
#ispolar = popd(kwargs, 'polar', False)
ispolar = kwargs.get('polar', False)
if ispolar != False:
del kwargs['polar']
if ispolar:
a = PolarAxes(self, rect, **kwargs)
else:
a = Axes(self, rect, **kwargs)
self.axes.append(a)
self._axstack.push(a)
self.sca(a)
self._seen[key] = a
return a
class MPLBaseNE(NetworkNode):
"""Base class for node wrapping the maptlotlib objects
"""
def __init__(self, name='MPLBase', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.figure = None # matplotlib Figure instance belonging to this node
self.axes = None # matplotlib Axes instance
# this is true for Figures who create the Tk Toplevel
# or plotting nodes that have no figure parent node
# it is used to decide when the Toplevel should be destroyed
self.ownsMaster = False
def setDrawArea(self, kw):
ax = self.axes
#ax.clear()
if kw.has_key('left'):
rect = [kw['left'], kw['bottom'], kw['width'], kw['height']]
ax.set_position(rect)
if kw.has_key('frameon'):
ax.set_frame_on(kw['frameon'])
if kw.has_key("title"):
if type(kw['title'])==types.StringType:
ax.set_title(kw['title'])
else:
print 'Set title as Object'
if kw.has_key("xlabel"):
ax.set_xlabel(kw['xlabel'])
if kw.has_key("ylabel"):
ax.set_ylabel(kw['ylabel'])
if kw.has_key("xlimit"):
if kw['xlimit']!='':
ax.set_xlim(eval(kw['xlimit']))
if kw.has_key("ylimit"):
if kw['ylimit']!='':
ax.set_ylim(eval(kw['ylimit']))
if kw.has_key("xticklabels"):
if not kw['xticklabels']:
ax.set_xticklabels([])
if kw.has_key("yticklabels"):
if not kw['yticklabels']:
ax.set_yticklabels([])
if kw.has_key("axison"):
if kw['axison']:
ax.set_axis_on()
else:
ax.set_axis_off()
if kw.has_key("autoscaleon"):
if kw['autoscaleon']:
ax.set_autoscale_on(True)
else:
ax.set_autoscale_on(False)
if kw.has_key("adjustable"):
ax.set_adjustable(kw['adjustable'])
if kw.has_key("aspect"):
ax.set_aspect(kw['aspect'])
if kw.has_key("anchor"):
ax.set_anchor(kw['anchor'])
if kw.has_key("axisbelow"):
if kw['axisbelow']==1:
val=True
else:
val=False
rcParams['axes.axisbelow']=val
ax.set_axisbelow(val)
#grid properties
if kw.has_key("gridOn"):
if kw['gridOn']==1:
ax._gridOn=True
val=True
if kw.has_key('gridcolor'):
gcolor=kw['gridcolor']
else:
gcolor=rcParams['grid.color']
if kw.has_key('gridlinestyle'):
glinestyle=kw['gridlinestyle']
else:
glinestyle=rcParams['grid.linestyle']
if kw.has_key('gridlinewidth'):
glinewidth=kw['gridlinewidth']
else:
glinewidth=rcParams['grid.linewidth']
if kw.has_key('whichgrid'):
whichgrid=kw['whichgrid']
else:
whichgrid='major'
ax.grid(val,color=gcolor, linestyle=glinestyle, linewidth=glinewidth,which=whichgrid)
else:
val=False
ax.grid(val)
if kw.has_key("facecolor"):
ax.set_axis_bgcolor(kw['facecolor'])
if kw.has_key("edgecolor"):
if hasattr(ax, "axesFrame"):
ax.axesFrame.set_edgecolor(kw['edgecolor'])
elif hasattr(ax, "axesPatch"):
ax.axesPatch.set_edgecolor(kw['edgecolor'])
# if kw.has_key('zoomx'):
# #Zoom in on the x xaxis numsteps (plus for zoom in, minus for zoom out)
# ax.zoomx(kw['zoomx'])
#
# if kw.has_key('zoomy'):
# #Zoom in on the x xaxis numsteps (plus for zoom in, minus for zoom out)
# ax.zoomy(kw['zoomy'])
if kw.has_key("xtick.color"):
for i in ax.xaxis.get_ticklabels():
i.set_color(kw['xtick.color'])
if kw.has_key("ytick.color"):
for i in ax.yaxis.get_ticklabels():
i.set_color(kw['ytick.color'])
if kw.has_key('xtick.labelrotation'):
for i in ax.xaxis.get_ticklabels():
i.set_rotation(float(kw['xtick.labelrotation']))
if kw.has_key('ytick.labelrotation'):
for i in ax.yaxis.get_ticklabels():
i.set_rotation(float(kw['ytick.labelrotation']))
if kw.has_key("xtick.labelsize"):
for i in ax.xaxis.get_ticklabels():
i.set_size(float(kw['xtick.labelsize']))
if kw.has_key("ytick.labelsize"):
for i in ax.yaxis.get_ticklabels():
i.set_size(float(kw['ytick.labelsize']))
if kw.has_key("linewidth"):
if hasattr(ax, "axesFrame"):
ax.axesFrame.set_linewidth(float(kw['linewidth']))
elif hasattr(ax, "axesPatch"):
ax.axesPatch.set_linewidth(float(kw['linewidth']))
#marker
if kw.has_key("markeredgewidth"):
for i in ax.get_xticklines():
i.set_markeredgewidth(kw['markeredgewidth'])
for i in ax.get_yticklines():
i.set_markeredgewidth(kw['markeredgewidth'])
if kw.has_key("markeredgecolor"):
for i in ax.get_xticklines():
i.set_markeredgecolor(kw['markeredgecolor'])
for i in ax.get_yticklines():
i.set_markeredgecolor(kw['markeredgecolor'])
if kw.has_key("markerfacecolor"):
for i in ax.get_xticklines():
i.set_markerfacecolor(kw['markerfacecolor'])
for i in ax.get_yticklines():
i.set_markerfacecolor(kw['markerfacecolor'])
#figure_patch properties
if kw.has_key("figpatch_linewidth"):
ax.figure.figurePatch.set_linewidth(kw['figpatch_linewidth'])
if kw.has_key("figpatch_facecolor"):
ax.figure.figurePatch.set_facecolor(kw['figpatch_facecolor'])
if kw.has_key("figpatch_edgecolor"):
ax.figure.figurePatch.set_edgecolor(kw['figpatch_edgecolor'])
if kw.has_key("figpatch_antialiased"):
ax.figure.figurePatch.set_antialiased(kw['figpatch_antialiased'])
#Text properties
if kw.has_key('text'):
for i in kw['text']:
if type(i)==types.DictType:
tlab=i['textlabel']
posx=i['posx']
posy=i['posy']
horizontalalignment=i['horizontalalignment']
verticalalignment=i['verticalalignment']
rotation=i['rotation']
ax.text(x=posx,y=posy,s=tlab,horizontalalignment=horizontalalignment,verticalalignment=verticalalignment,rotation=rotation,transform = ax.transAxes)
if kw.has_key("text.color"):
for t in ax.texts:
t.set_color(kw['text.color'])
if kw.has_key("text.usetex"):
rcParams['text.usetex']=kw['text.usetex']
if kw.has_key("text.dvipnghack"):
rcParams['text.dvipnghack']=kw['text.dvipnghack']
if kw.has_key("text.fontstyle"):
for t in ax.texts:
t.set_fontstyle(kw['text.fontstyle'])
if kw.has_key("text.fontangle"):
for t in ax.texts:
t.set_fontangle(kw['text.fontangle'])
if kw.has_key("text.fontvariant"):
for t in ax.texts:
t.set_fontvariant(kw['text.fontvariant'])
if kw.has_key("text.fontweight"):
for t in ax.texts:
t.set_fontweight(kw['text.fontweight'])
if kw.has_key("text.fontsize"):
for t in ax.texts:
t.set_fontsize(kw['text.fontsize'])
#Font
if kw.has_key("Font.fontfamily"):
for t in ax.texts:
t.set_family(kw['Font.fontfamily'])
if kw.has_key("Font.fontstyle"):
for t in ax.texts:
t.set_fontstyle(kw['Font.fontstyle'])
if kw.has_key("Font.fontangle"):
for t in ax.texts:
t.set_fontangle(kw['Font.fontangle'])
if kw.has_key("Font.fontvariant"):
for t in ax.texts:
t.set_fontvariant(kw['Font.fontvariant'])
if kw.has_key("Font.fontweight"):
for t in ax.texts:
t.set_fontweight(kw['Font.fontweight'])
if kw.has_key("Font.fontsize"):
for t in ax.texts:
t.set_fontsize(kw['Font.fontsize'])
#Legend Properties
if mplversion[0]==0 and mplversion[2]<=3 :
if kw.has_key('legendlabel'):
if ',' in kw['legendlabel']:
x=kw['legendlabel'].split(",")
else:
x=(kw['legendlabel'],)
if kw.has_key('legend.isaxes'):
isaxes=kw['legend.isaxes']
else:
isaxes=rcParams['legend.isaxes']
if kw.has_key('legend.numpoints'):
numpoints=kw['legend.numpoints']
else:
numpoints=rcParams['legend.numpoints']
if kw.has_key('legend.pad'):
borderpad=kw['legend.pad']
else:
borderpad=rcParams['legend.pad']
if kw.has_key('legend.markerscale'):
markerscale=kw['legend.markerscale']
else:
markerscale=rcParams['legend.markerscale']
if kw.has_key('legend.labelsep'):
labelspacing=kw['legend.labelsep']
else:
labelspacing=rcParams['legend.labelsep']
if kw.has_key('legend.handlelen'):
handlelength=kw['legend.handlelen']
else:
handlelength=rcParams['legend.handlelen']
if kw.has_key('legend.handletextsep'):
handletextpad=kw['legend.handletextsep']
else:
handletextpad=rcParams['legend.handletextsep']
if kw.has_key('legend.axespad'):
borderaxespad=kw['legend.axespad']
else:
borderaxespad=rcParams['legend.axespad']
if kw.has_key('legend.shadow'):
shadow=kw['legend.shadow']
else:
shadow=rcParams['legend.shadow']
#import pdb;pdb.set_trace()
leg=self.axes.legend(tuple(x),loc=kw['legendlocation'],
#isaxes=isaxes,
numpoints=numpoints,
pad=borderpad,
labelsep=labelspacing,
handlelen=handlelength,
handletextsep=handletextpad,
axespad=borderaxespad,
shadow=shadow,
markerscale=markerscale)
if kw.has_key('legend.fontsize'):
setp(ax.get_legend().get_texts(),fontsize=kw['legend.fontsize'])
elif mplversion[0] > 0:
if kw.has_key('legendlabel'):
if ',' in kw['legendlabel']:
x=kw['legendlabel'].split(",")
else:
x=(kw['legendlabel'],)
if kw.has_key('legend.isaxes'):
isaxes=kw['legend.isaxes']
else:
isaxes=rcParams['legend.isaxes']
if kw.has_key('legend.numpoints'):
numpoints=kw['legend.numpoints']
else:
numpoints=rcParams['legend.numpoints']
if kw.has_key('legend.borderpad'):
borderpad=kw['legend.borderpad']
else:
borderpad=rcParams['legend.borderpad']
if kw.has_key('legend.markerscale'):
markerscale=kw['legend.markerscale']
else:
markerscale=rcParams['legend.markerscale']
if kw.has_key('legend.labelspacing'):
labelspacing=kw['legend.labelspacing']
else:
labelspacing=rcParams['legend.labelspacing']
if kw.has_key('legend.handlelength'):
handlelength=kw['legend.handlelength']
else:
handlelength=rcParams['legend.handlelength']
if kw.has_key('legend.handletextpad'):
handletextpad=kw['legend.handletextpad']
else:
handletextpad=rcParams['legend.handletextpad']
if kw.has_key('legend.borderaxespad'):
borderaxespad=kw['legend.borderaxespad']
else:
borderaxespad=rcParams['legend.borderaxespad']
if kw.has_key('legend.shadow'):
shadow=kw['legend.shadow']
else:
shadow=rcParams['legend.shadow']
#import pdb;pdb.set_trace()
leg=self.axes.legend(tuple(x),loc=kw['legendlocation'],
#isaxes=isaxes,
numpoints=numpoints,
borderpad=borderpad,
labelspacing=labelspacing,
handlelength=handlelength,
handletextpad=handletextpad,
borderaxespad=borderaxespad,
shadow=shadow,
markerscale=markerscale)
if kw.has_key('legend.fontsize'):
setp(ax.get_legend().get_texts(),fontsize=kw['legend.fontsize'])
#Tick Options
if kw.has_key('xtick.major.pad'):
for i in ax.xaxis.majorTicks:
i.set_pad(kw['xtick.major.pad'])
if kw.has_key('xtick.minor.pad'):
for i in ax.xaxis.minorTicks:
i.set_pad(kw['xtick.minor.pad'])
if kw.has_key('ytick.major.pad'):
for i in ax.yaxis.majorTicks:
i.set_pad(kw['ytick.major.pad'])
if kw.has_key('ytick.minor.pad'):
for i in ax.yaxis.minorTicks:
i.set_pad(kw['ytick.minor.pad'])
if kw.has_key('xtick.major.size'):
rcParams['xtick.major.size']=kw['xtick.major.size']
if kw.has_key('xtick.minor.size'):
rcParams['xtick.minor.size']=kw['xtick.minor.size']
if kw.has_key('xtick.direction'):
rcParams['xtick.direction']=kw['xtick.direction']
if kw.has_key('ytick.major.size'):
rcParams['ytick.major.size']=kw['ytick.major.size']
if kw.has_key('ytick.minor.size'):
rcParams['ytick.minor.size']=kw['ytick.minor.size']
if kw.has_key('ytick.direction'):
rcParams['ytick.direction']=kw['ytick.direction']
def beforeRemovingFromNetwork(self):
#print 'remove'
NetworkNode.beforeRemovingFromNetwork(self)
# this happens for drawing nodes with no axes specified
if self.axes:
self.axes.figure.delaxes(self.axes) # feel a little strange !
self.canvas._tkcanvas.master.destroy()
elif self.canvas:
self.canvas._tkcanvas.master.destroy()
def onlyDataChanged(self, data):
"""returns true if only he first port (i.e. data) has new data.
"""
# This can be used to accelerate redraw by only updating the data
# rather than redrawing the whole figure
# see examples/animation_blit_tk.py
ports = self.inputPorts
if not ports[0].hasNewValidData():
return False
for p in self.inputPorts:
if p.hasNewValidData():
return False
return True
class MPLFigureNE(MPLBaseNE):
"""This node instanciates a Figure object and its FigureCanvasTkAgg object
in its .canvas attribute.
It also provide control over parameters such as width, height, dpi, etc.
Input:
plots - Matplotlib Axes objects
figwidth - width in inches
figheigh - height in inches
dpi - resolution; defaults to rc figure.dpi
facecolor - the background color; defaults to rc figure.facecolor
edgecolor - the border color; defaults to rc figure.edgecolor
master - Defaults to None, creating a topLevel
nbRows - number of rows for subgraph2D
nbColumns - number of columns for subgraph2D
frameon - boolean
hold - boolean
toolbar - boolean (init option only)
packOpts - string representation of packing options
Output:
canvas: MPLFigure Object
Todo:
legend
text
image ?
"""
def afterAddingToNetwork(self):
self.figure = Figure()
master = Tkinter.Toplevel()
master.title(self.name)
self.canvas = FigureCanvasTkAgg(self.figure, master)
self.figure.set_canvas(self.canvas)
packOptsDict = {'side':'top', 'fill':'both', 'expand':1}
self.canvas.get_tk_widget().pack( *(), **packOptsDict )
toolbar = NavigationToolbar2TkAgg(self.canvas, master)
def __init__(self, name='Figure2', **kw):
kw['name'] = name
apply( MPLBaseNE.__init__, (self,), kw )
codeBeforeDisconnect = """def beforeDisconnect(self, c):
node1 = c.port1.node
node2 = c.port2.node
if node2.figure.axes:
node2.figure.delaxes(node1.axes)
if node1.figure.axes:
node1.figure.delaxes(node1.axes)
node1.figure.add_axes(node1.axes)
"""
ip = self.inputPortsDescr
ip.append(datatype='MPLAxes', required=False, name='plots',
singleConnection=False,
beforeDisconnect=codeBeforeDisconnect)
ip.append(datatype='float', required=False, name='width')
ip.append(datatype='float', required=False, name='height')
ip.append(datatype='float', required=False, name='linewidth', defaultValue=1)
ip.append(datatype='int', required=False, name='dpi')
ip.append(datatype='colorRGB', required=False, name='facecolor')
ip.append(datatype='colorRGB', required=False, name='edgecolor')
ip.append(datatype='None', required=False, name='master')
ip.append(datatype='int', required=False, name='nbRows')
ip.append(datatype='int', required=False, name='nbColumns')
ip.append(datatype='boolean', required=False, name='frameon', defaultValue=True)
ip.append(datatype='boolean', required=False, name='hold', defaultValue=False)
ip.append(datatype='boolean', required=False, name='toolbar')
ip.append(datatype='None', required=False, name='packOpts')
op = self.outputPortsDescr
op.append(datatype='MPLFigure', name='figure')
self.widgetDescr['width'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':8.125,
'labelCfg':{'text':'width in inches'} }
self.widgetDescr['height'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':6.125,
'labelCfg':{'text':'height in inches'} }
self.widgetDescr['linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['dpi'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10, 'type':'int',
'wheelPad':2, 'initialValue':80,
'labelCfg':{'text':'DPI'} }
self.widgetDescr['nbRows'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'nb. rows'} }
self.widgetDescr['nbColumns'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'nb. col'} }
self.widgetDescr['frameon'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':1, 'labelCfg':{'text':'frame'} }
self.widgetDescr['hold'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':0, 'labelCfg':{'text':'hold'} }
self.widgetDescr['toolbar'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':1, 'labelCfg':{'text':'toolbar'} }
self.widgetDescr['packOpts'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'packing Opts.:'},
'initialValue':'{"side":"top", "fill":"both", "expand":1}'}
code = """def doit(self, plots, width, height, linewidth, dpi, facecolor,
edgecolor, master, nbRows, nbColumns, frameon, hold, toolbar, packOpts):
self.figure.clear()
if plots is not None:
for p in plots:
self.figure.add_axes(p)
figure = self.figure
# configure size
if width is not None or height is not None:
defaults = matplotlib.rcParams
if width is None:
width = defaults['figure.figsize'][0]
elif height is None:
height = defaults['figure.figsize'][1]
figure.set_size_inches(width,height)
# configure dpi
if dpi is not None:
figure.set_dpi(dpi)
# configure facecolor
if facecolor is not None:
figure.set_facecolor(facecolor)
# configure edgecolor
if edgecolor is not None:
figure.set_edgecolor(facecolor)
# configure frameon
if edgecolor is not None:
figure.set_edgecolor(facecolor)
# not sure linewidth is doing anything here
figure.figurePatch.set_linewidth(linewidth)
figure.hold(hold)
# FIXME for now we store this here but we might want to add this as
# regular attributes to Figure which would be used with subplot
#figure.nbRows = nbRows
#figure.nbColumns = nbColumns
self.canvas.draw()
self.outputData(figure=self.figure)
"""
self.setFunction(code)
class MPLImageNE(MPLBaseNE):
"""This node creates a PIL image
Input:
plots - Matplotlib Axes objects
figwidth - width in inches
figheigh - height in inches
dpi - resolution; defaults to rc figure.dpi
facecolor - the background color; defaults to rc figure.facecolor
edgecolor - the border color; defaults to rc figure.edgecolor
faceAlpha - alpha value of background
edgeAlpha - alpha value of edge
frameon - boolean
hold - boolean
toolbar - boolean (init option only)
packOpts - string representation of packing options
Output:
canvas: MPLFigure Object
Todo:
legend
text
image ?
"""
def __init__(self, name='imageFigure', **kw):
kw['name'] = name
apply( MPLBaseNE.__init__, (self,), kw )
codeBeforeDisconnect = """def beforeDisconnect(self, c):
node1 = c.port1.node
node2 = c.port2.node
if node1.figure.axes:
node1.figure.delaxes(node1.axes)
node1.figure.add_axes(node1.axes)
"""
ip = self.inputPortsDescr
ip.append(datatype='MPLAxes', required=False, name='plots',
singleConnection=False,
beforeDisconnect=codeBeforeDisconnect)
ip.append(datatype='float', required=False, name='width')
ip.append(datatype='float', required=False, name='height')
ip.append(datatype='int', required=False, name='dpi')
ip.append(datatype='colorsRGB', required=False, name='facecolor')
ip.append(datatype='colorsRGB', required=False, name='edgecolor')
ip.append(datatype='float', required=False, name='alphaFace', defaultValue=0.5)
ip.append(datatype='float', required=False, name='alphaEdge', defaultValue=0.5)
ip.append(datatype='boolean', required=False, name='frameon', defaultValue=True)
ip.append(datatype='boolean', required=False, name='hold', defaultValue=False)
op = self.outputPortsDescr
op.append(datatype='image', name='image')
self.widgetDescr['width'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':6.4,
'labelCfg':{'text':'width in inches'} }
self.widgetDescr['height'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':4.8,
'labelCfg':{'text':'height in inches'} }
self.widgetDescr['dpi'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10, 'type':'int',
'wheelPad':2, 'initialValue':80,
'labelCfg':{'text':'DPI'} }
self.widgetDescr['alphaFace'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'wheelPad':2, 'initialValue':0.5, 'min':0.0, 'max':1.0,
'labelCfg':{'text':'alpha Face'} }
self.widgetDescr['alphaEdge'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'wheelPad':2, 'initialValue':0.5, 'min':0.0, 'max':1.0,
'labelCfg':{'text':'alphaEdge'} }
self.widgetDescr['frameon'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':1, 'labelCfg':{'text':'frame'} }
self.widgetDescr['hold'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':0, 'labelCfg':{'text':'hold'} }
code = """def doit(self, plots, width, height, dpi, facecolor, edgecolor,
alphaFace, alphaEdge, frameon, hold):
figure = self.figure
try:
self.canvas.renderer.clear()
except AttributeError:
pass
figure.clear()
# Powers of 2 image to be clean
if width>height:
htc = float(height)/width
w = 512
h = int(round(512*htc))
else:
wtc = float(width)/height
w = int(round(512*wtc))
h = 512
figure.set_size_inches(float(w)/dpi, float(h)/dpi)
for p in plots:
if hasattr(p,"figure"):
p.figure.set_figwidth(float(w) / dpi)
p.figure.set_figheight(float(h) / dpi)
figure.add_axes(p)
p.set_figure(figure)
p.axesPatch.set_alpha(alphaFace)
# configure dpi
if dpi is not None:
figure.set_dpi(dpi)
# configure facecolor
if facecolor is not None:
figure.set_facecolor(tuple(facecolor[0]))
# configure edgecolor
if edgecolor is not None:
figure.set_edgecolor(tuple(edgecolor[0]))
# configure frameon
if frameon is not None:
figure.set_frameon(frameon)
figure.hold(hold)
figure.figurePatch.set_alpha(alphaEdge)
self.canvas.draw() # force a draw
import Image
im = self.canvas.buffer_rgba(0,0)
ima = Image.frombuffer("RGBA", (w, h), im)
ima = ima.transpose(Image.FLIP_TOP_BOTTOM)
self.outputData(image=ima)
"""
self.setFunction(code)
def beforeRemovingFromNetwork(self):
#print 'remove'
NetworkNode.beforeRemovingFromNetwork(self)
# this happens for drawing nodes with no axes specified
if self.axes:
self.axes.figure.delaxes(self.axes) # feel a little strange !
def afterAddingToNetwork(self):
self.figure = Figure()
from matplotlib.backends.backend_agg import FigureCanvasAgg
self.canvas = FigureCanvasAgg(self.figure)
class MPLDrawAreaNE(NetworkNode):
"""Class for configuring the axes.
The following options can be set.
left,bottom,width,height ----allows to set the position of the axes.
frame on/off --- allows to on or off frame
hold on/off --- allows to on or off hold.When hold is True, subsequent plot commands will be added to
the current axes. When hold is False, the current axes and figure will be cleared on
the next plot command
title --- allows to set title of the figure
xlabel ---allows to set xlabel of the figure
ylabel ---allows to set ylabel of the figure
xlimit --- set autoscale off before setting xlimit.
y limit --- set autoscale off before setting ylimit.
xticklabels on/off --- allows to on or off xticklabels
yticklabels on/off --- allows to on or off yticklabels
axis on/off --- allows to on or off axis
autoscale on/off --- when on sets default axes limits ,when off sets limit from xlimit and ylimit entries.
"""
def __init__(self, name='Draw Area', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='float', required=False, name='left', defaultValue=.1)
ip.append(datatype='float', required=False, name='bottom', defaultValue=.1)
ip.append(datatype='float', required=False, name='width', defaultValue=.8)
ip.append(datatype='float', required=False, name='height', defaultValue=.8)
ip.append(datatype='boolean', required=False, name='frameon', defaultValue=True)
ip.append(datatype='boolean', required=False, name='hold', defaultValue=False)
ip.append(datatype='string', required=False, name='title', defaultValue='Figure')
ip.append(datatype='string', required=False, name='xlabel', defaultValue='X')
ip.append(datatype='string', required=False, name='ylabel', defaultValue='Y')
ip.append(datatype='string', required=False, name='xlimit', defaultValue='')
ip.append(datatype='string', required=False, name='ylimit', defaultValue='')
ip.append(datatype='boolean', required=False, name='xticklabels', defaultValue=True)
ip.append(datatype='boolean', required=False, name='yticklabels', defaultValue=True)
ip.append(datatype='boolean', required=False, name='axison', defaultValue=True)
ip.append(datatype='boolean', required=False, name='autoscaleon', defaultValue=True)
self.widgetDescr['left'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'labelGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.1,
'labelCfg':{'text':'left (0. to 1.)'} }
self.widgetDescr['bottom'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'labelGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.1,
'labelCfg':{'text':'bottom (0. to 1.)'} }
self.widgetDescr['width'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'labelGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.8,
'labelCfg':{'text':'width (0. to 1.)'} }
self.widgetDescr['height'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'labelGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.8,
'labelCfg':{'text':'height (0. to 1.0)'} }
self.widgetDescr['frameon'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelGridCfg':{'sticky':'w'},
'initialValue':1, 'labelCfg':{'text':'frame'} }
self.widgetDescr['hold'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelGridCfg':{'sticky':'w'},
'initialValue':0, 'labelCfg':{'text':'hold'} }
self.widgetDescr['title'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'title'},'labelGridCfg':{'sticky':'w'},
'initialValue':'Figure:'}
self.widgetDescr['xlabel'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'X label'},'labelGridCfg':{'sticky':'w'},
'initialValue':'X'}
self.widgetDescr['ylabel'] = {
'class':'NEEntry', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Y label'},
'initialValue':'Y'}
self.widgetDescr['xlimit'] = {
'class':'NEEntry', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},
'labelCfg':{'text':'X limit'},
'initialValue':''}
self.widgetDescr['ylimit'] = {
'class':'NEEntry', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Y limit'},
'initialValue':''}
self.widgetDescr['xticklabels'] = {
'class':'NECheckButton', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},
'initialValue':1, 'labelCfg':{'text':'xticklabels'} }
self.widgetDescr['yticklabels'] = {
'class':'NECheckButton', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},'labelGridCfg':{'sticky':'w'},
'initialValue':1, 'labelCfg':{'text':'yticklabels'} }
self.widgetDescr['axison'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':1, 'labelCfg':{'text':'axis on'} }
self.widgetDescr['autoscaleon'] = {
'class':'NECheckButton', 'master':'ParamPanel','labelGridCfg':{'sticky':'w'},
'initialValue':1, 'labelCfg':{'text':'autoscale on'} }
op = self.outputPortsDescr
op.append(datatype='MPLDrawArea', name='drawAreaDef')
code = """def doit(self, left, bottom, width, height, frameon, hold, title,
xlabel, ylabel, xlimit, ylimit, xticklabels, yticklabels, axison, autoscaleon):
kw = {'left':left, 'bottom':bottom, 'width':width, 'height':height,
'frameon':frameon, 'hold':hold, 'title':title, 'xlabel':xlabel,
'ylabel':ylabel, 'axison':axison, 'xticklabels': xticklabels,'yticklabels': yticklabels,'xlimit':xlimit,'ylimit':ylimit,'autoscaleon':autoscaleon}
self.outputData(drawAreaDef=kw)
"""
self.setFunction(code)
class MPLMergeTextNE(NetworkNode):
"""Class for writting multiple labels in the axes.Takes input from Text
nodes.
"""
def __init__(self, name='MergeText', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MPLDrawArea', required=False,name='textlist',singleConnection=False)
op = self.outputPortsDescr
op.append(datatype='MPLDrawArea', name='drawAreaDef')
code = """def doit(self,textlist):
kw={'text':textlist}
self.outputData(drawAreaDef=kw)
"""
self.setFunction(code)
class MPLPlottingNode(MPLBaseNE):
"""Base class for plotting nodes"""
def afterAddingToNetwork(self):
self.figure = Figure()
self.axes = self.figure.add_subplot( 111 )
self.axes.node = weakref.ref(self)
master = Tkinter.Toplevel()
master.title(self.name)
self.canvas = FigureCanvasTkAgg(self.figure, master)
self.figure.set_canvas(self.canvas)
packOptsDict = {'side':'top', 'fill':'both', 'expand':1}
self.canvas.get_tk_widget().pack( *(), **packOptsDict )
self.canvas._master.protocol('WM_DELETE_WINDOW',self.canvas._master.iconify)
toolbar = NavigationToolbar2TkAgg(self.canvas, master)
def setDrawAreaDef(self, drawAreaDef):
newdrawAreaDef={}
if drawAreaDef:
if len(drawAreaDef)==1 and drawAreaDef[0] is not None:
#for d in drawAreaDef[0].keys():
# newdrawAreaDef[d]=drawAreaDef[0][d]
newdrawAreaDef = drawAreaDef[0]
elif len(drawAreaDef)>1:
for dAD in drawAreaDef:
if type(dAD)== types.DictType:
for j in dAD.keys():
newdrawAreaDef[j]=dAD[j]
self.setDrawArea(newdrawAreaDef)
codeBeforeDisconnect ="""def beforeDisconnect(self,c):
node=c.port2.node
node.axes.clear()
node.canvas.draw() """
########################################################################
####
#### PLOTTING NODES
####
########################################################################
class FillNE(MPLPlottingNode):
"""plots filled polygons.
x - list of x vertices
y - list of y vertices
fillcolor - color
"""
def __init__(self, name='Fill', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='fillcolor', defaultValue='w')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['fillcolor'] = {
'class':'NEComboBox', 'master':'node',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'white',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'fillcolor:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype='None', name='fig')
code = """def doit(self, x, y, fillcolor, drawAreaDef):
self.axes.clear()
ax=self.axes
p=ax.fill(x,y,fillcolor)
self.setDrawAreaDef(drawAreaDef)
self.canvas.draw()
self.outputData(axes=self.axes,fig=p)
"""
self.setFunction(code)
class PolarAxesNE(MPLPlottingNode):
""" This node plots on PolarAxes
Input:
y - sequence of values
x - None; sequence of values
Adjustable parameters:
grid --grid on or off(default is on)
gridcolor --color of the grid
gridlinewidth --linewidth of the grid
gridlinestyle --gridlinestyle
xtickcolor -- color of xtick
ytickcolor -- color of ytick
xticksize --size of xtick
yticksize --size of ytick
"""
def __init__(self, name='PolarAxes', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.styles={}
for ls in Line2D._lineStyles.keys():
self.styles[Line2D._lineStyles[ls][6:]]=ls
for ls in Line2D._markers.keys():
self.styles[Line2D._markers[ls][6:]]=ls
#these styles are not recognized
#del self.styles['steps']
for s in self.styles.keys():
if s =="nothing":
del self.styles['nothing']
if s[:4]=='tick':
del self.styles[s]
self.colors=colors
ip = self.inputPortsDescr
#ip.append(datatype='MPLAxes', required=False, name='p',
#singleConnection=True)#,beforeDisconnect=codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='lineStyle', defaultValue='solid')
ip.append(datatype='None', required=False, name='color', defaultValue='black')
ip.append(datatype='boolean', required=False, name='grid', defaultValue=1)
ip.append(datatype='str', required=False, name='gridlineStyle', defaultValue='--')
ip.append(datatype='str', required=False, name='gridcolor', defaultValue='gray')
ip.append(datatype='float', required=False, name='gridlinewidth', defaultValue=1)
ip.append(datatype='str', required=False, name='axisbg', defaultValue='white')
ip.append(datatype='str', required=False, name='xtickcolor', defaultValue='black')
ip.append(datatype='str', required=False, name='ytickcolor', defaultValue='black')
ip.append(datatype='float', required=False, name='xticksize', defaultValue=12)
ip.append(datatype='float', required=False, name='yticksize', defaultValue=12)
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['grid'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'initialValue':1, 'labelCfg':{'text':'grid'} ,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},}
self.widgetDescr['lineStyle'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.styles.keys(),
'fixedChoices':True,
'initialValue':'solid',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'line style:'}}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.colors.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['gridlineStyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':lineStyles.keys(),
'fixedChoices':True,
'initialValue':'--',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'gridlinestyle:'}}
self.widgetDescr['gridcolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'gray',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'gridcolor:'}}
self.widgetDescr['gridlinewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'gridlinewidth'},
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'}}
self.widgetDescr['axisbg'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'white',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'axisbg:'}}
self.widgetDescr['xtickcolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'xtickcolor:'}}
self.widgetDescr['ytickcolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'ytickcolor:'}}
self.widgetDescr['xticksize'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':12,
'labelCfg':{'text':'xticksize'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'} }
self.widgetDescr['yticksize'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':12,
'labelCfg':{'text':'yticksize'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'} }
op = self.outputPortsDescr
op.append(datatype='MPLFigure', name='figure')
code = """def doit(self, y, x, lineStyle, color, grid, gridlineStyle,
gridcolor, gridlinewidth, axisbg, xtickcolor, ytickcolor, xticksize, yticksize, drawAreaDef):
self.figure.clear()
self.setDrawAreaDef(drawAreaDef)
if grid==1:
matplotlib.rc('grid',color=gridcolor,linewidth=gridlinewidth,linestyle=gridlineStyle)
matplotlib.rc('xtick',color=xtickcolor,labelsize=xticksize)
matplotlib.rc('ytick',color=ytickcolor,labelsize=yticksize)
colorChar = self.colors[color]
lineStyleChar = self.styles[lineStyle]
new_axes=self.figure.add_axes(self.axes.get_position(),polar=True,axisbg=axisbg)
self.axes=new_axes
self.axes.plot(x, y, colorChar+lineStyleChar)
if grid!=1:
new_axes.grid(grid)
self.canvas.draw()
self.outputData(figure=self.figure)
"""
self.setFunction(code)
class StemNE(MPLPlottingNode):
"""A stem plot plots vertical lines (using linefmt) at each x location
from the baseline to y, and places a marker there using markerfmt. A
horizontal line at 0 is is plotted using basefmt
input: list of x values
Return value is (markerline, stemlines, baseline) .
"""
def __init__(self, name='Stem', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,),kw )
ip = self.inputPortsDescr
ip.append(datatype='list',required=True, name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',required=True, name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False,name='stemlinestyle', defaultValue='--')
ip.append(datatype='string',required=False,name='stemlinecolor', defaultValue='b')
ip.append(datatype='string',required=False,name='markerstyle', defaultValue='o')
ip.append(datatype='string',required=False,name='markerfacecolor', defaultValue='b')
ip.append(datatype='string',required=False,name='baselinecolor', defaultValue='b')
ip.append(datatype='string',required=False,name='baselinestyle', defaultValue='-')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['stemlinestyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['-.','--','-',':'],
'fixedChoices':True,
'initialValue':'--',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'stemlinestyle:'}}
self.widgetDescr['stemlinecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'stemlinecolor:'}}
self.widgetDescr['markerstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':Line2D._markers.keys(),
'fixedChoices':True,
'initialValue':'o',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'markerstyle:'}}
self.widgetDescr['markerfacecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'k',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'markerfacecolor:'}}
self.widgetDescr['baselinestyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['-.','--','-',':'],
'fixedChoices':True,
'initialValue':'-',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'baselinestyle:'}}
self.widgetDescr['baselinecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'k',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'baselinecolor:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='stem')
code = """def doit(self, x, y, stemlinestyle, stemlinecolor, markerstyle,
markerfacecolor, baselinecolor, baselinestyle, drawAreaDef):
self.axes.clear()
linefmt=stemlinecolor+stemlinestyle
markerfmt=markerfacecolor+markerstyle
basefmt= baselinecolor+baselinestyle
markerline, stemlines, baseline = self.axes.stem(x, y, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt )
self.setDrawAreaDef(drawAreaDef)
self.canvas.draw()
self.outputData(stem=self.axes)
"""
self.setFunction(code)
class MultiPlotNE(MPLPlottingNode):
"""This node allows to plot multiple plots on same axes
input: axes instances
"""
def __init__(self, name='MultiPlot', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,),kw )
ip = self.inputPortsDescr
ip.append(datatype='MPLAxes', required=True, name='multiplot', singleConnection=False,beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef', singleConnection=False)
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='multiplot')
code = """def doit(self, plots, drawAreaDef):
self.axes.clear()
ax=self.axes
if len(plots)>0:
ax.set_xlim(plots[0].get_xlim())
ax.set_ylim(plots[0].get_ylim())
for p in plots:
if p.patches!=[]:
for pt in p.patches:
ax.add_patch(pt)
elif p.lines!=[]:
if p.lines!=[]:
for pt in p.lines:
ax.add_line(pt)
elif p.collections!=[]:
if p.collections!=[]:
for pt in p.collections:
ax.add_collection(pt)
else:
ax.add_artist(p)
ax.autoscale_view()
self.setDrawAreaDef(drawAreaDef)
self.canvas.draw()
self.outputData(multiplot=self.axes)
"""
self.setFunction(code)
class TablePlotNE(MPLPlottingNode):
"""Adds a table to the current axes and plots bars.
input:
cellText - list of values
rowLabels - list of labels
rowColours - list of colors
colLabels - list of labels
colColours - list of colors
location - location where the table to be placed.
"""
def __init__(self, name='TablePlot', **kw):
"""
TABLE(cellText=None, cellColours=None,
cellLoc='right', colWidths=None,
rowLabels=None, rowColours=None, rowLoc='left',
colLabels=None, colColours=None, colLoc='center',
loc='bottom', bbox=None):
Adds a table to the current axes and plots bars.
"""
kw['name'] = name
locs=locations.keys()
locs.append("bottom")
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list',required=True, name='values',singleConnection="auto",beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',required=True, name='rowLabels',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',required=True, name='colLabels',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',required=False, name='rowColors')
ip.append(datatype='list',required=False, name='colColors')
ip.append(datatype='string',required=False, name='location', defaultValue='bottom')
ip.append(datatype='MPLDrawArea',required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['location'] = {
'class':'NEComboBox', 'master':'node',
'choices':locs,
'fixedChoices':True,
'initialValue':'bottom',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Location:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
code = """def doit(self, values, rowLabels, colLabels, rowColors,
colColors, location, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
#self.axes.set_position([0.2, 0.2, 0.7, 0.6])
data=[]
nd=[]
for val in values :
for v in val:
nd.append(float(v))
data.append(nd)
nd=[]
#rcolours = get_colours(len(colLabels))
rows = len(data)
ind = arange(len(colLabels)) + 0.3 # the x locations for the groups
cellText = []
width = 0.4 # the width of the bars
yoff = array([0.0] * len(colLabels)) # the bottom values for stacked bar chart
for row in xrange(rows):
self.axes.bar(ind, data[row], width, bottom=yoff, color=rowColors[row])
yoff = yoff + data[row]
cellText.append(['%1.1f' % x for x in yoff])
the_table = self.axes.table(cellText=cellText,
rowLabels=rowLabels,
rowColours=rowColors,
colColours=colColors,
colLabels=colLabels,
loc=location)
if location=="bottom":
self.axes.set_xticks([])
self.axes.set_xticklabels([])
self.canvas.draw()
self.outputData(plot=self.axes)
"""
self.setFunction(code)
class HistogramNE(MPLPlottingNode):
"""This nodes takes a list of values and builds a histogram using matplotlib
http://matplotlib.sourceforge.net/matplotlib.pylab.html#-hist
Compute the histogram of x. bins is either an integer number of
bins or a sequence giving the bins. x are the data to be binned.
The return values is (n, bins, patches)
If normed is true, the first element of the return tuple will be the
counts normalized to form a probability distribtion, ie,
n/(len(x)*dbin)
Addition kwargs: hold = [True|False] overrides default hold state
Input:
values: sequence of values
bins=10: number of dequence giving the gins
normed=0 normalize
Output:
plot Matplotlib Axes object
"""
def __init__(self, name='Histogram', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.colors=cnames
ip = self.inputPortsDescr
ip.append(datatype='None', name='values',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False, name='bins', defaultValue=10)
ip.append(datatype='boolean', required=False, name='normed', defaultValue=False)
ip.append(datatype='float', required=False, name='patch_antialiased', defaultValue=1)
ip.append(datatype='float', required=False, name='patch_linewidth', defaultValue=1)
ip.append(datatype='string', required=False, name='patch_edgecolor', defaultValue='black')
ip.append(datatype='string', required=False, name='patch_facecolor', defaultValue='blue')
ip.append(datatype='MPLDrawArea',required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['bins'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10, 'type':'int', 'wheelPad':2,
'initialValue':10,
'labelCfg':{'text':'# of bins'} }
self.widgetDescr['normed'] = {
'class':'NECheckButton', 'master':'node',
'initialValue':1, 'labelCfg':{'text':'normalize'},
}
self.widgetDescr['patch_linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['patch_antialiased'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'antialiased:'},
'initialValue':1,}
self.widgetDescr['patch_edgecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.colors.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'edgecolor:'}}
self.widgetDescr['patch_facecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.colors.keys(),
'fixedChoices':True,
'initialValue':'blue',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'facecolor:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
code = """def doit(self, values, bins, normed, patch_antialiased,
patch_linewidth, patch_edgecolor, patch_facecolor, drawAreaDef):
self.axes.clear()
n, bins, patches = self.axes.hist(values, bins=bins, normed=normed)
self.setDrawAreaDef(drawAreaDef)
if self.axes.patches:
for p in self.axes.patches:
p.set_linewidth(patch_linewidth)
p.set_edgecolor(patch_edgecolor)
p.set_facecolor(patch_facecolor)
p.set_antialiased(patch_antialiased)
self.canvas.draw()
self.outputData(plot=self.axes)
"""
self.setFunction(code)
#Plot Nodes
class PlotNE(MPLPlottingNode):
"""This nodes takes two lists of values and plots the the second against the first.
Input:
y - sequence of values
x - None; sequence of values
figure - None; MPLFigure object object into which to place the drawing
Output:
plot Matplotlib Axes object
line: - line
"""
def __init__(self, name='Plot', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.styles=get_styles()
self.colors=colors
self.joinstyles = Line2D.validJoin
self.capstyles = Line2D.validCap
ip = self.inputPortsDescr
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', required=False, name='x')
ip.append(datatype='string', required=False, name='lineStyle', defaultValue='solid')
ip.append(datatype='None', required=False, name='color', defaultValue='black')
ip.append(datatype='boolean', required=False, name='line_antialiased', defaultValue=1)
ip.append(datatype='float', required=False, name='line_linewidth', defaultValue=1)
ip.append(datatype='string', required=False, name='solid_joinstyle', defaultValue='miter')
ip.append(datatype='string', required=False, name='solid_capstyle', defaultValue='projecting')
ip.append(datatype='string', required=False, name='dash_capstyle', defaultValue='butt')
ip.append(datatype='string', required=False, name='dash_joinstyle', defaultValue='miter')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['lineStyle'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.styles.keys(),
'fixedChoices':True,
'initialValue':'solid',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'line style:'}}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.colors.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['dash_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'butt',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash_capstyle:'}}
self.widgetDescr['dash_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash _joinstyle:'}}
self.widgetDescr['solid_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'projecting',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_capstyle:'}}
self.widgetDescr['solid_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_joinstyle:'}}
self.widgetDescr['line_linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['line_antialiased'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'antialiased:'},
'initialValue':1,}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
code = """def doit(self, y, x, lineStyle, color, line_antialiased,
line_linewidth, solid_joinstyle, solid_capstyle, dash_capstyle, dash_joinstyle,
drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
colorChar = self.colors[color]
lineStyleChar = self.styles[lineStyle]
if x is None:
l = self.axes.plot(y, colorChar+lineStyleChar)
else:
l = self.axes.plot(x, y, colorChar+lineStyleChar)
#line properties
if self.axes.lines:
for l in self.axes.lines:
l.set_linewidth(line_linewidth)
l.set_antialiased(line_antialiased)
l.set_solid_joinstyle(solid_joinstyle)
l.set_solid_capstyle(solid_capstyle)
l.set_dash_capstyle(dash_capstyle)
l.set_dash_joinstyle(dash_joinstyle)
self.canvas.draw()
self.outputData(plot=self.axes)
"""
self.setFunction(code)
class PlotDateNE(MPLPlottingNode):
"""This nodes takes two lists of values and plots the the second against the first.
Input:
y - sequence of dates
x - sequence of dates
optional arguements:
lineStyle - line style
color - color of the line
(lineStyle+colorchar --fmt)
tz - timezone
xdate - is True, the x-axis will be labeled with dates
ydate - is True, the y-axis will be labeled with dates
Output:
plot Matplotlib Axes object
line: - line
pytz is required.
checks for pytz module and returns if not
"""
def __init__(self, name='PlotDate', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.styles=get_styles()
self.colors=colors
self.joinstyles = Line2D.validJoin
timezones=common_timezones
self.capstyles = Line2D.validCap
ip = self.inputPortsDescr
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='lineStyle', defaultValue='solid')
ip.append(datatype='None', required=False, name='color', defaultValue='black')
ip.append(datatype='string', required=False, name='tz', defaultValue='US/PACIFIC')
ip.append(datatype='boolean', required=False, name='xdate', defaultValue=True)
ip.append(datatype='boolean', required=False, name='ydate', defaultValue=False)
ip.append(datatype='boolean', required=False, name='line_antialiased', defaultValue=1)
ip.append(datatype='float', required=False, name='line_linewidth', defaultValue=1)
ip.append(datatype='string', required=False, name='solid_joinstyle', defaultValue='miter')
ip.append(datatype='string', required=False, name='solid_capstyle', defaultValue='projecting')
ip.append(datatype='string', required=False, name='dash_capstyle', defaultValue='butt')
ip.append(datatype='string', required=False, name='dash_joinstyle', defaultValue='miter')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
self.widgetDescr['lineStyle'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.styles.keys(),
'fixedChoices':True,
'initialValue':'circle',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'line style:'}}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.colors.keys(),
'fixedChoices':True,
'initialValue':'blue',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['tz'] = {
'class':'NEComboBox', 'master':'node',
'choices':timezones,
'fixedChoices':True,
'initialValue':'US/PACIFIC',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'timezone:'}}
self.widgetDescr['xdate'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'xdate:'},
'initialValue':1,}
self.widgetDescr['ydate'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'ydate:'},
'initialValue':0,}
self.widgetDescr['dash_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'butt',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash_capstyle:'}}
self.widgetDescr['dash_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash _joinstyle:'}}
self.widgetDescr['solid_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'projecting',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_capstyle:'}}
self.widgetDescr['solid_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_joinstyle:'}}
self.widgetDescr['line_linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['line_antialiased'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'antialiased:'},
'initialValue':1,}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
code = """def doit(self, y, x, lineStyle, color, tz, xdate, ydate,
line_antialiased, line_linewidth, solid_joinstyle, solid_capstyle, dash_capstyle,
dash_joinstyle, drawAreaDef):
try:
from pytz import common_timezones
except:
print "Could not import pytz "
return
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
colorChar = self.colors[color]
lineStyleChar = self.styles[lineStyle]
rcParams['timezone'] = tz
tz=timezone(tz)
fmt= colorChar+lineStyleChar
l = self.axes.plot_date(x, y, fmt=colorChar+lineStyleChar, tz=tz, xdate= xdate,ydate= ydate)
#line properties
if self.axes.lines:
for l in self.axes.lines:
l.set_linewidth(line_linewidth)
l.set_antialiased(line_antialiased)
l.set_solid_joinstyle(solid_joinstyle)
l.set_solid_capstyle(solid_capstyle)
l.set_dash_capstyle(dash_capstyle)
l.set_dash_joinstyle(dash_joinstyle)
self.canvas.draw()
self.outputData(plot=self.axes)
"""
self.setFunction(code)
class PieNE(MPLPlottingNode):
"""plots a pie diagram for a list of numbers. The size of each wedge
will be the fraction x/sumnumbers).
Input:
fractions - sequence of values
labels - None; sequence of labels (has to match length of factions
explode - None; float or sequence of values which specifies the
fraction of the radius to offset that wedge.
if a single float is given the list is generated automatically
shadow - True; if True, will draw a shadow beneath the pie.
format - None; fromat string used to label the wedges with their
numeric value
Output:
plot - Matplotlib Axes object
patches - sequence of matplotlib.patches.Wedge
texts - list of the label Text instances
autotextsline - list of text instances for the numeric labels (only if
format is not None
"""
def __init__(self, name='Pie', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='fractions',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', required=False, name='labels')
ip.append(datatype='None', required=False, name='explode')
ip.append(datatype='boolean', required=False, name='shadow')
ip.append(datatype='string', required=False, name='format')
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['explode'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10, 'type':'float',
'initialValue':0.05, 'wheelPad':2,
'labelCfg':{'text':'explode'} }
self.widgetDescr['shadow'] = {
'class':'NECheckButton', 'master':'node',
'initialValue':1, 'labelCfg':{'text':'shadow'}}
self.widgetDescr['format'] = {
'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'format:'},
'initialValue':'%1.1f%%'}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='patches')
op.append(datatype='None', name='texts')
op.append(datatype='None', name='autotextsline')
code = """def doit(self, fractions, labels, shadow, explode, format,
drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
if isinstance(explode, float) or isinstance(explode, int):
explode = [explode]*len(fractions)
res = self.axes.pie(fractions, explode=explode, labels=labels,
autopct=format, shadow=shadow)
if format is None:
patches, texts = res
autotextsline = None
else:
patches, texts, autotextsline = res
self.canvas.draw()
self.outputData(plot=self.axes, patches=patches, texts=texts, autotextsline=autotextsline)
"""
self.setFunction(code)
#Spy Nodes
class SpyNE(MPLPlottingNode):
"""Plots the sparsity pattern of the matrix Z using plot markers.
input:
Z - matrix
optional arguements:
marker - marker
markersize -markersize
The line handles are returned
"""
def __init__(self, name='Spy', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None',name = 'Z',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='marker', defaultValue='s')
ip.append(datatype='None', required=False, name='markersize', defaultValue=10)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['marker'] = {
'class':'NEComboBox', 'master':'node',
'choices':markers.values(),
'fixedChoices':True,
'initialValue':'s',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'markers:'}}
self.widgetDescr['markersize'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10, 'type':'float',
'initialValue':10.0, 'wheelPad':2,
'labelCfg':{'text':'size'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
code = """def doit(self, Z, marker, markersize, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
l=self.axes.spy(Z,marker=marker,markersize=markersize)
self.canvas.draw()
self.outputData(plot=self.axes)
"""
self.setFunction(code)
class Spy2NE(MPLPlottingNode):
"""SPY2 plots the sparsity pattern of the matrix Z as an image
input:
Z - matrix
The image instance is returned
"""
def __init__(self, name='Spy2', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None',name = 'Z',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='image')
code = """def doit(self, Z, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
im=self.axes.spy2(Z)
self.canvas.draw()
self.outputData(plot=self.axes,image=im)
"""
self.setFunction(code)
class VlineNE(MPLPlottingNode):
"""Plots vertical lines at each x from ymin to ymax. ymin or ymax can be
scalars or len(x) numpy arrays. If they are scalars, then the
respective values are constant, else the heights of the lines are
determined by ymin and ymax
x - array
ymin or ymax can be scalars or len(x) numpy arrays
color+marker - fmt is a plot format string, eg 'g--'
Returns a list of lines that were added
"""
def __init__(self, name='Vline', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list',name = 'x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',name = 'ymin',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list',name = 'ymax',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='color', defaultValue='k')
ip.append(datatype='string', required=False, name='linestyle', defaultValue='-')
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'node',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'k',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['linestyle'] = {
'class':'NEComboBox', 'master':'node',
'choices':['solid','dashed','dashdot','dotted'],
'fixedChoices':True,
'initialValue':'solid',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'linestyle:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='lines')
code = """def doit(self, x, ymin, ymax, color, linestyle, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
lines=self.axes.vlines(x, ymin, ymax, color=color, linestyle=linestyle )
self.canvas.draw()
self.outputData(plot=self.axes,lines=lines)
"""
self.setFunction(code)
#Scatter Nodes
from math import fabs
class ScatterNE(MPLPlottingNode):
"""plots a scatter diagram for two lists of numbers.
Input:
x - sequence of values
y - sequence of values
s - None; sequence of values for size in area
c - None, string or sequence of colors
marker - 'circle', marker
Output:
plot Matplotlib Axes object
patches - matplotlib.collections.RegularPolyCollection instance
"""
def getPointInBin(self, data, sortind, x, eps):
#dichotomous search for indices of values in data within x+-eps
if len(sortind)>2:
if data[sortind[0]]==x: return data, [sortind[0]]
elif data[sortind[-1]]==x: return data, [sortind[-1]]
elif len(sortind)==2: return data, sortind
else:
mid = len(sortind)/2
if fabs(data[sortind[mid]]-x)<eps:
if fabs(data[sortind[0]]-x)<eps:
return data, sortind[:mid]
elif fabs(data[sortind[-1]]-x)<eps:
return data, sortind[mid:]
if data[sortind[mid]]>x:
data, sortind = self.getPointInBin(data, sortind[:mid],
x, eps)
elif data[sortind[mid]]<x:
data, sortind = self.getPointInBin(data, sortind[mid:],
x, eps)
return data, sortind
def on_click(self, event):
# get the x and y pixel coords
if event.inaxes:
d1 = self.inputPorts[0].getData()
d2 = self.inputPorts[1].getData()
mini = min(d1)
maxi = max(d1)
epsx = (maxi-mini)/200.
import numpy
d1s = numpy.argsort(d1)
x, y = event.xdata, event.ydata
dum, v1 = self.getPointInBin(d1, d1s, x, epsx)
mini = min(d2)
maxi = max(d2)
epsy = (maxi-mini)/200.
result = []
for v in v1:
if fabs(x - d1[v])<epsx and fabs(y - d2[v])<epsy:
result.append(v)
#print v, x - d1[v], epsx, y - d2[v], epsy
if len(result):
print 'point:', result, x, d1[result[0]], y, d2[result[0]]
self.outputData(pick=result)
self.scheduleChildren([self.outputPorts[2]])
return result
else:
print "NO POINT"
return None
def afterAddingToNetwork(self):
MPLPlottingNode.afterAddingToNetwork(self)
self.figure.canvas.mpl_connect('button_press_event', self.on_click)
def __init__(self, name='Scatter', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.cutoff = 10.0
self.joinstyles = Line2D.validJoin
self.capstyles = Line2D.validCap
self.colors = colors
self.markers = markers
self.widgetDescr['s'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10, 'type':'float',
'initialValue':1.0, 'wheelPad':2,
'labelCfg':{'text':'size'} }
self.widgetDescr['c'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.colors.values(),
'fixedChoices':True,
'initialValue':'k',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['marker'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.markers.keys(),
'fixedChoices':True,
'initialValue':'circle',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'markers:'}}
self.widgetDescr['dash_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'butt',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash_capstyle:'}}
self.widgetDescr['dash_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash _joinstyle:'}}
self.widgetDescr['solid_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'projecting',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_capstyle:'}}
self.widgetDescr['solid_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_joinstyle:'}}
self.widgetDescr['linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['line_antialiased'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'antialiased:'},
'initialValue':1,}
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False, name='s')
ip.append(datatype='None', required=False, name='c', defaultValue='k')
ip.append(datatype='string', required=False, name='marker', defaultValue='circle')
ip.append(datatype='string', required=False, name='solid_joinstyle', defaultValue='miter')
ip.append(datatype='string', required=False, name='solid_capstyle', defaultValue='projecting')
ip.append(datatype='string', required=False, name='dash_capstyle', defaultValue='butt')
ip.append(datatype='string', required=False, name='dash_joinstyle', defaultValue='miter')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='patches')
op.append(datatype='int', name='pick')
code = """def doit(self, x, y, s, c, marker, solid_joinstyle,
solid_capstyle, dash_capstyle, dash_joinstyle, drawAreaDef):
kw={'solid_joinstyle':solid_joinstyle,'solid_capstyle':solid_capstyle,'dash_capstyle':dash_capstyle,'dash_joinstyle':dash_joinstyle}
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
if self.markers.has_key(marker):
marker = self.markers[marker]
res = self.axes.scatter( x, y, s, c, marker)
#collections properties
if self.axes.lines:
for c in self.axes.collections:
c.set_solid_joinstyle(solid_joinstyle)
c.set_solid_capstyle(solid_capstyle)
c.set_dash_capstyle(dash_capstyle)
c.set_dash_joinstyle(dash_joinstyle)
self.canvas.draw()
self.outputData(plot=self.axes, patches=res)
"""
self.setFunction(code)
class ScatterClassicNE(MPLPlottingNode):
"""plots a scatter diagram for two lists of numbers.
Input:
x - sequence of values
y - sequence of values
s - None; sequence of values for size in area
c - None, string or sequence of colors
Output:
plot Matplotlib Axes object
patches - matplotlib.collections.RegularPolyCollection instance
"""
def __init__(self, name='ScatterClassic', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
self.joinstyles = Line2D.validJoin
self.capstyles = Line2D.validCap
self.colors=colors
self.markers =markers
self.widgetDescr['s'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10, 'type':'float',
'initialValue':1.0, 'wheelPad':2,
'labelCfg':{'text':'size'} }
self.widgetDescr['c'] = {
'class':'NEComboBox', 'master':'node',
'choices':self.colors.values(),
'fixedChoices':True,
'initialValue':'k',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'we'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['dash_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'butt',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash_capstyle:'}}
self.widgetDescr['dash_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'dash _joinstyle:'}}
self.widgetDescr['solid_capstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.capstyles,
'fixedChoices':True,
'initialValue':'projecting',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_capstyle:'}}
self.widgetDescr['solid_joinstyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':self.joinstyles,
'fixedChoices':True,
'initialValue':'miter',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'solid_joinstyle:'}}
self.widgetDescr['linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':60, 'height':21, 'oneTurn':2, 'type':'int',
'wheelPad':2, 'initialValue':1,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['line_antialiased'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'antialiased:'},
'initialValue':1,}
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False, name='s')
ip.append(datatype='None', required=False, name='c')
ip.append(datatype='string', required=False, name='solid_joinstyle', defaultValue='miter')
ip.append(datatype='string', required=False, name='solid_capstyle', defaultValue='projecting')
ip.append(datatype='string', required=False, name='dash_capstyle', defaultValue='butt')
ip.append(datatype='string', required=False, name='dash_joinstyle', defaultValue='miter')
ip.append(datatype='MPLDrawArea', required=False,name='drawAreaDef',singleConnection=False)
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='patches')
code = """def doit(self, x, y, s, c, solid_joinstyle, solid_capstyle,
dash_capstyle, dash_joinstyle, drawAreaDef):
kw={'solid_joinstyle':solid_joinstyle,'solid_capstyle':solid_capstyle,'dash_capstyle':dash_capstyle,'dash_joinstyle':dash_joinstyle}
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
res = self.axes.scatter_classic( x, y, s, c)
#collections properties
if self.axes.lines:
for c in self.axes.collections:
c.set_solid_joinstyle(solid_joinstyle)
c.set_solid_capstyle(solid_capstyle)
c.set_dash_capstyle(dash_capstyle)
c.set_dash_joinstyle(dash_joinstyle)
self.canvas.draw()
self.outputData(plot=self.axes, patches=res)
"""
self.setFunction(code)
class FigImageNE(MPLPlottingNode):
"""plots an image from a 2d array fo data
Input:
data - 2D array of data
Output:
plot Matplotlib Axes object
image - image.FigureImage instance
"""
def __init__(self, name='Figimage', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='data',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False, name='cmap', defaultValue='jet')
ip.append(datatype='string',required=False, name='imaspect', defaultValue='equal')
ip.append(datatype='string',required=False, name='interpolation', defaultValue='bilinear')
ip.append(datatype='string',required=False, name='origin', defaultValue='upper')
ip.append(datatype='None', required=False, name='alpha', defaultValue=1.)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
imaspects=['auto', 'equal']
interpolations =['nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric','catrom', 'gaussian', 'bessel', 'mitchell', 'sinc','lanczos', 'blackman']
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['imaspect'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':imaspects,
'fixedChoices':True,
'initialValue':'equal',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'aspect:'}}
self.widgetDescr['interpolation'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':interpolations,
'fixedChoices':True,
'initialValue':'bilinear',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'interpolation:'}}
self.widgetDescr['origin'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['upper','lower',],
'fixedChoices':True,
'initialValue':'upper',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'origin:'}}
self.widgetDescr['alpha'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1, 'type':'float',
'initialValue':1.0, 'wheelPad':2,
'labelCfg':{'text':'alpha'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='plot')
op.append(datatype='None', name='image')
code = """def doit(self, data, cmap, imaspect, interpolation, origin,
alpha, drawAreaDef):
kw={'cmap':cmap,'imaspect':imaspect,'interpolation':interpolation,'origin':origin,'alpha':alpha}
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
self.setDrawArea(kw)
im = self.axes.imshow(data)
#image properties
cmp=cm.get_cmap(cmap)
im.set_cmap(cmp)
im.set_interpolation(interpolation)
im.set_alpha(alpha)
im.origin=origin
self.axes.set_aspect(imaspect)
self.canvas.draw()
self.outputData(plot=self.axes, image=im)
"""
self.setFunction(code)
#PSEUDO COLOR PLOTS
class PcolorMeshNE(MPLPlottingNode):
"""This class is for making a pseudocolor plot.
input:
arraylistx - array
arraylisty - array
arraylistz - may be a masked array
optional arguements:
cmap - cm.jet : a cm Colormap instance from matplotlib.cm.
defaults to cm.jet
shading - 'flat' : or 'faceted'. If 'faceted', a black grid is
drawn around each rectangle; if 'flat', edge colors are same as
face colors
alpha - blending value
PCOLORMESH(Z) - make a pseudocolor plot of matrix Z
PCOLORMESH(X, Y, Z) - a pseudo color plot of Z on the matrices X and Y
Return value is a matplotlib.collections.PatchCollection
object
"""
def __init__(self, name='PcolorMesh', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', required=False,name='arraylistx')
ip.append(datatype='None', required=False,name='arraylisty')
ip.append(datatype='None', name='arraylistz',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False, name='cmap', defaultValue='jet')
ip.append(datatype='string',required=False, name='shading', defaultValue='faceted')
ip.append(datatype='float',required=False, name='alpha', defaultValue=1.)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['shading'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['flat','faceted'],
'fixedChoices':True,
'initialValue':'faceted',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'shading:'}}
self.widgetDescr['alpha'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'initialValue':1.0, 'wheelPad':2,
'labelCfg':{'text':'alpha'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype='None', name='patches')
code = """def doit(self, x, y, z, cmap, shading, alpha, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
#pseudo color plot of Z
Qz=z
cmap = cm.get_cmap(cmap)
if x==None or y==None:
C=self.axes.pcolormesh(Qz,cmap=cmap,shading=shading,alpha=alpha)
else:
#a pseudo color plot of Z on the matrices X and Y
Qx,Qy=array(x),array(y)
C=self.axes.pcolormesh(Qx,Qy,Qz,cmap=cmap,shading=shading,alpha=alpha)
self.canvas.draw()
self.outputData(axes=self.axes,patches=C)
"""
self.setFunction(code)
class PcolorNE(MPLPlottingNode):
"""This class is for making a pseudocolor plot.
input:
arraylistx - may be a array
arraylisty - may be a array
arraylistz - may be a masked array
optional arguements:
cmap - cm.jet : a cm Colormap instance from matplotlib.cm.
defaults to cm.jet
shading - 'flat' : or 'faceted'. If 'faceted', a black grid is
drawn around each rectangle; if 'flat', edge colors are same as
face colors
alpha - blending value
PCOLOR(Z) - make a pseudocolor plot of matrix Z
PCOLOR(X, Y, Z) - a pseudo color plot of Z on the matrices X and Y
Return value is a matplotlib.collections.PatchCollection
object
"""
def __init__(self, name='Pcolor', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', required=False,name='arraylistx')
ip.append(datatype='None', required=False,name='arraylisty')
ip.append(datatype='None', name='arraylistz',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False, name='cmap', defaultValue='jet')
ip.append(datatype='string',required=False, name='shading', defaultValue='faceted')
ip.append(datatype='float',required=False, name='alpha', defaultValue=1.)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['shading'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['flat','faceted'],
'fixedChoices':True,
'initialValue':'faceted',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'shading:'}}
self.widgetDescr['alpha'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'initialValue':1.0, 'wheelPad':2,
'labelCfg':{'text':'alpha'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype='None', name='patches')
code = """def doit(self, x, y, z, cmap, shading, alpha, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
#pseudo color plot of Z
Qz=z
cmap = cm.get_cmap(cmap)
if x==None or y==None:
C=self.axes.pcolor(Qz,cmap=cmap,shading=shading,alpha=alpha)
else:
#a pseudo color plot of Z on the matrices X and Y
Qx,Qy=array(x),array(y)
C=self.axes.pcolor(Qx,Qy,Qz,cmap=cmap,shading=shading,alpha=alpha)
self.canvas.draw()
self.outputData(axes=self.axes,patches=C)
"""
self.setFunction(code)
class PcolorClassicNE(MPLPlottingNode):
"""This class is for making a pseudocolor plot.
input:
arraylistx - array
arraylisty - array
arraylistz - may be a masked array
optional arguements:
cmap - cm.jet : a cm Colormap instance from matplotlib.cm.
defaults to cm.jet
shading - 'flat' : or 'faceted'. If 'faceted', a black grid is
drawn around each rectangle; if 'flat', edge colors are same as
face colors
alpha - blending value
PCOLOR_CLASSIC(Z) - make a pseudocolor plot of matrix Z
PCOLOR_CLASSIC(X, Y, Z) - a pseudo color plot of Z on the matrices X and Y
Return value is a matplotlib.collections.PatchCollection
object
"""
def __init__(self, name='PcolorClassic', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', required=False,name='arraylistx')
ip.append(datatype='None', required=False,name='arraylisty')
ip.append(datatype='None', name='arraylistz',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False, name='cmap', defaultValue='jet')
ip.append(datatype='string',required=False, name='shading', defaultValue='faceted')
ip.append(datatype='float',required=False, name='alpha', defaultValue=.75)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['shading'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['flat','faceted'],
'fixedChoices':True,
'initialValue':'faceted',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'shading:'}}
self.widgetDescr['alpha'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'initialValue':0.75, 'wheelPad':2,
'labelCfg':{'text':'alpha'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype='None', name='patches')
code = """def doit(self, x, y, z, cmap, shading, alpha, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
#pseudo color plot of Z
Qz=z
cmap = cm.get_cmap(cmap)
if x==None or y==None:
C=self.axes.pcolor_classic(Qz,cmap=cmap,shading=shading,alpha=alpha)
else:
#a pseudo color plot of Z on the matrices X and Y
Qx,Qy=array(x),array(y)
C=self.axes.pcolor_classic(Qx,Qy,Qz,cmap=cmap,shading=shading,alpha=alpha)
self.canvas.draw()
self.outputData(axes=self.axes,patches=C)
"""
self.setFunction(code)
class ContourNE(MPLPlottingNode):
"""contour and contourf draw contour lines and filled contours.
input:
arraylistx :array
arraylisty :array
arraylistz :array
optional arguements:
length_colors : no of colors required to color contour
cmap :a cm Colormap instance from matplotlib.cm.
origin :'upper'|'lower'|'image'|None.
linewidth :linewidth
hold:
contour(Z) make a contour plot of n arrayZ
contour(X,Y,Z) X,Y specify the (x,y) coordinates of the surface
"""
def __init__(self, name='Contour', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', required=False, name='arraylistx')
ip.append(datatype='None', required=False,name='arraylisty')
ip.append(datatype='None', name='arraylistz',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string', required=False, name='contour', defaultValue='default')
ip.append(datatype='int', required=False, name='length_colors')
ip.append(datatype='string', required=False, name='cmap', defaultValue='jet')
ip.append(datatype='string', required=False, name='colors', defaultValue='black')
ip.append(datatype='string', required=False, name='origin', defaultValue='upper')
ip.append(datatype='int', required=False, name='linewidth', defaultValue=1)
ip.append(datatype='boolean', required=False, name='hold', defaultValue=0)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['contour'] = {
'class':'NEComboBox', 'master':'node',
'choices':['default','filledcontour'],
'fixedChoices':True,
'initialValue':'default',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'contour:'}}
self.widgetDescr['length_colors'] = {
'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'no. of colors:'},
'initialValue':10}
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['colors'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'black',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'colors:'}}
self.widgetDescr['linewidth'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':4, 'type':'int',
'initialValue':1, 'wheelPad':2,
'labelCfg':{'text':'linewidth'} }
self.widgetDescr['origin'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['upper','lower','image',None],
'fixedChoices':True,
'initialValue':'upper',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'origin:'}}
self.widgetDescr['hold'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'hold'},
'initialValue':0,}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype='None', name='contour')
code = """def doit(self, arraylistx, arraylisty, arraylistz, contour,
length_colors, cmapval, colors, origin, linewidth, hold, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
axes_list=self.axes.figure.axes
if len(axes_list):
for i in axes_list:
if not isinstance(i,Subplot):
self.axes.figure.delaxes(i)
import numpy
#Z=10.0*(numpy.array(z2) - numpy.array(z1))
Z=arraylistz
if length_colors:
cmap = cm.get_cmap(cmapval,int(length_colors))
else:
cmap=eval("cm.%s" %cmapval)
if arraylistx==None or arraylisty==None:
#contour plot of an array Z
if contour=='default':
CS=self.axes.contour(Z,cmap=cmap,linewidths=linewidth,origin=origin,hold=hold)
self.axes.clabel(CS,inline=1)
else:
CS=self.axes.contourf(numpy.array(Z),cmap=cmap,origin=origin)
else:
#(x,y) coordinates of the surface
X=numpy.array(arraylistx)
Y=numpy.array(arraylisty)
if contour=='default':
CS=self.axes.contour(X,Y,Z,cmap=cmap,linewidths=linewidth,origin=origin,hold=hold)
self.axes.clabel(CS,inline=1)
else:
CS=self.axes.contourf(X,Y,numpy.array(Z),cmap=cmap,origin=origin)
self.canvas.draw()
self.outputData(axes=self.axes,contour=CS)
"""
self.setFunction(code)
class SpecgramNE(MPLPlottingNode):
"""plots a spectrogram of data in arraylistx.
NFFT - Data are split into NFFT length segements
Fs - samplingFrequency
cmap - colormap
nOverlap- the amount of overlap of each segment.
Returns im
im is a matplotlib.image.AxesImage
"""
def __init__(self, name='Specgram', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='arraylistx',singleConnection='auto',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='int', name='NFFT', defaultValue=256)
ip.append(datatype='int', name='Fs', defaultValue=2)
ip.append(datatype='string', required=False, name='cmap')
ip.append(datatype='int', name='nOverlap', defaultValue=128)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['NFFT'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'NFFT (powOf 2):'},'width':10,
'type':'int',
'initialValue':256}
self.widgetDescr['Fs'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':2,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Fs'} }
self.widgetDescr['cmap'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cmaps,
'fixedChoices':True,
'initialValue':'jet',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'cmap:'}}
self.widgetDescr['nOverlap'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'nOverlap:'},'width':10,
'type':'int','labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype=None,name='image')
code="""def doit(self, x, NFFT, Fs, cmapval, nOverlap, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
cmap=eval("cm.%s" %cmapval)
Pxx, freqs, bins, im=self.axes.specgram(x, NFFT=int(NFFT), Fs=Fs,cmap=cmap,noverlap=int(nOverlap))
self.canvas.draw()
self.outputData(axes=self.axes,image=im)
"""
self.setFunction(code)
class CSDNE(MPLPlottingNode):
"""plots a cross spectral density of data in arraylistx,arraylisty.
NFFT - Data are split into NFFT length segements
Fs - samplingFrequency
nOverlap- the amount of overlap of each segment.
"""
def __init__(self, name='CSD', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype=None, name='arraylistx',singleConnection='auto',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype=None, name='arraylisty',singleConnection='auto',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='int', name='NFFT', defaultValue=256)
ip.append(datatype='int', name='Fs', defaultValue=2)
ip.append(datatype='int', name='nOverlap', defaultValue=128)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['NFFT'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'NFFT (powOf 2):'},'width':10,
'type':'int',
'initialValue':256}
self.widgetDescr['Fs'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':2,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Fs'} }
self.widgetDescr['nOverlap'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'nOverlap:'},'width':10,
'type':'int','labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, arraylistx, arraylisty, NFFT, Fs, nOverlap,
drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
Pxx, freqs=self.axes.csd(arraylistx,arraylisty, NFFT=int(NFFT), Fs=Fs,noverlap=int(nOverlap))
self.canvas.draw()
self.outputData(axes=self.axes)
"""
self.setFunction(code)
class PSDNE(MPLPlottingNode):
"""plots a cross spectral density of data in arraylistx.
NFFT - Data are split into NFFT length segements
Fs - samplingFrequency
nOverlap- the amount of overlap of each segment.
"""
def __init__(self, name='PSD', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype=None, name='arraylistx',singleConnection='auto',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='int', required=False,name='NFFT', defaultValue=256)
ip.append(datatype='int', required=False,name='Fs', defaultValue=2)
ip.append(datatype='int', required=False,name='nOverlap', defaultValue=0)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['NFFT'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'NFFT (powOf 2):'},'width':10,
'type':'int',
'initialValue':256}
self.widgetDescr['Fs'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':2,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Fs'}}
self.widgetDescr['nOverlap'] = {
'class':'NEEntry', 'master':'ParamPanel',
'labelCfg':{'text':'nOverlap:'},'width':10,
'type':'int','labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, x, NFFT, Fs, nOverlap, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
self.axes.psd(x,NFFT=int(NFFT), Fs=Fs,noverlap=int(nOverlap))
self.canvas.draw()
self.outputData(axes=self.axes)
"""
self.setFunction(code)
class LogCurveNE(MPLPlottingNode):
"""This node is to make a loglog plot with log scaling on the x and y axis.
input:
x - list
y - list
basex - base of the x logarithm
basey - base of the y logarithm
"""
def __init__(self, name='LogCurve', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='string',required=False, name='logCurve', defaultValue='log')
ip.append(datatype='float',required=False, name='basex', defaultValue=10)
ip.append(datatype='float',required=False, name='basey', defaultValue=10)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['logCurve'] = {
'class':'NEComboBox', 'master':'node',
'choices':['logbasex','logbasey'],
'fixedChoices':True,
'initialValue':'logbasex',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'logCurve:'}}
self.widgetDescr['basex'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':10,
'labelCfg':{'text':'basex'} }
self.widgetDescr['basey'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':10,
'labelCfg':{'text':'basey'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, x, y, logCurve, basex, basey, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
if logCurve=="logbasex":
log_curve=self.axes.loglog(x,y,basex=basex)
else:
log_curve=self.axes.loglog( x,y,basey=basey)
self.canvas.draw()
self.outputData(axes=self.axes)
"""
self.setFunction(code)
class SemilogxNE(MPLPlottingNode):
"""This node is to make a semilog plot with log scaling on the xaxis.
input:
x - list
basex - base of the x logarithm
"""
def __init__(self, name='Semilogx', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='float',required=False, name='basex', defaultValue=10)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['basex'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':10,
'labelCfg':{'text':'basex'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, x, y, basex, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
self.axes.semilogx(x,y,basex=basex)
self.canvas.draw()
self.outputData(axes=self.axes)
"""
self.setFunction(code)
class SemilogyNE(MPLPlottingNode):
"""This node is to make a semilog plot with log scaling on the y axis.
input:
y - list
basey - base of the y logarithm
"""
def __init__(self, name='Semilogy', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='float',required=False, name='basey', defaultValue=10)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['basey'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':10,
'labelCfg':{'text':'basey'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, x, y, basey, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
self.axes.semilogy(x,y,basey=basey)
self.canvas.draw()
self.outputData(axes=self.axes)
"""
self.setFunction(code)
class BoxPlotNE(MPLPlottingNode):
""" To plot a box and whisker plot for each column of x.
The box extends from the lower to upper quartile values
of the data, with a line at the median. The whiskers
extend from the box to show the range of the data. Flier
points are those past the end of the whiskers.
input:
x - Numeric array
optional arguements:
notch - notch = 0 (default) produces a rectangular box plot.
notch = 1 will produce a notched box plot
sym - (default 'b+') is the default symbol for flier points.
Enter an empty string ('') if you dont want to show fliers.
vert - vert = 1 (default) makes the boxes vertical.
vert = 0 makes horizontal boxes. This seems goofy, but
thats how Matlab did it.
whis - (default 1.5) defines the length of the whiskers as
a function of the inner quartile range. They extend to the
most extreme data point within ( whis*(75%-25%) ) data range.
positions- (default 1,2,...,n) sets the horizontal positions of
the boxes. The ticks and limits are automatically set to match
the positions.
widths - either a scalar or a vector and sets the width of
each box. The default is 0.5, or 0.15*(distance between extreme
positions) if that is smaller.
Returns a list of the lines added
"""
def __init__(self, name='BoxPlot', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list', name='x',singleConnection='auto',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='list', required=False, name='positions')
ip.append(datatype=None, required=False, name='widths', defaultValue=.15)
ip.append(datatype='boolean', required=False, name='notch', defaultValue=0)
ip.append(datatype='boolean', required=False, name='vert', defaultValue=0)
ip.append(datatype='string', required=False, name='color', defaultValue='b')
ip.append(datatype='string', required=False, name='linestyle', defaultValue='-')
ip.append(datatype='float', required=False, name='whis', defaultValue=1.5)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['notch'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'notch:'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0,}
self.widgetDescr['vert'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'vert:'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0,}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['linestyle'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':get_styles().values(),
'fixedChoices':True,
'initialValue':'-',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'linestyle:'}}
self.widgetDescr['whis'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':1.5,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'whis'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype=None, name='lines')
code="""def doit(self, x, positions, widths, notch, vert, color, linestyle,
whis, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
sym=color+linestyle
ll=self.axes.boxplot(x,notch=notch, sym=sym, vert=vert, whis=whis,positions=positions,widths=widths)
self.canvas.draw()
self.outputData(axes=self.axes,lines=ll) """
self.setFunction(code)
class BarNE(MPLPlottingNode):
"""Plots a horizontal bar plot with rectangles bounded by
left, left+width, bottom, bottom+height (left, right, bottom and top edges)
bottom, width, height, and left can be either scalars or sequences
input:
height - the heights (thicknesses) of the bars
left - the x coordinates of the left edges of the bars
Optional arguments:
bottom - can be either scalars or sequences
width - can be either scalars or sequences
color - specifies the colors of the bars
edgecolor - specifies the colors of the bar edges
xerr - if not None, will be used to generate errorbars
on the bar chart
yerr - if not None, will be used to generate errorbars
on the bar chart
ecolor - specifies the color of any errorbar
capsize - determines the length in points of the error bar caps
align - 'edge' | 'center'
'edge' aligns the horizontal bars by their bottom edges in bottom, while
'center' interprets these values as the y coordinates of the bar centers.
Return value is a list of Rectangle patch instances
"""
def __init__(self, name='Bar', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='left',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', name='height',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False,name='bottom', defaultValue=0)
ip.append(datatype='None', required=False,name='width', defaultValue=.8)
ip.append(datatype='None', required=False, name='xerr')
ip.append(datatype='None', required=False, name='yerr')
ip.append(datatype='string', required=False, name='color', defaultValue='b')
ip.append(datatype='string', required=False, name='edgecolor', defaultValue='b')
ip.append(datatype='string', required=False, name='ecolor', defaultValue='b')
ip.append(datatype='int', required=False, name='capsize', defaultValue=3)
ip.append(datatype='list', required=False, name='align', defaultValue='edge')
ip.append(datatype='list', required=False, name='orientation', defaultValue='vertical')
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['align'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['edge','center'],
'fixedChoices':True,
'initialValue':'edge',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'align:'}}
self.widgetDescr['orientation'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['vertical','horizontal'],
'fixedChoices':True,
'initialValue':'vertical',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'orientation:'}}
self.widgetDescr['edgecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'edgecolor:'}}
self.widgetDescr['ecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'ecolor:'}}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['capsize'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':3,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'capsize'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype=None, name='patches')
code="""def doit(self, left, height, bottom, width, xerr, yerr, color,
edgecolor, ecolor, capsize, align, orientation, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
patches=self.axes.bar(left,height,bottom=bottom, width=width,
color=color, edgecolor=edgecolor, xerr=xerr, yerr=yerr, ecolor=ecolor, capsize=capsize,
align=align,orientation=orientation)
self.canvas.draw()
self.outputData(axes=self.axes,patches=patches) """
self.setFunction(code)
class BarHNE(MPLPlottingNode):
"""Plots a horizontal bar plot with rectangles bounded by
left, left+width, bottom, bottom+height (left, right, bottom and top edges)
bottom, width, height, and left can be either scalars or sequences
input:
bottom - can be either scalars or sequences
width - can be either scalars or sequences
Optional arguments:
height - the heights (thicknesses) of the bars
left - the x coordinates of the left edges of the bars
color - specifies the colors of the bars
edgecolor - specifies the colors of the bar edges
xerr - if not None, will be used to generate errorbars
on the bar chart
yerr - if not None, will be used to generate errorbars
on the bar chart
ecolor - specifies the color of any errorbar
capsize - determines the length in points of the error bar caps
align - 'edge' | 'center'
'edge' aligns the horizontal bars by their bottom edges in bottom, while
'center' interprets these values as the y coordinates of the bar centers.
Return value is a list of Rectangle patch instances
"""
def __init__(self, name='BarH', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='bottom',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', name='width',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False, name='height', defaultValue=.8)
ip.append(datatype='None', required=False, name='left', defaultValue=0)
ip.append(datatype='None', required=False, name='xerr')
ip.append(datatype='None', required=False, name='yerr')
ip.append(datatype='string', required=False, name='color', defaultValue='b')
ip.append(datatype='string', required=False, name='edgecolor', defaultValue='b')
ip.append(datatype='string', required=False, name='ecolor', defaultValue='b')
ip.append(datatype='int', required=False, name='capsize', defaultValue=3)
ip.append(datatype='list', required=False, name='align', defaultValue='edge')
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['align'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['edge','center'],
'fixedChoices':True,
'initialValue':'edge',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'align:'}}
self.widgetDescr['edgecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'edgecolor:'}}
self.widgetDescr['ecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'ecolor:'}}
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['capsize'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':3,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'capsize'} }
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
op.append(datatype=None, name='patches')
code="""def doit(self, bottom, width, height, left, xerr, yerr, color,
edgecolor, ecolor, capsize, align, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
patches=self.axes.barh(bottom, width, height=height, left=left,
color=color, edgecolor=edgecolor, xerr=xerr, yerr=yerr, ecolor=ecolor, capsize=capsize,
align=align)
self.canvas.draw()
self.outputData(axes=self.axes,patches=patches) """
self.setFunction(code)
class QuiverNE(MPLPlottingNode):
"""Makes a vector plot (U, V) with arrows on a grid (X, Y)
If X and Y are not specified, U and V must be 2D arrays. Equally spaced
X and Y grids are then generated using the meshgrid command.
color -color
S -used to scale the vectors.Use S=0 to disable automatic scaling.
If S!=0, vectors are scaled to fit within the grid and then are multiplied by S.
pivot -'mid','tip' etc
units - 'inches','width','x','y'
width - a scalar that controls the width of the arrows
"""
def __init__(self, name='Quiver', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='u',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', name='v',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False,name='x')
ip.append(datatype='None', required=False,name='y')
ip.append(datatype='None', required=False, name='color')
ip.append(datatype='float', required=False, name='S', defaultValue=.2)
ip.append(datatype='float', required=False, name='width', defaultValue=1.)
ip.append(datatype='string', required=False, name='pivot', defaultValue='tip')
ip.append(datatype='string', required=False, name='units', defaultValue='inches')
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['color'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'color:'}}
self.widgetDescr['S'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1,
'type':'float','precision':3,
'wheelPad':2, 'initialValue':0.20,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'S'} }
self.widgetDescr['width'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1,
'type':'float','precision':3,
'wheelPad':2, 'initialValue':0.002,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'width'} }
self.widgetDescr['pivot'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['tip','mid'],
'fixedChoices':True,
'initialValue':'tip',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'pivot:'}}
self.widgetDescr['units'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['inches','width','x','y'],
'fixedChoices':True,
'initialValue':'units',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'units:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, u, v, x, y, color, S, width, pivot, units, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
if x!=None:
self.axes.quiver(x,y,u,v,S,pivot=pivot,color=color,width=width,units=units)
else:
self.axes.quiver(u,v,S,color=color,width=width,units=units)
self.canvas.draw()
self.outputData(axes=self.axes) """
self.setFunction(code)
class ErrorBarNE(MPLPlottingNode):
"""Plot x versus y with error deltas in yerr and xerr.
Vertical errorbars are plotted if yerr is not None
Horizontal errorbars are plotted if xerr is not None.
input:
x - scalar or sequence of vectors
y - scalar or sequence of vectors
xerr - scalar or sequence of vectors, plots a single error bar at x, y.,default is None
yerr - scalar or sequence of vectors, plots a single error bar at x, y.,default is None
optional arguements:
controlmarkers - controls errorbar markers(with props: markerfacecolor, markeredgecolor, markersize and
markeredgewith)
fmt - plot format symbol for y. if fmt is None, just
plot the errorbars with no line symbols. This can be useful
for creating a bar plot with errorbars
ecolor - a matplotlib color arg which gives the color the
errorbar lines; if None, use the marker color.
capsize - the size of the error bar caps in points
barsabove- if True, will plot the errorbars above the plot symbols
default is below
"""
def __init__(self, name='ErrorBar', **kw):
kw['name'] = name
apply( MPLPlottingNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='x',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', name='y',beforeDisconnect=self.codeBeforeDisconnect)
ip.append(datatype='None', required=False, name='xerr')
ip.append(datatype='None', required=False, name='yerr')
ip.append(datatype='string', required=False, name='format', defaultValue='b-')
ip.append(datatype='string', required=False, name='ecolor', defaultValue='b')
ip.append(datatype='int', required=False, name='capsize', defaultValue=3)
ip.append(datatype='boolean', required=False, name='barsabove', defaultValue=0)
ip.append(datatype='boolean', required=False, name='controlmarkers', defaultValue=0)
ip.append(datatype='MPLDrawArea', required=False, name='drawAreaDef',singleConnection=False)
self.widgetDescr['format'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':get_styles().values(),
'fixedChoices':True,
'initialValue':'-',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'format:'}}
self.widgetDescr['ecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':colors.values(),
'fixedChoices':True,
'initialValue':'b',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'ecolor:'}}
self.widgetDescr['capsize'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':1, 'type':'float',
'wheelPad':2, 'initialValue':3,'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'capsize'} }
self.widgetDescr['barsabove'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'barsabove:'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0,}
self.widgetDescr['controlmarkers'] = {
'class':'NECheckButton', 'master':'node',
'labelCfg':{'text':'barsabove:'},'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'initialValue':0,}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code="""def doit(self, x, y, xerr, yerr, format, ecolor, capsize,
barsabove, controlmarkers, drawAreaDef):
self.axes.clear()
self.setDrawAreaDef(drawAreaDef)
fmt=ecolor+format
if controlmarkers == 0:
self.axes.errorbar(x,y,xerr=xerr,yerr=yerr,fmt=fmt,ecolor=ecolor,capsize=capsize,barsabove=barsabove)
else:
def set_markerparams(dAD):
if dAD.has_key('marker'):
marker = dAD['marker']
else:
marker = 'solid'
if dAD.has_key('markerfacecolor'):
markerfacecolor = dAD['markerfacecolor']
else:
markerfacecolor = 'blue'
if dAD.has_key('markeredgecolor'):
markeredgecolor = dAD['markeredgecolor']
else:
markeredgecolor = 'blue'
if dAD.has_key('markersize'):
markersize = dAD['markersize']
else:
markersize = 6
if dAD.has_key('makeredgewidth'):
makeredgewidth = dAD['makeredgewidth']
else:
makeredgewidth = 0.5
return marker,markerfacecolor,markeredgecolor,markersize,makeredgewidth
if drawAreaDef:
markerdict={}
if len(drawAreaDef) == 1 and type(drawAreaDef[0])==types.DictType:
for d in drawAreaDef[0].keys():
if d[:6]=="marker":
markerdict[d]=drawAreaDef[0][d]
if len(drawAreaDef)>1:
for dAD in drawAreaDef:
if type(dAD) == types.DictType:
for d in dAD.keys():
if d[:6]=="marker":
markerdict[d]=dAD[d]
if markerdict!={}:
marker,markerfacecolor,markeredgecolor,markersize,makeredgewidth=set_markerparams(markerdict)
self.axes.errorbar(x, y, xerr=xerr,yerr=yerr, marker=marker,
mfc=markerfacecolor, mec=markeredgecolor, ms=markersize, mew=makeredgewidth)
self.canvas.draw()
self.outputData(axes=self.axes) """
self.setFunction(code)
###########################################################################
#
# Nodes generating data for demos
#
###########################################################################
class RandNormDist(NetworkNode):
"""
Outputs values describing a randomized normal distribution
Input:
mu -
sigma -
dpi - number of value points
Output:
data: list of values
mu -
sigma -
"""
def __init__(self, name='RandNormDist', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='float', name='mu')
ip.append(datatype='float', name='sigma')
ip.append(datatype='int', name='npts')
self.widgetDescr['mu'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':100,
'labelCfg':{'text':'mu'} }
self.widgetDescr['sigma'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':15,
'labelCfg':{'text':'sigma'} }
self.widgetDescr['npts'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':1000, 'type':'int',
'wheelPad':2, 'initialValue':10000,
'labelCfg':{'text':'nb. points'} }
op = self.outputPortsDescr
op.append(datatype='list', name='data')
op.append(datatype='float', name='mu')
op.append(datatype='float', name='sigma')
code = """def doit(self, mu, sigma, npts):
from numpy.oldnumeric.mlab import randn
self.outputData( data=mu+sigma*randn(npts), mu=mu, sigma=sigma )
"""
self.setFunction(code)
class SinFunc(NetworkNode):
"""
Outputs values describing a sinusoidal function.
Input:
start - first x value
end - last x value
step - step size
Output:
x: list x values
y = list of y values
"""
def __init__(self, name='SinFunc', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='float', name='x0')
ip.append(datatype='float', name='x1')
ip.append(datatype='float', name='step')
self.widgetDescr['x0'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10., 'type':'float',
'wheelPad':2, 'initialValue':0.,
'labelCfg':{'text':'x0'} }
self.widgetDescr['x1'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':10., 'type':'float',
'wheelPad':2, 'initialValue':3.,
'labelCfg':{'text':'x1'} }
self.widgetDescr['step'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10., 'type':'float',
'wheelPad':2, 'initialValue':0.01,
'labelCfg':{'text':'nb. points'} }
op = self.outputPortsDescr
op.append(datatype='list', name='x')
op.append(datatype='list', name='y')
code = """def doit(self, x0, x1, step):
import numpy
x = numpy.arange(x0, x1, step)
y = numpy.sin(2*numpy.pi*x)
self.outputData( x=x, y=y)
"""
self.setFunction(code)
class SinFuncSerie(NetworkNode):
"""
Outputs a list of y values of a sinusoidal function
Input:
Output:
x: list y values
"""
def __init__(self, name='SinFuncSerie', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
## ip = self.inputPortsDescr
## ip.append(datatype='float', name='x0')
## ip.append(datatype='float', name='x1')
## ip.append(datatype='float', name='step')
## self.widgetDescr['x0'] = {
## 'class':'NEThumbWheel','master':'node',
## 'width':75, 'height':21, 'oneTurn':10., 'type':'float',
## 'wheelPad':2, 'initialValue':0.,
## 'labelCfg':{'text':'x0'} }
## self.widgetDescr['x1'] = {
## 'class':'NEThumbWheel','master':'node',
## 'width':75, 'height':21, 'oneTurn':10., 'type':'float',
## 'wheelPad':2, 'initialValue':3.,
## 'labelCfg':{'text':'x1'} }
##
## self.widgetDescr['step'] = {
## 'class':'NEThumbWheel','master':'ParamPanel',
## 'width':75, 'height':21, 'oneTurn':10., 'type':'float',
## 'wheelPad':2, 'initialValue':0.01,
## 'labelCfg':{'text':'nb. points'} }
op = self.outputPortsDescr
op.append(datatype='list', name='X')
code = """def doit(self):
import numpy
ind = numpy.arange(60)
x_tmp=[]
for i in range(100):
x_tmp.append(numpy.sin((ind+i)*numpy.pi/15.0))
X=numpy.array(x_tmp)
self.outputData(X=X)
"""
self.setFunction(code)
class MatPlotLibOptions(NetworkNode):
"""This node allows to set various rendering Options.
Choose a category from,
Axes,Font,Figure,Text,Tick,Grid,Legend.
if "Grid" choosen,allows you to set following properties
gridOn/Off,gridlinewidth,gridlinestyle,gridcolor,whichgrid major/minor.
To ignore any property rightclick on property(sets to default value when
ignored)
"""
def __init__(self, name='Set Matplotlib Options', canvas=None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(name='matplotlibOptions', datatype='dict')
self.widgetDescr['matplotlibOptions'] = {
'class':'NEMatPlotLibOptions', 'lockedOnPort':True}
op = self.outputPortsDescr
op.append(datatype='dict', name='matplotlibOptions')
code = """def doit(self, matplotlibOptions):
self.outputData(matplotlibOptions=matplotlibOptions)
"""
self.setFunction(code)
class NEMatPlotLibOptions(PortWidget):
configOpts = PortWidget.configOpts.copy()
ownConfigOpts = {}
ownConfigOpts['initialValue'] = {
'defaultValue':{}, 'type':'dict',
}
configOpts.update(ownConfigOpts)
def __init__(self, port, **kw):
# call base class constructor
apply( PortWidget.__init__, (self, port), kw)
colors=cnames
self.styles=lineStyles
self.markers = markers
from DejaVu import viewerConst
self.main_props=['Axes','Font','Text','Figure','Tick','Grid','Legend']#,'MathText',
self.booleanProps =['axisbelow','gridOn','figpatch_antialiased','text.usetex','text.dvipnghack',
'hold','legend.isaxes','legend.shadow','mathtext.mathtext2']#visible
if mplversion[0]==0 and mplversion[2]<=3:
self.twProps=['linewidth','xtick.labelsize','xtick.labelrotation','ytick.labelsize',
'ytick.labelrotation','gridlinewidth','figpatch_linewidth','markeredgewidth',
#'zoomx','zoomy',
'legend.numpoints','legend.pad','legend.markerscale','legend.handlelen',
'legend.axespad','legend.labelsep','legend.handletextsep','xtick.major.size',
'ytick.major.size','xtick.minor.size','ytick.minor.size','xtick.major.pad',
'ytick.major.pad','xtick.minor.pad','ytick.minor.pad','font.size']
elif mplversion[0] > 0:
self.twProps=['linewidth','xtick.labelsize','xtick.labelrotation','ytick.labelsize',
'ytick.labelrotation','gridlinewidth','figpatch_linewidth','markeredgewidth',
#'zoomx','zoomy',
'legend.numpoints','legend.borderpad','legend.markerscale','legend.handlelength',
'legend.borderaxespad','legend.labelspacing','legend.handletextpad','xtick.major.size',
'ytick.major.size','xtick.minor.size','ytick.minor.size','xtick.major.pad',
'ytick.major.pad','xtick.minor.pad','ytick.minor.pad','font.size']
self.choiceProps ={'facecolor':tuple(colors.keys()),
'edgecolor':tuple(colors.keys()),
'gridcolor':tuple(colors.keys()),
'xtick.color':tuple(colors.keys()),
'ytick.color':tuple(colors.keys()),
'figpatch_facecolor':tuple(colors.keys()),
'figpatch_edgecolor':tuple(colors.keys()),
'marker':tuple(self.markers.values()),
'markeredgecolor':tuple(colors.keys()),
'markerfacecolor':tuple(colors.keys()),
'gridlinestyle':tuple(self.styles.keys()),
'adjustable':('box','datalim'),
'anchor':('C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'),
'aspect':('auto', 'equal' ,'normal',),
'text.color':tuple(colors.keys()),
'text.fontstyle':('normal',),
'text.fontvariant':('normal',),
'text.fontweight':('normal',),
'text.fontsize':('medium','small','large'),
'xtick.direction':('in','out'),
'ytick.direction':('in','out'),
'text.fontangle':('normal',),
'font.family':('serif',),
'font.style':('normal',),
'font.variant':('normal',),
'font.weight':('normal',),
'mathtext.rm':('cmr10.ttf',),
'mathtext.it':('cmmi10.ttf',),
'mathtext.tt':('cmtt10.ttf',),
'mathtext.mit':('cmmi10.ttf',),
'mathtext.cal':('cmsy10.ttf',),
'mathtext.nonascii' : ('cmex10.ttf',),
'legend.fontsize':('small','medium','large'),
'titlesize':('large','medium','small'),
'whichgrid':('minor','major')
}
self.frame = Tkinter.Frame(self.widgetFrame, borderwidth=3,
relief = 'ridge')
self.propWidgets = {} # will hold handle to widgets created
self.optionsDict = {} # widget's value
self.labels={}
self.delvar=0
self.new_list_to_add=[]
self.delete_proplist=[]
self.initialvalues={'font.family':'serif','font.style':'normal','font.variant':'normal',
'font.weight':'normal','font.size':12.0,'text.color':'black','text.usetex':False,
'text.dvipnghack':False,'text.fontstyle':'normal','text.fontangle':'normal',
'text.fontvariant':'normal','text.fontweight':'normal','text.fontsize':'medium',
'axisbelow':False,'hold':True,'facecolor':'white','edgecolor':'black','linewidth':1,
'titlesize':'large','gridOn':False,'legend.isaxes':True,'legend.numpoints':4,
'legend.fontsize':"small",'legend.markerscale':0.6,
#'legend.pad':0.2,'legend.labelsep':0.005, 'legend.handlelen':0.05,
#'legend.handletextsep':0.02, 'legend.axespad':0.02,
'legend.shadow':True,'xtick.major.size':5,'xtick.minor.size':2,
'xtick.major.pad':3,'xtick.minor.pad':3,'xtick.labelsize':10,'xtick.labelrotation':0,
'ytick.labelsize':10,'ytick.labelrotation':0, 'xtick.color':'black','xtick.direction':'in',
'ytick.major.size':5,'ytick.minor.size':2,'ytick.major.pad':3,'ytick.minor.pad':3,
'ytick.color':'black','ytick.direction':'in','gridcolor':'black','gridlinestyle':':',
'gridlinewidth':0.5,'whichgrid':'major','mathtext.mathtext2':False,'mathtext.rm': 'cmr10.ttf',
'mathtext.it':'cmmi10.ttf','mathtext.tt':'cmtt10.ttf','mathtext.mit':'cmmi10.ttf',
'mathtext.cal':'cmsy10.ttf','mathtext.nonascii' : 'cmex10.ttf','figpatch_linewidth':1.0,
'figpatch_facecolor':'darkgray','figpatch_edgecolor':'white','marker':'s','markeredgewidth':0.5,
'markeredgecolor':'black','markerfacecolor':'blue',
#'zoomx':0,'zoomy':0,
'adjustable':'box','aspect':'auto','anchor':'C','figpatch_antialiased':False}
if mplversion[0]==0 and mplversion[2]<=3:
self.initialvalues.update({'legend.pad':0.2, 'legend.labelsep':0.005, 'legend.handlelen':0.05, 'legend.handletextsep':0.02, 'legend.axespad':0.02})
elif mplversion[0]>0:
self.initialvalues.update({'legend.borderpad':0.2, 'legend.labelspacing':0.005, 'legend.handlelength':0.05, 'legend.handletextpad':0.02, 'legend.borderaxespad':0.02} )
import Pmw
#items = self.booleanProps +self.choiceProps.keys()+self.twProps
items=self.main_props
w = Pmw.Group(self.frame, tag_text='Choose a Category')
val=items[0]
cb=CallBackFunction(self.properties_list, (val,))
self.chooser = Pmw.ComboBox(
w.interior(), label_text='', labelpos='w',
entryfield_entry_width=20, scrolledlist_items=items,selectioncommand=cb)
self.chooser.pack(padx=2, pady=2, expand='yes', fill='both')
w.pack(fill = 'x', expand = 1, side='top')
# configure without rebuilding to avoid enless loop
apply( self.configure, (False,), kw)
self.frame.pack(expand='yes', fill='both')
w1 = Pmw.Group(self.frame, tag_text='choose a Property')
self.propWidgetMaster = w1.interior()
cb = CallBackFunction( self.mainChoices, (val,))
self.chooser1 = Pmw.ComboBox(w1.interior(), label_text='', labelpos='w',entryfield_entry_width=20, scrolledlist_items=self.new_list_to_add,selectioncommand=cb)
self.chooser1.pack(padx=2, pady=2, expand='yes', fill='both')
w1.pack(fill = 'x', expand = 1, side='top')
self.chooser1.grid(row=len(self.propWidgets), column=1, sticky='w')
if self.initialValue is not None:
self.set(self.initialValue, run=0)
self._setModified(False) # will be set to True by configure method
def properties_list(self,prop1,prop2):
prop=prop2
if prop=='Text':
list_to_add=['text.color','text.usetex','text.dvipnghack','text.fontstyle','text.fontangle','text.fontvariant','text.fontweight','text.fontsize']
elif prop=='Axes':
list_to_add=['axisbelow','hold','facecolor','edgecolor','linewidth','titlesize','marker','markeredgewidth','markeredgecolor','markerfacecolor',
#'zoomx','zoomy',
'adjustable','anchor','aspect']
elif prop=='Grid':
list_to_add=['gridOn','gridlinewidth','gridcolor','gridlinestyle','whichgrid']
elif prop=='Legend':
if mplversion[0]==0 and mplversion[2]<=3:
list_to_add=['legend.isaxes','legend.numpoints','legend.fontsize','legend.pad','legend.markerscale','legend.labelsep','legend.handlelen','legend.handletextsep','legend.axespad','legend.shadow']
elif mplversion[0] > 0:
list_to_add=['legend.isaxes','legend.numpoints','legend.fontsize','legend.borderpad','legend.markerscale','legend.labelspacing','legend.handlelength','legend.handletextpad','legend.borderaxespad','legend.shadow']
elif prop=="Tick":
list_to_add=['xtick.major.pad','ytick.major.pad','xtick.minor.pad','ytick.minor.pad','xtick.color','ytick.color','xtick.labelsize','ytick.labelsize','xtick.labelrotation','ytick.labelrotation']
#['xtick.major.size','ytick.major.size','xtick.minor.size','ytick.minor.size','xtick.major.pad','ytick.major.pad','xtick.minor.pad','ytick.minor.pad','xtick.color','ytick.color','xtick.size','ytick.size','xtick.direction','ytick.direction']
elif prop=="Font":
list_to_add=['font.family','font.style','font.variant','font.weight','font.size']
elif prop=="MathText":
list_to_add=['mathtext.mathtext2','mathtext.rm','mathtext.it','mathtext.tt','mathtext.mit', 'mathtext.cal','mathtext.nonascii' ,]
elif prop=="Figure":
list_to_add=['figpatch_antialiased','figpatch_linewidth','figpatch_edgecolor','figpatch_facecolor']
self.new_list_to_add=list_to_add
self.chooser1.setlist(self.new_list_to_add)
def mainChoices(self,prop,val):
self.addProp(val)
def deleteProp(self):
prop=self.property
widget= self.propWidgets[prop][0]
if prop in self.choiceProps:
widget.selectitem(self.initialvalues[prop])
widget.update_idletasks()
self.setChoice((prop,), self.initialvalues[prop])
if prop in self.booleanProps:
widget.deselect()
if prop in self.twProps:
widget.setValue(self.initialvalues[prop])
self.setTwValue(prop, self.initialvalues[prop])
self.scheduleNode()
widget.pack_forget()
widget.place_forget()
widget.grid_forget()
self.labels[prop].pack_forget()
self.labels[prop].place_forget()
self.labels[prop].grid_forget()
del self.propWidgets[prop]
del self.labels[prop]
def addProp(self, prop):
if self.propWidgets.has_key(prop):
return
labwidget = Tkinter.Label(self.propWidgetMaster, text=prop)
rown=self.propWidgetMaster.size()[1]
labwidget.grid(padx=2, pady=2, row=rown, column=0,
sticky='w')
self.labels[prop]=labwidget
#Right Click Menu
popup = Tkinter.Menu(labwidget, tearoff=0)
#popup.add_command(label="ToolTip")
#popup.add_separator()
popup.add_command(label="Ignore",command=self.deleteProp)
def do_popup(event):
# display the popup menu
self.property=labwidget['text']
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
popup.grab_release()
labwidget.bind("<Button-3>", do_popup)
if prop in self.booleanProps:
var = Tkinter.IntVar()
var.set(self.initialvalues[prop])
cb = CallBackFunction( self.setBoolean, (prop, var))
widget = Tkinter.Checkbutton(self.propWidgetMaster,
variable=var, command=cb)
if prop not in self.propWidgets:
self.propWidgets[prop] = (widget, var.get())
self.setBoolean( (prop, var) )
elif prop in self.choiceProps:
items = self.choiceProps[prop]
var = None
cb = CallBackFunction( self.setChoice, (prop,))
widget = Pmw.ComboBox(
self.propWidgetMaster,
entryfield_entry_width=10,
scrolledlist_items=items, selectioncommand=cb)
if prop not in self.propWidgets:
self.propWidgets[prop] = (widget, var)
self.setChoice( (prop,), self.initialvalues[prop] )
elif prop in self.twProps:
cb = CallBackFunction( self.setTwValue,prop)
val=self.initialvalues[prop]
self.twwidget=widget =ThumbWheel(width=75, height=21,wheelPad=2,master=self.propWidgetMaster,labcfg={'fg':'black', 'side':'left', 'text':prop},min = 0.0,type='float',showlabel =1,continuous =0,oneTurn =10,value=val,callback=cb)
if prop not in self.propWidgets:
self.propWidgets[prop] = (widget,val)
widget.grid(row=rown, column=1, sticky='w')
def setTwValue(self,prop,val):
self.optionsDict[prop] = val
if self.port.node.paramPanel.immediateTk.get():
self.scheduleNode()
def setBoolean(self,args):
prop, val = args
#if type(val)==types.InstanceType:
from mglutil.util.misc import isInstance
if isInstance(val) is True:
self.optionsDict[prop] = val.get()
else:
self.optionsDict[prop] = val
if self.optionsDict[prop]==1:
self.propWidgets[prop][0].select()
else:
self.propWidgets[prop][0].deselect()
if self.port.node.paramPanel.immediateTk.get():
self.scheduleNode()
def setChoice(self, prop, value):
self.optionsDict[prop[0]] = value
self.propWidgets[prop[0]][0].selectitem(value)
if self.port.node.paramPanel.immediateTk.get():
self.scheduleNode()
def set(self, valueDict, run=1):
self._setModified(True)
for k,v in valueDict.items():
self.addProp(k)
if k in self.booleanProps:
self.setBoolean( (k, v) )
elif k in self.choiceProps:
self.setChoice((k,), v)
else:
self.setTwValue(k, v)
self._newdata = True
if run:
self.scheduleNode()
def get(self):
return self.optionsDict
def configure(self, rebuild=True, **kw):
action, rebuildDescr = apply( PortWidget.configure, (self, 0), kw)
# this methods just creates a resize action if width changes
if self.widget is not None:
if 'width' in kw:
action = 'resize'
if action=='rebuild' and rebuild:
action, rebuildDescr = self.rebuild(rebuildDescr)
if action=='resize' and rebuild:
self.port.node.autoResize()
return action, rebuildDescr
class LegendNE(NetworkNode):
"""This nodes takes two lists of values and plots the the second against the first.
Input:
labels - sequence of strings
loc - 'best' : 0,
'upper right' : 1, (default)
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
If none of these are suitable, loc can be a 2-tuple giving x,y in axes coords, ie,
loc = 0, 1 is left top
loc = 0.5, 0.5 is center, center
lines - sequence of lines
Output:
legend Matplotlib Axes object
"""
def __init__(self, name='Legend', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw)
codeBeforeDisconnect = """def beforeDisconnect(self, c):
node1 = c.port1.node
node2 = c.port2.node
node1.figure.delaxes(node1.axes)
node1.figure.add_axes(node1.axes)
"""
ip = self.inputPortsDescr
ip.append(datatype='list',required=True, name='label')
ip.append(datatype='string',required=False, name='location', defaultValue='upper right')
self.widgetDescr['label'] = {
'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'Label:'},
'initialValue':''}
self.widgetDescr['location'] = {
'class':'NEComboBox', 'master':'node',
'choices':locations.keys(),
'fixedChoices':True,
'initialValue':'upper right',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Location:'}}
op = self.outputPortsDescr
op.append(datatype='MPLDrawArea', name='drawAreaDef')
code = """def doit(self, label, location):
kw={ 'legendlabel':label,'legendlocation':location}
self.outputData(drawAreaDef=kw) """
self.setFunction(code)
class ColorBarNE(NetworkNode):
"""Class for drawing color bar
input :
plot - axes instance
current_image -image instance
extend - both,neither,min or max.If not 'neither', make pointed end(s) for
out-of-range values. These are set for a given colormap using the
colormap set_under and set_over methods.
orientation - horizontal or vertical
spacing -uniform or proportional.Uniform spacing gives each discrete color the same space;proportional makes the space proportional to the data interval.
shrink -fraction by which to shrink the colorbar
"""
def __init__(self, name='ColorBar', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MPLAxes', required=True, name='plot')
ip.append(datatype='None', required=True, name='current_image')
ip.append(datatype='string', required=False, name='extend', defaultValue='neither')
ip.append(datatype='float', required=False, name='orientation', defaultValue='vertical')
ip.append(datatype='string', required=False, name='spacing', defaultValue='uniform')
ip.append(datatype='float', required=False, name='shrink', defaultValue=1.)
self.widgetDescr['shrink'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':1.0,'min':0.0,'max':1.0,
'labelCfg':{'text':'shrink'} }
self.widgetDescr['extend'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['both','neither','min','max'],
'fixedChoices':True,
'initialValue':'neither',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'extend:'}}
self.widgetDescr['orientation'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['vertical','horizontal'],
'fixedChoices':True,
'initialValue':'vertical',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'orientation:'}}
self.widgetDescr['spacing'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['uniform',' proportional'],
'fixedChoices':True,
'initialValue':'uniform',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'spacing:'}}
op = self.outputPortsDescr
op.append(datatype='MPLAxes', name='axes')
code = """def doit(self, plot, current_image, extend, orientation, spacing, shrink):
axes_list=plot.figure.axes
if len(axes_list):
pos=plot.figure.axes[0].get_position()
for i in axes_list:
if not isinstance(i,Subplot):
plot.figure.delaxes(i)
if current_image!=None:
pl=plot.figure.colorbar(current_image,cmap=current_image.cmap,shrink=shrink,extend=extend,orientation=orientation,spacing=spacing,filled=True)
if orientation=="vertical":
plot.figure.axes[0].set_position([0.125, 0.1, 0.62, 0.8])
if shrink>=1.0:
pl.ax.set_position([0.785, 0.1, 0.03, 0.8])
else:
pl.ax.set_position([0.785,pl.ax.get_position()[1],0.03,pl.ax.get_position()[-1]])
else:
plot.figure.axes[0].set_position([0.125, 0.34, 0.62, 0.56])
if shrink>=1.0:
pl.ax.set_position([0.125, 0.18, 0.62, 0.04])
else:
pl.ax.set_position([pl.ax.get_position()[0],0.18,pl.ax.get_position()[2],0.04])
plot.figure.canvas.draw()
else:
plot.figure.canvas.delete(pl)
self.outputData(axes=pl)
"""
self.setFunction(code)
class Text(NetworkNode):
"""Class for writting text in the axes
posx: x coordinate
posy: y coordinate
textlabel: label name
rotation: angle to be rotated
horizontal alignment: ['center', 'right', 'left']
vertical alignment: ['center', 'right', 'left']
"""
def __init__(self, name='Text', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='float', required=False, name='posx', defaultValue=.1)
ip.append(datatype='float', required=False, name='posy', defaultValue=.1)
ip.append(datatype='string', required=False, name='textlabel', defaultValue='')
ip.append(datatype='string', required=False, name='rotation', defaultValue=0)
ip.append(datatype='string', required=False, name='horizontalalignment', defaultValue='center')
ip.append(datatype='string', required=False, name='verticalalignment', defaultValue='center')
self.widgetDescr['posx'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'wheelPad':2, 'initialValue':0.1,
'labelCfg':{'text':'posx'} }
self.widgetDescr['posy'] = {
'class':'NEThumbWheel','master':'node',
'width':75, 'height':21, 'oneTurn':1., 'type':'float',
'wheelPad':2, 'initialValue':0.1,
'labelCfg':{'text':'posy'} }
self.widgetDescr['textlabel'] = {
'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'text'},
'initialValue':''}
self.widgetDescr['rotation'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':75, 'height':21, 'oneTurn':10, 'type':'float',
'wheelPad':2, 'initialValue':0,
'labelCfg':{'text':'rotation'} }
self.widgetDescr['horizontalalignment'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['center', 'right', 'left'],
'fixedChoices':True,
'initialValue':'center',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'horizontalalignment:'}}
self.widgetDescr['verticalalignment'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['top', 'bottom', 'center'],
'fixedChoices':True,
'initialValue':'center',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'verticalalignment:'}}
op = self.outputPortsDescr
op.append(datatype='MPLDrawArea', name='drawAreaDef')
code = """def doit(self, posx, posy, textlabel, rotation, horizontalalignment, verticalalignment):
kw = {'posx':posx, 'posy':posy, 'textlabel':textlabel, 'horizontalalignment':horizontalalignment, 'verticalalignment':verticalalignment,'rotation':rotation}
self.outputData(drawAreaDef=kw)
"""
self.setFunction(code)
class SaveFig(NetworkNode):
"""Save the current figure.
fname - the filename to save the current figure to. The
output formats supported depend on the backend being
used. and are deduced by the extension to fname.
Possibilities are eps, jpeg, pdf, png, ps, svg. fname
can also be a file or file-like object - cairo backend
only. dpi - is the resolution in dots per inch. If
None it will default to the value savefig.dpi in the
matplotlibrc file
facecolor and edgecolor are the colors of the figure rectangle
orientation - either 'landscape' or 'portrait'
papertype - is one of 'letter', 'legal', 'executive', 'ledger', 'a0' through
'a10', or 'b0' through 'b10' - only supported for postscript output
format - one of 'pdf', 'png', 'ps', 'svg'. It is used to specify the
output when fname is a file or file-like object - cairo
backend only.
"""
def __init__(self, name='saveFig', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='MPLFigure', required=False, name='figure')
ip.append(datatype=None, required=False, name='fname')
ip.append(datatype=None, required=False, name='dpi', defaultValue=80)
ip.append(datatype=None, required=False, name='facecolor', defaultValue='w')
ip.append(datatype=None, required=False, name='edgecolor', defaultValue='w')
ip.append(datatype=None, required=False, name='orientation', defaultValue='portrait')
ip.append(datatype=None, required=False, name='papertype')
ip.append(datatype=None, required=False, name='format')
self.widgetDescr['fname'] = {
'class':'NEEntry', 'master':'node',
'labelCfg':{'text': 'filename:'},
'initialValue':''}
self.widgetDescr['dpi'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'int',
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':80,
'labelCfg':{'text':'dpi'} }
self.widgetDescr['facecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'w',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'facecolor:'}}
self.widgetDescr['edgecolor'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':cnames.keys(),
'fixedChoices':True,
'initialValue':'w',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'edgecolor:'}}
self.widgetDescr['orientation'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['landscape','portrait'],
'fixedChoices':True,
'initialValue':'portrait',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'orientation:'}}
self.widgetDescr['papertype'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['letter', 'legal', 'executive', 'ledger','a0','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','b0','b1','b2','b3','b4','b5','b6','b7','b8','b9','b10',None],
'fixedChoices':True,
'initialValue':'None',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'papertype:'}}
self.widgetDescr['format'] = {
'class':'NEComboBox', 'master':'ParamPanel',
'choices':['pdf', 'png', 'ps', 'svg',None],
'fixedChoices':True,
'initialValue':'None',
'entryfield_entry_width':7,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'format:'}}
code = """def doit(self, figure, fname, dpi, facecolor, edgecolor,
orientation, papertype, format):
if figure:
figure.savefig(fname,dpi=dpi,facecolor=facecolor,edgecolor=edgecolor,orientation=orientation,papertype=papertype,format=format)
"""
self.setFunction(code)
class MeshGrid(NetworkNode):
"""This class converts vectors x, y with lengths Nx=len(x) and Ny=len(y) to X, Y and returns them.
where X and Y are (Ny, Nx) shaped arrays with the elements of x
and y repeated to fill the matrix
"""
def __init__(self, name='MeshGrid', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='list',required=False, name='x')
ip.append(datatype='list',required=False, name='y')
op = self.outputPortsDescr
op.append(datatype='None', name='X')
op.append(datatype='None', name='Y')
code = """def doit(self,x,y):
X,Y=meshgrid(x, y)
self.outputData(X=X,Y=Y)
"""
self.setFunction(code)
class BivariateNormal(NetworkNode):
"""Bivariate gaussan distribution for equal shape X, Y"""
def __init__(self, name='BivariateNormal', **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
ip = self.inputPortsDescr
ip.append(datatype='None', name='arraylist1')
ip.append(datatype='None', name='arraylist2')
ip.append(datatype='float', required=False, name='sigmax', defaultValue=1.)
ip.append(datatype='float', required=False, name='sigmay', defaultValue=1.)
ip.append(datatype='float', required=False, name='mux', defaultValue=0.)
ip.append(datatype='float', required=False, name='muy', defaultValue=0.)
ip.append(datatype='float', required=False, name='sigmaxy', defaultValue=0.)
self.widgetDescr['sigmax'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'wheelPad':2, 'initialValue':1.0,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'sigmax'} }
self.widgetDescr['sigmay'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':1.0,
'labelCfg':{'text':'sigmay'} }
self.widgetDescr['mux'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.0,
'labelCfg':{'text':'mux'} }
self.widgetDescr['muy'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.0,
'labelCfg':{'text':'muy'} }
self.widgetDescr['sigmaxy'] = {
'class':'NEThumbWheel','master':'ParamPanel',
'width':61, 'height':21, 'oneTurn':2, 'type':'float',
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w'},
'wheelPad':2, 'initialValue':0.0,
'labelCfg':{'text':'sigmaxy'} }
op = self.outputPortsDescr
op.append(datatype=None, name='z')
code = """def doit(self, x, y, sigmax, sigmay, mux, muy, sigmaxy):
import numpy
X=numpy.array(x)
Y=numpy.array(y)
z=bivariate_normal( X, Y, sigmax=sigmax, sigmay=sigmay, mux=mux, muy=muy, sigmaxy=sigmaxy)
self.outputData(z=z)
"""
self.setFunction(code)
###########################################################################
#
# Create and populate library
#
###########################################################################
from Vision.VPE import NodeLibrary
matplotliblib = NodeLibrary('MatPlotLib', '#99AFD8')
matplotliblib.addNode(MPLFigureNE, 'Figure', 'Input')
matplotliblib.addNode(MPLImageNE, 'ImageFigure', 'Input')
matplotliblib.addNode(MPLDrawAreaNE, 'Draw Area', 'Input')
matplotliblib.addNode(MultiPlotNE, 'MultiPlot', 'Misc')
matplotliblib.addNode(MPLMergeTextNE, 'MergeText', 'Input')
matplotliblib.addNode(ColorBarNE, 'ColorBar', 'Misc')
matplotliblib.addNode(Text, 'Text', 'Input')
matplotliblib.addNode(PolarAxesNE, 'PolarAxes', 'Plotting')
matplotliblib.addNode(HistogramNE, 'Histogram', 'Plotting')
matplotliblib.addNode(PlotNE, 'Plot', 'Plotting')
matplotliblib.addNode(PlotDateNE, 'PlotDate', 'Plotting')
matplotliblib.addNode(PieNE, 'Pie', 'Plotting')
matplotliblib.addNode(SpyNE, 'Spy', 'Plotting')
#matplotliblib.addNode(Spy2NE, 'Spy2', 'Plotting')
matplotliblib.addNode(VlineNE, 'Vline', 'Plotting')
matplotliblib.addNode(ScatterNE, 'Scatter', 'Plotting')
#matplotliblib.addNode(ScatterClassicNE, 'ScatterClassic', 'Plotting')
matplotliblib.addNode(FigImageNE, 'Figimage', 'Plotting')
matplotliblib.addNode(FillNE, 'Fill', 'Plotting')
matplotliblib.addNode(ContourNE, 'Contour', 'Plotting')
matplotliblib.addNode(PcolorMeshNE,'PcolorMesh', 'Plotting')
matplotliblib.addNode(PcolorNE,'Pcolor', 'Plotting')
#matplotliblib.addNode(PcolorClassicNE,'PcolorClassic', 'Plotting')
matplotliblib.addNode(RandNormDist, 'RandNormDist', 'Demo')
matplotliblib.addNode(SinFunc, 'SinFunc', 'Demo')
matplotliblib.addNode(SinFuncSerie, 'SinFuncSerie', 'Demo')
matplotliblib.addNode(MatPlotLibOptions, 'Set Matplotlib options', 'Input')
matplotliblib.addNode(LegendNE, 'Legend', 'Input')
matplotliblib.addNode(TablePlotNE, 'TablePlot', 'Plotting')
matplotliblib.addNode(SpecgramNE, 'Specgram', 'Plotting')
matplotliblib.addNode(CSDNE, 'CSD', 'Plotting')
matplotliblib.addNode(PSDNE, 'PSD', 'Plotting')
matplotliblib.addNode(LogCurveNE, 'LogCurve', 'Plotting')
matplotliblib.addNode(SemilogxNE, 'Semilogx', 'Plotting')
matplotliblib.addNode(SemilogyNE, 'Semilogy', 'Plotting')
matplotliblib.addNode(BoxPlotNE, 'BoxPlot', 'Plotting')
matplotliblib.addNode(ErrorBarNE, 'ErrorBar', 'Plotting')
matplotliblib.addNode(BarHNE, 'BarH', 'Plotting')
matplotliblib.addNode(BarNE, 'Bar', 'Plotting')
matplotliblib.addNode(QuiverNE, 'Quiver', 'Plotting')
matplotliblib.addNode(StemNE,'Stem','Plotting')
matplotliblib.addNode(BivariateNormal,'BivariateNormal','Demo')
matplotliblib.addNode(MeshGrid,'MeshGrid','Demo')
matplotliblib.addNode(SaveFig,'SaveFig','Misc')
matplotliblib.addWidget(NEMatPlotLibOptions)
###########################################################################
#
# Library specific data types
#
###########################################################################
UserLibBuild.addTypes(matplotliblib, 'Vision.matplotlibTypes')
try:
UserLibBuild.addTypes(matplotliblib, 'Vision.PILTypes')
except:
pass
```
#### File: Volume/Operators/MapData.py
```python
import numpy.oldnumeric as Numeric , struct
from time import time
from math import log
def isPowerOf2(num):
if num == 1:
power = 0
return 1, power
result = 1
ntemp = num
power = 0
while ntemp > 1:
if ntemp % 2 != 0: result = 0
ntemp = ntemp/2
power = power + 1
if result == 1:
return 1, power
power = power + 1
return 0, power
class MapGridData:
"""An instance of this class can be used to:
- change the data type in a Numeric array
- map the data to a new range of values using a linear or log mapping. This
operation can be performed in place or create a new array
- pad the array to have dimensions that are powers of 2
"""
def __call__(self, data, datatype=None, datamap=None, powerOf2=False,
fillValue=0.0):
""" Map(data, datamap=None, datatype=None, powerOf2=False)
data -- 3D array, source.
datatype -- The Numeric data type to be used for the destination array
datamap -- Dictionary that defines the following keys:
src_min, src_max: range of values in the source map. None
for these values will use the full range
dst_min, dst_max: range of values in the destination map
map_type: type of mapping. Can be 'linear' or 'log'.
powerOf2 -- if set to 1, then if the data array dimensions are not
power of 2 - the returned array will be padded with zeros
so that its dims are power of 2.
"""
#if no mapping is required:
if datamap is None:
if datatype:
if isinstance(data, Numeric.ArrayType):
if data.dtype.char!=datatype: # do the type conversion
data = data.astype(datatype)
else:
data = Numeric.array( data, datatype )
if not datatype:
if isinstance(data, Numeric.ArrayType):
datatype = data.dtype.char
nx, ny, nz = data.shape
# map data to range
if datamap is not None:
src_min = datamap['src_min']
src_max = datamap['src_max']
dst_min = datamap['dst_min']
dst_max = datamap['dst_max']
mtype = datamap['map_type']
#nx, ny, nz = data.shape
arrsize = nx*ny*nz
#arr_max = Numeric.maximum.reduce(data.ravel())
#arr_min = Numeric.minimum.reduce(data.ravel())
maxif = Numeric.maximum.reduce
arr_max = maxif(maxif(maxif(data)))
minif = Numeric.minimum.reduce
arr_min = minif(minif(minif(data)))
# check src_min
if src_min is not None:
assert src_min >= arr_min and src_min < arr_max, \
"%f>=%f and %f<=%f failed"%(src_min, arr_min, src_min,
arr_max)
if src_max is not None:
assert src_min < src_max
else:
src_min = arr_min
# check src_max
if src_max is not None:
#assert src_max >= arr_min and src_max < arr_max
assert src_max >= arr_min and src_max <= arr_max, \
"%f>=%f and %f<=%f failed"%(src_max, arr_min, src_max,
arr_max)
if src_min is not None:
assert src_min < src_max
else:
src_max = arr_max
# check
assert dst_min < dst_max
#print type(src_min), type(src_max), type(dst_min), type(dst_max)
#print "mapping data range %g -- %g to %g -- %g "%(src_min, src_max,
# dst_min, dst_max)
if mtype == 'linear':
data = self.linearMap( data, src_min, src_max, dst_min,dst_max,
arr_min, arr_max, datatype)
elif mtype == 'log':
data = self.logMap( data, src_min, src_max, dst_min, dst_max,
arr_min, arr_max, datatype)
# pad to make dimensions powers of 2
if powerOf2:
nx1, ny1, nz1 = data.shape
res, power = isPowerOf2(nx1)
if not res:
nx1 = 2**power
res, power = isPowerOf2(ny1)
if not res:
ny1 = 2**power
res, power = isPowerOf2(nz1)
if not res:
nz1 = 2**power
dx, dy, dz = 0, 0, 0
if nx1 != nx or ny1 != ny or nz1 != nz:
narr = (Numeric.ones( (nx1,ny1,nz1) )*fillValue).astype(datatype)
narr[:nx, :ny,:nz] = data
data = narr
## if nx1 != nx or ny1 != ny or nz1 != nz:
## dx = (nx1-nx)
## dy = (ny1-ny)
## dz = (nz1-nz)
## #narr = Numeric.zeros( (nx1,ny1,nz1), data.dtype.char)
## narr = Numeric.zeros( (nx1,ny1,nz1), datatype)
## # copy original data
## narr[:nx,:ny,:nz] = data[:,:,:]
## # duplicate last face in 3 directions
## for i in xrange(nx, nx1):
## narr[i,:ny,:nz] = data[-1,:,:]
## for i in xrange(ny, ny1):
## narr[:nx,i,:nz] = data[:,-1,:]
## for i in xrange(nz, nz1):
## narr[:nx,:ny,i] = data[:,:,-1]
## # duplicate edge values
## for i in xrange(nx):
## carr = Numeric.ones( (dy, dz) )*data[i, -1, -1]
## #narr[i, ny:, nz:] = carr[:,:].astype(data.dtype.char)
## narr[i, ny:, nz:] = carr[:,:].astype(datatype)
## for i in xrange(ny):
## carr = Numeric.ones( (dx, dz) )*data[-1, i, -1]
## #narr[nx:, i, nz:] = carr[:,:].astype(data.dtype.char)
## narr[nx:, i, nz:] = carr[:,:].astype(datatype)
## for i in xrange(nz):
## carr = Numeric.ones( (dx, dy) )*data[-1, -1, i]
## #narr[nx:, ny:, i] = carr[:,:].astype(data.dtype.char)
## narr[nx:, ny:, i] = carr[:,:].astype(datatype)
## # duplicate far corner arr[-1, -1, -1] in narr[nx:, ny:, nz:]
## carr = Numeric.ones( (dx, dy, dz) )*data[-1, -1, -1]
## #narr[nx:, ny:, nz:] = carr[:,:,:].astype(data.dtype.char)
## narr[nx:, ny:, nz:] = carr[:,:,:].astype(datatype)
## data = narr
return data
def linearMap(self, data, data_min, data_max, val_min, val_max,
arr_min, arr_max, datatype):
k2,c2 = self.ScaleMap((val_min, val_max), (data_min, data_max))
if k2 == 1 and c2 == 0:
return data
new_arr = Numeric.clip(k2*data+c2, k2*data_min+c2, k2*data_max+c2)
#return new_arr.astype(data.dtype.char)
return new_arr.astype(datatype)
def logMap(self, data, data_min, data_max, val_min, val_max,
arr_min, arr_max, datatype):
if arr_min < 0:
diff = abs(arr_min)+1.0
elif arr_min >= 0 and arr_min < 1.0:
diff = 1.0
elif arr_min >= 1.0:
diff=0
k1, c1 = self.ScaleMap( (val_min, val_max),
(log(arr_min+diff), log(arr_max+diff)) )
return (k1*Numeric.log10(data+diff)+c1).astype(datatype)
def ScaleMap(self, val_limit, data_limit, par=1):
""" Computes coefficients for linear mapping"""
assert data_limit[1]-data_limit[0]
k = float (val_limit[1]-val_limit[0])
k = k / (data_limit[1]**par-data_limit[0]**par)
c = val_limit[1]-k*data_limit[1]**par
return (k,c)
class MapData :
""" Class for mapping a numeric array of floats to an array of integers.
A special case where the user can define three mapping intervals for
the source data array and for the resulting integer array.
If mapping intervals are specified by supplying data min and max values
(other than global data minimum and maximum values) and scalar Val_min and
val_max (in range int_min ... int_limit), then the mapping will proceed as follows:
[global_data_min, data_min] is mapped to [int_min, val__min],
[data_min,data_max] is maped to [val _min, val_max],
[data_max,global_data_max] is mapped to [val_max, int_limit]."""
def __init__(self, int_limit=4095, int_min = 0, int_type = Numeric.Int16):
"""(int_limit=4095, int_type = Numeric.Int16)
int_limit - maximum int value of the resulting integer array;
int_type - Numeric typecode of the integer array. """
self.int_limit = int_limit
self.arr = None
self.int_min = int_min
self.val_max = int_limit
self.int_type = int_type
def __call__(self, data, data_min=None, data_max=None,
val_min=None, val_max=None, map_type='linear', powerOf2=0):
""" (data, data_min=None, data_max=None, val_min=None, val_max=None,
map_type = 'linear', powerOf2=0)
Maps an array of floats to integer values.
data -- 3D numeric array;
data_min, data_max -- min and max data values(other than actual
array minimum/maximum) to map to integer values -
val_min and val_max - in range (0 ... int_limit);
map_type -- can be 'linear' or 'log';
powerOf2 -- if set to 1, then if the data array dimensions are not
power of 2 - the returned array will be padded with zeros
so that its dims are power of 2.
"""
# if data_min/max and val_min/max specified then the mapping
# will proceed as follows:
# [arr_min, data_min] is mapped to [int_min, val_min],
# [data_min, data_max] is maped to [val_min, val_max],
# [data_max, arr_max] is mapped to [val_max, int_limit].
int_limit = self.int_limit
int_min = self.int_min
shape = data.shape
assert len(shape)==3
nx, ny, nz = shape
arrsize = nx*ny*nz
#arr_max = Numeric.maximum.reduce(data.ravel())
#arr_min = Numeric.minimum.reduce(data.ravel())
maxif = Numeric.maximum.reduce
arr_max = maxif(maxif(maxif(data)))
minif = Numeric.minimum.reduce
arr_min = minif(minif(minif(data)))
#print "min(arr)=%f" % arr_min
#print "max(arr)=%f" % arr_max
if val_min != None:
assert val_min >= 0 and val_min < int_limit
else:
val_min = int_min
if val_max != None:
assert val_max <= int_limit and val_max > 0
else:
val_max = int_limit
if data_min != None:
if data_min < arr_min: data_min = arr_min
else:
data_min = arr_min
if data_max != None:
if data_max > arr_max: data_max = arr_max
else:
data_max = arr_max
print "mapping data_min %4f to val_min %d, data_max %4f to val_max %d"\
% (data_min, val_min, data_max, val_max)
if map_type == 'linear':
k2,c2 = self.ScaleMap((val_min, val_max), (data_min, data_max))
n_intervals = 3
if abs(data_min-arr_min) < 0.00001: # data_min==arr_min
k1,c1 = k2, c2
n_intervals = n_intervals-1
else :
k1, c1 = self.ScaleMap((int_min, val_min),
(arr_min, data_min))
if abs(data_max-arr_max) < 0.00001: # data_max == arr_max
k3, c3 = k2, c2
n_intervals = n_intervals-1
else:
k3, c3 = self.ScaleMap((val_max, int_limit),
(data_max, arr_max))
t1 = time()
#print "n_intervals = ", n_intervals
if n_intervals == 2:
if data_max == arr_max:
#print "data_max == arr_max"
new_arr = Numeric.where(Numeric.less(data, data_min),
k1*data+c1, k2*data+c2 )
elif data_min == arr_min:
#print "data_min == arr_min"
new_arr = Numeric.where(Numeric.greater_equal(data,
data_max), k3*data+c3, k2*data+c2)
elif n_intervals == 3:
new_arr1 = Numeric.where(Numeric.less(data, data_min),
k1*data+c1, k2*data+c2)
new_arr = Numeric.where(Numeric.greater_equal(data, data_max),
k3*data+c3, new_arr1)
del(new_arr1)
else :
new_arr = k2*data+c2
arr = Numeric.transpose(new_arr).astype(self.int_type)
del(new_arr)
t2 = time()
print "time to map : ", t2-t1
elif map_type == 'log':
if arr_min < 0:
diff = abs(arr_min)+1.0
elif arr_min >= 0 and arr_min < 1.0:
diff = 1.0
elif arr_min >= 1.0:
diff=0
k1, c1 = self.ScaleMap( (int_min, int_limit),
(log(arr_min+diff), log(arr_max+diff)) )
arr=Numeric.transpose(k1*Numeric.log10(data+diff)+c1).astype(self.int_type)
self.data_min = data_min
self.data_max = data_max
self.val_min = val_min
self.val_max = val_max
if powerOf2:
nx1, ny1, nz1 = nx, ny, nz
res, power = isPowerOf2(nx)
if not res:
nx1 = 2**power
res, power = isPowerOf2(ny)
if not res:
ny1 = 2**power
res, power = isPowerOf2(nz)
if not res:
nz1 = 2**power
dx, dy, dz = 0, 0, 0
if nx1 != nx or ny1 != ny or nz1 != nz:
#print "new data size: ", nx1,ny1,nz1
dx = (nx1-nx)/2. ; dy = (ny1-ny)/2. ; dz = (nz1-nz)/2.
#narr = Numeric.zeros((nx1,ny1,nz1), self.int_type)
#narr[:nx,:ny,:nz] = arr[:,:,:]
narr = Numeric.zeros((nz1,ny1,nx1), self.int_type)
narr[:nz,:ny,:nx] = arr[:,:,:]
self.arr = narr
#arr = Numeric.zeros((nx1,ny1,nz1), self.int_type)
#arr[:nx,:ny,:nz] = new_arr[:,:,:]
#arr = Numeric.transpose(arr).astype(self.int_type)
#self.arr = arr
return narr
self.arr = arr
return arr
def ScaleMap(self, val_limit, data_limit, par=1):
""" Computes coefficients for linear mapping"""
assert data_limit[1]-data_limit[0]
k=(val_limit[1]-val_limit[0])/(data_limit[1]**par-data_limit[0]**par)
c=val_limit[1]-k*data_limit[1]**par
return (k,c)
```
#### File: MGLToolsPckgs/WebServices/OpalCache.py
```python
import sys
import time
import httplib
import urllib
import xml.dom.minidom
import os
import shutil
import subprocess
import copy
import urlparse
import pickle
from mglutil.web.services import AppService_client
class OpalCache:
def getServices(self, opal_url):
services = []
if opal_url.find("/opal2") != -1:
service_list_url = opal_url + "/opalServices.xml"
opener = urllib.FancyURLopener({})
socket = opener.open(service_list_url)
text = socket.read()
feed = xml.dom.minidom.parseString(text)
for entry in feed.getElementsByTagName('entry'):
link = entry.getElementsByTagName('link')[0]
service = link.getAttribute('href')
services.append(str(service))
else:
print "ERROR: No opal2 contained in URL"
return services
def getFileName(self, url):
hostname = url.split('http://')[1].split('/')[0]
hostname = hostname.replace(':', '+')
servicename = os.path.basename(url)
filename = os.path.join(hostname, servicename)
return filename
def getBinaryLocation(self, url, dir):
(bl, x2, x3) = self.getCache(url, dir)
return bl
def getParams(self, url, dir):
(x1, params, x3) = self.getCache(url, dir)
return params
def getSeparator(self, url, dir):
(x1, x2, separator) = self.getCache(url, dir)
return separator
def getServicesFromCache(self, url, dir, disable_inactives=True):
hostname = url.split('http://')[1].split('/')[0]
hostname = hostname.replace(':', '+')
hostcd = os.path.join(dir, hostname)
inactivedir = os.path.join(os.path.join(dir, "inactives"), hostname)
files = []
inactives = []
try:
files = os.listdir(hostcd)
inactives = os.listdir(inactivedir)
actives = set(files) - set(inactives)
except:
print "ERROR: Cache directory for " + url + " does not exist!"
print " Are you connected to the internet???"
return []
if disable_inactives:
services = map(lambda x: url + '/services/' + x, actives)
else:
services = map(lambda x: url + '/services/' + x, files)
return services
def getCache(self, url, dir):
file = os.path.join(dir, self.getFileName(url))
params = pickle.load(open(file))
return params
def isCacheValid(self, url, dir, days=30):
fn = self.getFileName(url)
cachedir = os.path.join(dir, os.path.dirname(fn))
filename = os.path.join(dir, fn)
if not(os.path.exists(cachedir)) or not(os.path.exists(filename)):
return False
if (time.time() - os.path.getmtime(filename) > days * 86400):
print "*** [WARNING]: Cache for " + url + " is older than " + days + " days!"
return False
return True
def writeCache(self, url, dir, days=30):
fn = self.getFileName(url)
cachedir = os.path.join(dir, os.path.dirname(fn))
if not(os.path.exists(cachedir)):
os.mkdir(cachedir)
filename = os.path.join(dir, fn)
if not(self.isCacheValid(url, dir, days)):
print "[INFO]: Writing cache for " + url + " in " + filename
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
req = AppService_client.getAppMetadataRequest()
metadata = appServicePort.getAppMetadata(req)
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
# req = AppService_client.getAppConfigRequest()
# metadata2 = appServicePort.getAppConfig(req)
# executable = metadata2._binaryLocation
try:
req = AppService_client.getAppConfigRequest()
metadata2 = appServicePort.getAppConfig(req)
executable = metadata2._binaryLocation
except:
executable = 'NA'
pass
separator = None
params = {}
try:
rawlist = metadata._types._flags._flag
order = 0
for i in rawlist:
myhash = {}
myhash = {'type': 'boolean'}
myhash['config_type'] = 'FLAG'
myhash['tag'] = str(i._tag)
myhash['default'] = 'True' if str(i._default)=='True' else 'False'
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
try:
rawlist = metadata._types._taggedParams._param
separator = metadata._types._taggedParams._separator
order = 0
for i in rawlist:
myhash = {}
myhash['config_type'] = 'TAGGED'
if i._value:
myhash['type'] = 'selection'
myhash['values'] = [str(z) for z in i._value]
else:
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
myhash['default'] = str(i._default) if i._default else None
myhash['tag'] = str(i._tag)
myhash['separator'] = separator
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
try:
rawlist = metadata._types._untaggedParams._param
order = 0
for i in rawlist:
myhash = {}
myhash['config_type'] = 'UNTAGGED'
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc)
myhash['default'] = str(i._default) if i._default else None
myhash['tag'] = str(i._tag)
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
lock = filename + '.lock'
if os.path.exists(lock) and time.time() - os.path.getmtime(lock) > 100:
os.remove(lock)
if not(os.path.exists(lock)):
open(lock, 'w').close()
pickle.dump((executable, params, separator), open(filename, "wb"))
os.remove(lock)
```
|
{
"source": "J-E-J-S/ProtocolScraper",
"score": 3
}
|
#### File: ProtocolScraper/protocolScraper/protocolScraper.py
```python
import requests
import re
import click
def search_page(string):
''' Given search string will return JSON format of the search page for that string '''
base = 'https://www.protocols.io/api/v3/protocols' # http request base
payload = {'filter': 'public', "order_field" : 'relevance', "key" : string} # api parameters : https://apidoc.protocols.io/#get-list
r = requests.get(base, params=payload) # requests page information
jason = r.json() # page as json format
return jason
def protocol_ids(jason):
''' Given JSON of search page, will return list of ids in descending order of releveancy '''
ids = []
for item in jason['items']: # this format because dictionary into list
ids.append(item['id'])
return ids
def get_protocols(ids, limit):
''' Returns list of protocol objects through api '''
base = 'https://www.protocols.io/api/v3/protocols/'
protocol_list = [] # holds jason of protocol objects for top 3 relevent protocols
count = 0
while count < limit: # CHANGE THIS limit to however many files you want to generate
try:
number = str(ids[count]) # gets id from list and converts to string for search
url = base + number # plugs id into url
r = requests.get(url) # request api
except:
return protocol_list
jason = r.json() # converts json
protocol_list.append(jason)
click.echo('Collected Protocol ' + str(count+1) + '.' )
count += 1
return protocol_list
def single_translate_steps(protocol):
''' Takes a protocol object and returns list of steps as strings with title of protocol being first element '''
steps = protocol['protocol']['steps'] # steps object of protocol
step_list = ['Steps:'] # stores cleaned text with title of protocol being first item in list
for step in steps:
step_description = step['components'][1]['source']['description'] # navigates JSON to description which holds html of step text
cleanr = re.compile('<.*?>')
clean_text = re.sub(cleanr, '', step_description) # removes html syntax from step text
step_list.append(clean_text)
count = 1
while count < len(step_list):
step_list[count] = str(count) + '. ' + step_list[count] # adds step number to description but not to title
count += 1
return step_list
def single_translate_material(protocol):
''' Takes protocol object and returns list of materials for protocol '''
title = protocol['protocol']['title'] # title of protocol
materials = protocol['protocol']['materials']
material_list = [title, 'Materials:']
for reagent in materials:
material_list.append(reagent['name']) # gets material name + quant.
count = 2
while count < len(material_list):
material_list[count] = '* ' + material_list[count] # adds bullet point to material description
count +=1
if len(material_list) == 2:
material_list.append('None') # checks to see if materials are included in protocol
return material_list
def find_credit(protocol):
''' Finds author credit from protocol object and protocol url '''
credit = ['Reference:'] # holds information on author, authors' institution and protocol url on protocol.io
authors = protocol['protocol']['authors']
for item in authors:
credit.append(item['name']) # finds authors name
if item['affiliation'] != 'null':
credit.append(item['affiliation']) # finds authors institution if given
url = protocol['protocol']['url'] # finds url for protocol on protocol.io
credit.append(url)
return credit
def write_protocols(protocol_list):
''' Writes the protocol information to files '''
count = 0
while count < len(protocol_list):
translation = single_translate_steps(protocol_list[count]) # translates protocol object into plain text steps (see single_translate function) + remove spaces
material_list = single_translate_material(protocol_list[count])
credit_list = find_credit(protocol_list[count])
title = material_list[0].replace(' ', '_') # first element in material_list is always title
f = open(str(count+1)+ '_' + title + '.txt', 'w') # creates file with unique name
for material in material_list: # writes materials section + title
material = material.encode('cp1252', 'replace').decode('cp1252')
f.write(material + '\n')
for step in translation: # writes steps
step = step.encode('cp1252', 'replace').decode('cp1252') # this fixes bug that brings up UnicodeEncodeError for greek/roman symbol
f.write(step + '\n') # writes out steps to file
for item in credit_list:
try:
item = item.encode('cp1252', 'replace').decode('cp1252')
except:
continue
f.write(item + '\n')
f.close()
count += 1
@click.command()
@click.argument('protocol')
@click.option('-l', '--limit', default = 3, type=int, help='Number of test protocols to write. Default = 3' )
def cli(protocol, limit):
"""Arguments:\n
PROTOCOL The protocol to write.
"""
click.echo('Accessing protocols.io API.')
jason = search_page(protocol)
ids = protocol_ids(jason)
protocol_list = get_protocols(ids, limit)
click.echo('Writing Protocols...')
write_protocols(protocol_list)
click.echo('Protocol Generation Complete.')
click.echo(str(len(protocol_list)) + ' Protocols Written.')
if __name__ == '__main__':
cli()
```
|
{
"source": "jej-ui/yatta-gif",
"score": 3
}
|
#### File: jej-ui/yatta-gif/yatta.py
```python
from PIL import Image, ImageSequence
#yatta gif
im1 = Image.open('yatta.gif')
# profile pic
im2 = Image.open('elysia.png').resize((200,200))
img = Image.new("RGB", im1.size, (255, 255, 255))
img.paste(im2, (210,60))
def senti():
frames = []
for frame in ImageSequence.Iterator(im1):
if len(frames) < 35:
mask_im = Image.open(f'fmask/senti{len(frames)}.png').resize(im1.size).convert('1')
frame = Image.composite(im1, img, mask_im)
frame = frame.copy()
frames.append(frame)
else:
frame = frame.copy()
frames.append(frame)
frames[0].save('result.gif', save_all=True, append_images=frames[1:], duration=30, loop=0)
senti()
```
|
{
"source": "Jejulia/labtools",
"score": 3
}
|
#### File: labtools/labtools/library.py
```python
import pandas as pd
import numpy as np
import tkinter as tk
class package:
def __init__(self):
# elements defined
C = 12
H = 1.007825
N = 14.003074
O = 15.994915
P = 30.973763
S = 31.972072
Na = 22.98977
Cl = 34.968853
self.elements = [C,H,N,O,P,S,Na,Cl]
self.elementsymbol = ['C','H','N','O','P','S','Na','Cl']
ionname = ['M','M+H','M+2H','M+H-H2O','M+2H-H2O','M+Na','M+2Na','M+2Na-H','M+NH4',
'M-H','M-2H','M-3H','M-4H','M-5H','M-H-H2O','M-2H-H2O','M-CH3','M+Cl','M+HCOO','M+OAc']
ionfunc = []
ionfunc.append(lambda ms: ms)
ionfunc.append(lambda ms: ms+package().elements[1])
ionfunc.append(lambda ms: (ms+2*package().elements[1])/2)
ionfunc.append(lambda ms: ms-package().elements[1]-package().elements[3])
ionfunc.append(lambda ms: (ms-package().elements[3])/2)
ionfunc.append(lambda ms: ms+package().elements[6])
ionfunc.append(lambda ms: (ms+2*package().elements[6])/2)
ionfunc.append(lambda ms: ms-package().elements[1]+2*package().elements[6])
ionfunc.append(lambda ms: ms+4*package().elements[1]+package().elements[2])
ionfunc.append(lambda ms: ms-package().elements[1])
ionfunc.append(lambda ms: (ms-2*package().elements[1])/2)
ionfunc.append(lambda ms: (ms-3*package().elements[1])/3)
ionfunc.append(lambda ms: (ms-4*package().elements[1])/4)
ionfunc.append(lambda ms: (ms-5*package().elements[1])/5)
ionfunc.append(lambda ms: ms-3*package().elements[1]-package().elements[3])
ionfunc.append(lambda ms: (ms-4*package().elements[1]-package().elements[3])/2)
ionfunc.append(lambda ms: ms-package().elements[0]-3*package().elements[1])
ionfunc.append(lambda ms: ms+package().elements[7])
ionfunc.append(lambda ms: ms+package().elements[0]+package().elements[1]+2*package().elements[3])
ionfunc.append(lambda ms: ms+2*package().elements[0]+3*package().elements[1]+2*package().elements[3])
self.ion = {}
for i,j in enumerate(ionname):
self.ion[j] = ionfunc[i]
# %% [markdown]
# Package for Sphingolipids
# %%
class package_sl(package):
def __init__(self):
# base structure defined
self.base = {'Cer': np.array([0,3,1,0]+[0]*(len(package().elements)-4)),
'Sphingosine': np.array([0,3,1,0]+[0]*(len(package().elements)-4)),
'Sphinganine': np.array([0,3,1,0]+[0]*(len(package().elements)-4))}
# headgroups defined
headgroup = ['Pi','Choline','Ethanolamine','Inositol','Glc','Gal','GalNAc','NeuAc','Fuc','NeuGc']
formula = []
formula.append(np.array([0,3,0,4,1]+[0]*(len(package().elements)-5)))
formula.append(np.array([5,13,1,1]+[0]*(len(package().elements)-4)))
formula.append(np.array([2,7,1,1]+[0]*(len(package().elements)-4)))
formula.append(np.array([6,12,0,6]+[0]*(len(package().elements)-4)))
formula.append(np.array([6,12,0,6]+[0]*(len(package().elements)-4)))
formula.append(np.array([6,12,0,6]+[0]*(len(package().elements)-4)))
formula.append(np.array([8,15,1,6]+[0]*(len(package().elements)-4)))
formula.append(np.array([11,19,1,9]+[0]*(len(package().elements)-4)))
formula.append(np.array([6,12,0,5]+[0]*(len(package().elements)-4)))
formula.append(np.array([11,19,1,10]+[0]*(len(package().elements)-4)))
self.components = self.base.copy()
for i,j in enumerate(headgroup):
self.components[j] = formula[i]
# sn type defined
sntype = ['none','d','t']
snformula = []
snformula.append(lambda carbon,db: np.array([carbon,2*carbon-2*db,0,2]+[0]*(len(package().elements)-4)))
snformula.append(lambda carbon,db: np.array([carbon,2*carbon+2-2*db,0,3]+[0]*(len(package().elements)-4)))
snformula.append(lambda carbon,db: np.array([carbon,2*carbon+2-2*db,0,4]+[0]*(len(package().elements)-4)))
self.sn = {}
for i,j in enumerate(sntype):
self.sn[j] = snformula[i]
# extended structure
nana = ['M','D','T','Q','P']
iso = ['1a','1b','1c']
namedf = pd.DataFrame({'0-series': ['LacCer'],'a-series': ['GM3'],'b-series': ['GD3'],'c-series': ['GT3']})
namedf = namedf.append(pd.Series(['G'+'A'+'2' for name in namedf.iloc[0,0:1]]+['G'+i+'2' for i in nana[0:3]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series(['G'+'A'+'1' for name in namedf.iloc[0,0:1]]+['G'+i+j for i,j in zip(nana[0:3],iso)],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series(['G'+'M'+'1b' for name in namedf.iloc[0,0:1]]+['G'+i+j for i,j in zip(nana[1:4],iso)],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series(['G'+'D'+'1c' for name in namedf.iloc[0,0:1]]+['G'+i+j for i,j in zip(nana[2:],iso)],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series(['G'+'D'+'1α' for name in namedf.iloc[0,0:1]]+[i+'α' for i in namedf.iloc[4,1:]],index = namedf.columns), ignore_index=True)
sequencedf = pd.DataFrame({'0-series': ['Gal-Glc-Cer'],'a-series': ['(NeuAc)-Gal-Glc-Cer'],'b-series': ['(NeuAc-NeuAc)-Gal-Glc-Cer'],'c-series': ['(NeuAc-NeuAc-NeuAc)-Gal-Glc-Cer']})
sequencedf = sequencedf.append(pd.Series(['GalNAc-'+formula for formula in sequencedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Gal-'+formula for formula in sequencedf.iloc[1,:]],index = namedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['NeuAc-'+formula for formula in sequencedf.iloc[2,:]],index = namedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['NeuAc-'+formula for formula in sequencedf.iloc[3,:]],index = namedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['NeuAc-Gal-(NeuAc)-GalNAc-'+formula for formula in sequencedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
self.base = {'Cer': 'Cer','Sphingosine': 'Sphingosine','Sphinganine': 'Sphinganine','Sphingosine-1-Phosphate': 'Pi-Sphingosine','Sphinganine-1-Phosphate': 'Pi-Sphinganine',
'CerP': 'Pi-Cer','SM': 'Choline-Pi-Cer','CerPEtn': 'Ethanolamine-Pi-Cer','CerPIns': 'Inositol-Pi-Cer',
'LysoSM(dH)': 'Choline-Pi-Sphinganine','LysoSM': 'Choline-Pi-Sphingosine',
'GlcCer': 'Glc-Cer','GalCer': 'Gal-Cer'}
for i in namedf:
for j,k in enumerate(namedf[i]):
self.base[k] = sequencedf[i][j]
def basesn(self,base,typ):
typ = base[typ].split('-')[-1]
if 'Cer' == base[typ]:
return [['d','t'],list(range(18,23)),':',[0,1],'/',['none','h'],list(range(12,33)),':',[0,1]]
elif 'Sphingosine' == base[typ]:
return [['d','t'],list(range(18,23)),':','1']
elif 'Sphinganine' == base[typ]:
return [['d','t'],list(range(18,23)),':','0']
else:
return 0
def iterate(self,base,typ,start,end):
typ = base[typ].split('-')[-1]
start = pd.Series(start)
end = pd.Series(end)
start = start.replace('none','')
end = end.replace('none','')
if 'Cer' == base[typ]:
return ['{}{}:{}/{}{}:{}'.format(i,j,k,l,m,n) for i in [start[0]] for k in range(int(start[2]),int(end[2])+1) for j in range(int(start[1]),int(end[1])+1) for n in range(int(start[5]),int(end[5])+1) for l in [start[3]] for m in range(int(start[4]),int(end[4])+1)]
elif 'Sphingosine' == base[typ]:
return ['{}{}:1'.format(i,j) for i in [start[0]] for j in range(int(start[1]),int(end[1])+1)]
elif 'Sphinganine' == base[typ]:
return ['{}{}:0'.format(i,j) for i in [start[0]] for j in range(int(start[1]),int(end[1])+1)]
else:
return 0
# %% [markdown]
# Package for Glycerophospholipids
# %%
class package_gpl(package):
def __init__(self):
# base structure defined
self.base = {'PA': np.array([3,9,0,6,1]+[0]*(len(package().elements)-5)),
'LysoPA': np.array([3,9,0,6,1]+[0]*(len(package().elements)-5))}
# headgroups defined
headgroup = ['Pi','Choline','Ethanolamine','Inositol','Glycerol']
formula = []
formula.append(np.array([0,3,0,4,1]+[0]*(len(package().elements)-5)))
formula.append(np.array([5,13,1,1]+[0]*(len(package().elements)-4)))
formula.append(np.array([2,7,1,1]+[0]*(len(package().elements)-4)))
formula.append(np.array([6,12,0,6]+[0]*(len(package().elements)-4)))
formula.append(np.array([3,8,0,3]+[0]*(len(package().elements)-4)))
self.components = self.base.copy()
for i,j in enumerate(headgroup):
self.components[j] = formula[i]
# sn type defined
sntype = ['none','O','P']
snformula = []
snformula.append(lambda carbon,db: np.array([carbon,2*carbon-2*db,0,2]+[0]*(len(package().elements)-4)))
snformula.append(lambda carbon,db: np.array([carbon,2*carbon+2-2*db,0,1]+[0]*(len(package().elements)-4)))
snformula.append(lambda carbon,db: np.array([carbon,2*carbon-2*db,0,1]+[0]*(len(package().elements)-4)))
self.sn = {}
for i,j in enumerate(sntype):
self.sn[j] = snformula[i]
# extended structure(extended structure can be defined by library.baseext())
namedf = pd.DataFrame({'a': ['PA'],'b': ['LysoPA']})
namedf = namedf.append(pd.Series([name[0:-1]+'C' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'E' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'G' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'GP' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'I' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'IP' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'IP2' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
namedf = namedf.append(pd.Series([name[0:-1]+'IP3' for name in namedf.iloc[0,:]],index = namedf.columns), ignore_index=True)
sequencedf = pd.DataFrame({'a': ['PA'],'b': ['LysoPA']})
sequencedf = sequencedf.append(pd.Series(['Choline-'+name for name in sequencedf.iloc[0,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Ethanolamine-'+name for name in sequencedf.iloc[0,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Glycerol-'+name for name in sequencedf.iloc[0,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Pi-'+name for name in sequencedf.iloc[3,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Inositol-'+name for name in sequencedf.iloc[0,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Pi-'+name for name in sequencedf.iloc[5,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Pi-'+name for name in sequencedf.iloc[6,:]],index = sequencedf.columns), ignore_index=True)
sequencedf = sequencedf.append(pd.Series(['Pi-'+name for name in sequencedf.iloc[7,:]],index = sequencedf.columns), ignore_index=True)
self.base = {'PA': 'PA','LysoPA': 'LysoPA'}
for i in namedf:
for j,k in enumerate(namedf[i]):
self.base[k] = sequencedf[i][j]
def basesn(self,base,typ):
typ = base[typ].split('-')[-1]
if 'PA' == base[typ]:
return [['none','O','P'],list(range(2,27)),':',[0,1,2,3,4,5,6],'/',['none','O','P'],list(range(2,27)),':',[0,1,2,3,4,5,6]]
elif 'LysoPA' == base[typ]:
return [['none','O','P'],list(range(2,27)),':',[0,1,2,3,4,5,6]]
else:
return 0
def iterate(self,base,typ,start,end):
typ = base[typ].split('-')[-1]
start = pd.Series(start)
end = pd.Series(end)
start = start.replace('none','')
end = end.replace('none','')
if 'PA' == base[typ]:
return ['{}{}:{}/{}{}:{}'.format(i,j,k,l,m,n) for i in [start[0]] for j in range(int(start[1]),int(end[1])+1) for k in range(int(start[2]),int(end[2])+1) for l in [start[3]] for m in range(int(start[4]),int(end[4])+1) for n in range(int(start[5]),int(end[5])+1)]
elif 'LysoPA' == base[typ]:
return ['{}{}:{}'.format(i,j,k) for i in [start[0]] for j in range(int(start[1]),int(end[1])+1) for k in range(int(start[2]),int(end[2])+1)]
else:
return 0
# %% [markdown]
# library class
# %%
class library(package):
def __init__(self,pack):
self.elements = package().elements
self.elementsymbol = package().elementsymbol
self.ion = package().ion
self.components = {}
self.base = {}
self.sn = {}
self.basesnorg = []
self.iterateorg = []
for i,j in enumerate(pack):
self.components = {**self.components,**j().components}
self.base = {**self.base,**j().base}
self.sn = {**self.sn,**j().sn}
self.basesnorg.append(j().basesn)
self.iterateorg.append(j().iterate)
def basesn(self,typ):
base = self.base
for i in range(len(self.basesnorg)):
if not self.basesnorg[i](base,typ) == 0:
return self.basesnorg[i](base,typ)
def iterate(self,typ,start,end):
base = self.base
for i in range(len(self.iterateorg)):
if not self.iterateorg[i](base,typ,start,end) == 0:
return self.iterateorg[i](base,typ,start,end)
def newhgdef(self,newheadgroup,newformula):
self.components[newheadgroup] = newformula
def baseext(self,name,sequence):
self.base[name] = sequence
def mscomp(self,name):
components = name.split('-')
base = components[-1].split('(')[0]
sn = components[-1].split('(')[1].split(')')[0].split('/')
hg = '('+name.replace(base,'')+self.base[base]+')'
hgcode = []
s = 0
hg = hg.split('-')
hg.reverse()
for i,j in enumerate(hg):
if ')' in j:
s += 1
hgcode.append(s)
if '(' in j:
s+= -1
hg[i] = j.replace('(','').replace(')','')
code = []
for i,j in enumerate(hgcode):
if i == 0:
code.append([0])
elif hgcode[i-1] == j:
new = code[i-1].copy()
last = new[-1]+1
new.pop()
new.append(last)
code.append(new)
elif hgcode[i-1] < j:
new = code[i-1].copy()
new.append(0)
code.append(new)
elif hgcode[i-1] > j:
pre = max([k for k in range(i) if hgcode[k] == j])
new = code[pre].copy()
last = new[-1]+1
new.pop()
new.append(last)
code.append(new)
comp = pd.DataFrame({'headgroups': hg,'position': code})
return comp
def msformula(self,name,mode):
components = name.split('-')
base = components[-1].split('(')[0]
sn = components[-1].split('(')[1].split(')')[0].split('/')
headgroups = components[0:-1]
for hg in headgroups:
if '(' in hg:
if ')' not in hg.split('(')[1]:
headgroups[headgroups.index(hg)] = hg.split('(')[1]
elif ')' in hg.split('(')[1]:
headgroups[headgroups.index(hg)] = hg.split('(')[1].split(')')[0]
elif ')' in hg:
headgroups[headgroups.index(hg)] = hg.split(')')[0]
ms = np.array([0,2,0,1]+[0]*(len(self.elements)-4))
H2O = np.array([0,2,0,1]+[0]*(len(self.elements)-4))
for hg in headgroups:
ms += self.components[hg]
ms += -H2O
components = self.base[base].split('-')
for c in components:
if '(' in c:
if ')' not in c.split('(')[1]:
components[components.index(c)] = c.split('(')[1]
elif ')' in c.split('(')[1]:
components[components.index(c)] = c.split('(')[1].split(')')[0]
elif ')' in c:
components[components.index(c)] = c.split(')')[0]
for c in components:
ms += self.components[c]
ms += -H2O
for sni in sn:
if 'd' in sni:
carbon = int(sni.split('d')[1].split(':')[0])
db = int(sni.split('d')[1].split(':')[1])
ms += self.sn['d'](carbon,db)
elif 't' in sni:
carbon = int(sni.split('t')[1].split(':')[0])
db = int(sni.split('t')[1].split(':')[1])
ms += self.sn['t'](carbon,db)
elif 'O' in sni:
carbon = int(sni.split('O')[1].split(':')[0])
db = int(sni.split('O')[1].split(':')[1])
ms += self.sn['O'](carbon,db)
elif 'P' in sni:
carbon = int(sni.split('P')[1].split(':')[0])
db = int(sni.split('P')[1].split(':')[1])
ms += self.sn['P'](carbon,db)
else:
carbon = int(sni.split(':')[0])
db = int(sni.split(':')[1])
ms += self.sn['none'](carbon,db)
ms += -H2O
if mode == 'raw':
return ms
elif mode == 'molecule':
formulalist = [i+'{}'.format(j) for i,j in zip(self.elementsymbol[0:len(ms)],ms) if j > 0]
formula = ''
for f in formulalist:
formula += f
return formula
def mscalculator(self,name,ion):
ms = (self.msformula(name,mode='raw')*self.elements[0:len(self.msformula(name,mode='raw'))]).cumsum()[-1]
return self.ion[ion](ms)
def export(self):
expwind = tk.Tk()
expwind.title('Export settings')
expwind.geometry('700x300')
var_base = tk.StringVar()
initialbase = list(self.base.keys())
title = tk.Label(expwind,text = 'Select base')
title.config(font=("Times New Roman", 20))
var_base.set(initialbase)
listbox1 = tk.Listbox(expwind,listvariable = var_base,selectmode = 'extended')
listbox1.config(font=("Times New Roman", 12))
var_add = tk.StringVar()
subtitle = tk.Label(expwind,text = 'others')
subtitle.config(font=("Times New Roman", 15))
other = tk.Entry(expwind,textvariable = var_add)
other.config(font=("Times New Roman", 12))
def base_selection():
global base_input
base_input = [listbox1.get(i) for i in listbox1.curselection()]
title.destroy()
listbox1.destroy()
button1.destroy()
subtitle.destroy()
other.destroy()
addbutton.destroy()
global sn_input
sn_input = []
def snloop(i,skip,add,apply):
if skip == True:
i += 1
else:
global menu_st,menu_end,var_st,var_end
menu_st = []
menu_end = []
var_st = []
var_end = []
title = tk.Label(expwind,text = base_input[i])
title.config(font=("Times New Roman", 20))
title.grid(row = 0,column = 0,padx=20)
labelstart = tk.Label(expwind,text = 'start')
labelstart.config(font=("Times New Roman", 15))
labelend = tk.Label(expwind,text = 'end')
labelend.config(font=("Times New Roman", 15))
labelstart.grid(row = 1,column = 0,padx=20)
label = []
for n,sntype in enumerate(self.basesn(base_input[i])):
if type(sntype) == str:
label.append(tk.Label(expwind,text = sntype))
label[-1].config(font=("Times New Roman", 12))
label[-1].grid(row = 1,column = n+1)
else:
var_st.append(tk.StringVar())
menu_st.append(tk.OptionMenu(expwind,var_st[-1],*sntype))
menu_st[-1].config(font=("Times New Roman", 12))
menu_st[-1].grid(row = 1,column = n+1)
labelend.grid(row = 2,column = 0,padx=20)
for n,sntype in enumerate(self.basesn(base_input[i])):
if type(sntype) == str:
label.append(tk.Label(expwind,text = sntype))
label[-1].config(font=("Times New Roman", 12))
label[-1].grid(row = 2,column = n+1)
elif type(sntype[0]) == str:
label.append(tk.Label(expwind,text = ''))
label[-1].config(font=("Times New Roman", 12))
label[-1].grid(row = 2,column = n+1)
var_end.append(tk.StringVar())
var_end[-1].set(var_st[n].get())
menu_end.append(tk.OptionMenu(expwind,var_end[-1],*sntype))
else:
var_end.append(tk.StringVar())
menu_end.append(tk.OptionMenu(expwind,var_end[-1],*sntype))
menu_end[-1].config(font=("Times New Roman", 12))
menu_end[-1].grid(row = 2,column = n+1)
i += 1
def sn_selection():
st = []
end = []
for n in range(len(menu_st)):
st.append(var_st[n].get())
end.append(var_end[n].get())
menu_st[n].destroy()
menu_end[n].destroy()
for n in label:
n.destroy()
title.destroy()
labelstart.destroy()
labelend.destroy()
button2.destroy()
button3.destroy()
button4.destroy()
if add == True:
sn_input[-1] = sn_input[-1]+self.iterate(base_input[i-1],st,end)
else:
sn_input.append(self.iterate(base_input[i-1],st,end))
if i < len(base_input):
snloop(i,skip = False,add = False,apply = False)
else:
cancel.destroy()
ion_selection()
def apply_all():
st = []
end = []
for n in range(len(menu_st)):
st.append(var_st[n].get())
end.append(var_end[n].get())
menu_st[n].destroy()
menu_end[n].destroy()
for n in label:
n.destroy()
title.destroy()
labelstart.destroy()
labelend.destroy()
if apply == False:
button2.destroy()
button3.destroy()
button4.destroy()
if add == True:
sn_input[-1] = sn_input[-1]+self.iterate(base_input[i-1],st,end)
else:
sn_input.append(self.iterate(base_input[i-1],st,end))
if i < len(base_input):
if self.basesn(base_input[i]) in [self.basesn(base_input[p]) for p in range(i)]:
snloop(i,skip = True,add = False,apply = True)
else:
snloop(i,skip = False,add = False,apply = True)
else:
ion_selection()
def add_other():
st = []
end = []
for n in range(len(menu_st)):
st.append(var_st[n].get())
end.append(var_end[n].get())
menu_st[n].destroy()
menu_end[n].destroy()
for n in label:
n.destroy()
title.destroy()
labelstart.destroy()
labelend.destroy()
if apply == False:
button2.destroy()
button3.destroy()
button4.destroy()
if add == True:
sn_input[-1] = sn_input[-1]+self.iterate(base_input[i-1],st,end)
else:
sn_input.append(self.iterate(base_input[i-1],st,end))
if apply == True:
snloop(i-1,skip = False,add = True,apply = True)
else:
snloop(i-1,skip = False,add = True,apply = False)
if skip == False:
if apply == False:
button2 = tk.Button(expwind,text = 'confirm',command = sn_selection)
button2.config(font=("Times New Roman", 12))
button2.grid(row = 3,column = 0)
button3 = tk.Button(expwind,text = 'apply to others',command = apply_all)
button3.config(font=("Times New Roman", 12))
button3.grid(row = 3,column = 1)
button4 = tk.Button(expwind,text = 'add',command = add_other)
button4.config(font=("Times New Roman", 12))
button4.grid(row = 3,column = 2)
expwind.mainloop()
else:
index = [self.basesn(base_input[p]) for p in range(i-1)].index(self.basesn(base_input[i-1]))
sn_input.append(sn_input[index])
if i < len(base_input):
if self.basesn(base_input[i]) in [self.basesn(base_input[p]) for p in range(i)]:
snloop(i,skip = True,add = False,apply = False)
else:
snloop(i,skip = False,add = False,apply = False)
else:
cancel.destroy()
ion_selection()
snloop(0,skip = False,add = False,apply = False)
def add_base():
initialbase.append(other.get())
var_base.set(initialbase)
other.delete(first = 0,last = 100)
def ion_selection():
title1 = tk.Label(expwind,text = 'Select ions')
title1.config(font=("Times New Roman", 20))
var_ion = tk.StringVar()
var_ion.set(list(package().ion.keys()))
listbox2 = tk.Listbox(expwind,listvariable = var_ion,selectmode = 'extended')
listbox2.config(font=("Times New Roman", 12))
title1.grid(row = 0,column = 0,padx=100)
listbox2.grid(row = 1,column = 0,padx=100)
def filename_type():
global ion_input
ion_input = [listbox2.get(i) for i in listbox2.curselection()]
title1.destroy()
listbox2.destroy()
button5.destroy()
title2 = tk.Label(expwind,text = 'Type filename(with.xlsx)')
title2.config(font=("Times New Roman", 20))
var_file = tk.StringVar(value = 'library.xlsx')
file = tk.Entry(expwind,textvariable = var_file)
file.config(font=("Times New Roman", 12))
title2.grid(row = 0,column = 0,padx=100)
file.grid(row = 1,column = 0,padx=100)
def export():
global filename
filename = var_file.get()
self.toexcel()
expwind.destroy()
root()
button6 = tk.Button(expwind,text = 'export',command = export)
button6.config(font=("Times New Roman", 12))
button6.grid(row = 2,column = 0,padx=100)
expwind.mainloop()
button5 = tk.Button(expwind,text = 'confirm',command = filename_type)
button5.config(font=("Times New Roman", 12))
button5.grid(row = 2,column = 0,padx=100)
cancel = tk.Button(expwind,text = 'cancel',command = cancelrun)
cancel.config(font=("Times New Roman", 12))
cancel.grid(row = 2,column = 1,padx=5)
expwind.mainloop()
def cancelrun():
expwind.destroy()
root()
button1 = tk.Button(expwind,text = 'confirm',command = base_selection)
button1.config(font=("Times New Roman", 12))
addbutton = tk.Button(expwind,text = 'add',command = add_base)
addbutton.config(font=("Times New Roman", 12))
title.grid(row = 0,column = 0,padx=20)
listbox1.grid(row = 1,column = 0,rowspan = 9,padx=20)
button1.grid(row = 10,column = 0,padx=20)
subtitle.grid(row = 0,column = 1,padx=20)
other.grid(row = 1,column = 1,padx=20)
addbutton.grid(row = 2,column = 1,padx=20)
cancel = tk.Button(expwind,text = 'cancel',command = cancelrun)
cancel.config(font=("Times New Roman", 12))
cancel.grid(row = 10,column = 20)
expwind.mainloop()
def toexcel(self):
with pd.ExcelWriter(filename) as writer:
self.df = {}
for i,b in enumerate(base_input):
name = [b+'('+j+')' for j in sn_input[i]]
self.df[b] = pd.DataFrame({b: name})
self.df[b]['formula'] = [self.msformula(j,'molecule') for j in name]
for ion in ion_input:
ms = [self.mscalculator(i,ion) for i in self.df[b][b]]
self.df[b][ion] = ms
self.df[b].to_excel(writer,index = False,sheet_name = '{}'.format(b))
# %% [markdown]
# GUI
# %%
def entry():
package_available = {'Sphingolipid': package_sl,'Glycerophospholipid': package_gpl}
entrywind = tk.Tk()
entrywind.geometry('500x300')
title = tk.Label(entrywind,text = 'Welcome! choose package(s)')
title.config(font=("Times New Roman", 20))
var_pack = tk.StringVar()
var_pack.set(list(package_available.keys()))
listbox = tk.Listbox(entrywind,listvariable = var_pack,selectmode = 'extended')
def choose_pack():
pack = [listbox.get(i) for i in listbox.curselection()]
global currentlibrary
currentlibrary = library([package_available[i] for i in pack])
entrywind.destroy()
root()
button = tk.Button(entrywind,text = 'confirm',command = choose_pack)
button.config(font=("Times New Roman", 12))
title.pack()
listbox.pack()
button.pack()
entrywind.mainloop()
def root():
rootwind = tk.Tk()
rootwind.geometry('500x300')
def run_export():
rootwind.destroy()
global exp
exp = True
def cancelrun():
rootwind.destroy()
global exp
exp = False
del currentlibrary
title = tk.Label(rootwind,text = 'Root')
title.config(font=("Times New Roman", 20))
export = tk.Button(rootwind,text = 'Export data',command = run_export)
export.config(font=("Times New Roman", 12))
cancel = tk.Button(rootwind,text = 'cancel',command = cancelrun)
cancel.config(font=("Times New Roman", 12))
title.pack(pady = 5)
export.pack(pady = 5)
cancel.pack(pady = 5)
rootwind.mainloop()
while __name__ == '__main__':
entry()
while exp == True:
currentlibrary.export()
```
#### File: labtools/labtools/model.py
```python
import pandas as pd
import numpy as np
import scipy.stats as ss
import statsmodels.api as sm
import matplotlib.pyplot as plt
from tkinter.filedialog import askopenfilename, asksaveasfilename
import re
import multiprocessing as mp
from labtools.plot import plot_calibration_line
import random
import labtools.optimizer as op
def test(a,x):
if a > x:
return a
else:
pass
def comp(data):
pool = mp.Pool(mp.cpu_count())
results = pool.starmap(test, [(a,10) for a in data])
pool.close()
return results
class lm():
def __init__(self,x,y,w):
self.x = x
self.y = y
self.w = w
self.model = sm.WLS(y,sm.add_constant(x),weights = self.w)
self.fit = self.model.fit()
def accuracy(self):
return (self.y-self.fit.params[0])/self.fit.params[1]/self.x
def residual(self):
return (self.y-self.fit.params[0])/self.fit.params[1]-self.x
def vscore(self,target="accuracy"):
if target == "accuracy":
return (self.y-self.fit.params[0])/self.fit.params[1]/self.x
elif target == "residual":
return (self.y-self.fit.params[0])/self.fit.params[1]-self.x
def score(self,target="accuracy"):
if target == "accuracy":
return np.dot((self.accuracy()-1),(self.accuracy()-1))/(len(self.y)-1)
elif target == "residual":
return np.dot(self.residual(),self.residual())/(len(self.y)-1)
class calibration():
def __init__(self,df,name,sample = 'none'):
self.data_cal = df
self.data_sample = sample
self.name = name
self.nobs = len(self.data_cal.index)
self.nlevel = len(self.data_cal['x'].unique())
def accuracy(self,x,y,params):
return (y-params[0])/params[1]/x
def fit(self,optimize = True,target = "accuracy",crit = 0.15, lloq_crit = 0.2,
order = 'range' , rangemode = 'auto', selectmode = 'hloq stepdown',
lloq = 0, hloq = -1, weights = ['1','1/x^0.5','1/x','1/x^2'], fixpoints = [], model = lm,
repeat_weight = True):
# avalible order: 'range', 'weight'
# available rangemode: 'auto', 'unlimited'
# available weights: '1','1/x^0.5','1/x','1/x^2','1/y^0.5','1/y','1/y^2'
# available selectmode: 'hloq stepdown','lloq stepup','sequantial stepdownup','sequantial stepupdown'
om = op.linear(name = self.name,data_cal = self.data_cal,data_sample = self.data_sample,optimize = optimize,target = target,
crit = crit, lloq_crit = lloq_crit, order = order , rangemode = rangemode, selectmode = selectmode,
lloq = lloq, hloq = hloq, weights = weights, fixpoints = fixpoints,repeat_weight = repeat_weight)
om.fit(model)
self.model = om.model
self.data_cal['select'] = om.select_p
self.data_cal['weight'] = om.weight_type[om.weight](om.x,om.y)
print('done')
del om
def quantify(self,rangelimit):
self.data_sample['x'] = (self.data_sample['y']-self.model.fit.params[0])/self.model.fit.params[1]
if rangelimit == True:
for i in self.data_sample['x']:
if i < min(self.model.x):
self.data_sample.loc[self.data_sample['x'] == i,'x'] = '{}(< LLOQ)'.format(round(i,3))
elif i > max(self.model.x):
self.data_sample.loc[self.data_sample['x'] == i,'x'] = '{}(> HLOQ)'.format(round(i,3))
def drop_level(self,level):
self.data_cal = self.data_cal.drop(level)
self.nobs = len(self.data_cal.index)
self.nlevel = len(self.data_cal['x'].unique())
def drop_obs(self,obs):
self.data_cal = self.data_cal.drop(obs)
self.nobs = len(self.data_cal.index)
self.nlevel = len(self.data_cal['x'].unique())
class batch():
def __init__(self,data_cal = 0,data_sample = 0,data_val = 0,MultiIndex = True,index_var = 'x'):
self.data_cal = data_cal
self.data_sample = data_sample
self.data_val = data_val
self.list = []
df = self.data_cal
if MultiIndex == True:
x = [float(i) for i in list(zip(*df.index))[0]]
else:
x = [float(i) for i in df.index]
index = df.index
for i in range(len(df.columns)):
name = df.columns[i]
y = df.iloc[:,i].values
score = np.zeros(len(y))
weight = np.ones(len(y))
if index_var == 'x':
dfa = pd.DataFrame({'x': x,'y': y,'select': score, 'accuracy': score,'weight': weight},index = index)
elif index_var == 'y':
dfa = pd.DataFrame({'x': y,'y': x,'select': score, 'accuracy': score,'weight': weight},index = index)
self.list.append(calibration(dfa,name))
def add_sample(self,sample):
for i in range(len(self.list)):
index = sample.index
y = sample.iloc[:,i].values
x = np.zeros(len(y))
dfb = pd.DataFrame({'x': x,'y': y},index = index)
self.list[i].data_sample = dfb
self.data_sample = sample
def quantify(self,rangelimit = False):
self.results = self.data_sample.copy()
if rangelimit == True:
for i,j in enumerate(self.list):
j.quantify(rangelimit = True)
self.results.iloc[:,i] = j.data_sample['x']
else:
for i,j in enumerate(self.list):
j.quantify(rangelimit = False)
self.results.iloc[:,i] = j.data_sample['x']
def fit(self,optimize = True,target = "accuracy", lloq_crit = 0.2,crit = 0.15, order = 'weight' , rangemode = 'auto', selectmode = 'hloq stepdown',
lloq = 0, hloq = -1, weights = ['1','1/x^0.5','1/x','1/x^2'], fixpoints = [],model = lm,repeat_weight = True):
for i in self.list:
i.fit(optimize=optimize,target=target,lloq_crit=lloq_crit,crit=crit,order=order,rangemode=rangemode,selectmode=selectmode,
lloq=lloq, hloq=hloq, weights=weights, fixpoints=fixpoints,model=model,repeat_weight=repeat_weight)
def plot(self,n=2,neg = False,ylabel = 0, xlabel = 0):
plot_calibration_line(batch = self,n=n,neg = neg,ylabel = ylabel, xlabel = xlabel)
def build_multical(self):
def __intit__(self):
self.multical = []
df = self.data_cal
xname = list(zip(*df.index))[0]
x = list(zip(*df.index))[1]
index = df.index
for i in range(len(df.columns)):
yname = df.columns[i]
for j in xname.unique():
y = df.iloc[:,i].loc[j].values
x = list(zip(*df.loc[j].index))[1]
score = np.zeros(len(y))
weight = np.ones(len(y))
dfa = pd.DataFrame({'x': x,'y': y,'select': score, 'accuracy': score,'weight': weight},index = index)
```
#### File: labtools/labtools/plot.py
```python
from scipy.stats import ttest_ind, ttest_rel, median_test, wilcoxon, bartlett, levene, fligner
from scipy.stats import f as ftest
from scipy.stats.mstats import mannwhitneyu
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
def plot_calibration_line(batch,n=2,neg = False,ylabel = 0, xlabel = 0):
for i in range(len(batch.list)):
analyte = batch.list[i]
fig, ax = plt.subplots()
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['text.usetex'] = True
plt.rcParams['figure.figsize'] = [6*n,4*n]
plt.rcParams['font.size'] = 10*n
ax.scatter(analyte.data_cal['x'],analyte.data_cal['y'],s = 15*n,c = 'r',alpha = 0.7,marker = 'x')
lin = np.linspace(min(analyte.model.x),max(analyte.model.x),1000)
lin2 = analyte.model.fit.predict(sm.add_constant(lin))
ax.plot(lin,lin2,c = 'chartreuse',lw = 2*n,alpha = 0.7)
ax.scatter(analyte.model.x,analyte.model.y,c = 'b',s = 15*n)
plt.xlim([min(lin)-(max(lin)-min(lin))*0.1,max(lin)+(max(lin)-min(lin))*0.1])
plt.ylim([min(lin2)-(max(lin2)-min(lin2))*0.1,max(lin2)+(max(lin2)-min(lin2))*0.1])
if xlabel == 0:
ax.set_xlabel('{} concentration (ng/mL)'.format(analyte.name))
else:
ax.set_xlabel(xlabel[i])
if ylabel == 0:
ax.set_ylabel('Corrected signal')
else:
ax.set_ylabel(ylabel[i])
if not neg:
ax.annotate(r'$y = {}+{}x$'.format(round(analyte.model.fit.params[0],3),round(analyte.model.fit.params[1],3)),
xy = ((max(lin)+3*min(lin))/4,(3*max(analyte.model.y)+min(analyte.model.y))/4))
ax.annotate(r'$r^2 = {}$'.format(round(analyte.model.fit.rsquared,3)),
xy = ((max(lin)+3*min(lin))/4,(2.7*max(analyte.model.y)+1.3*min(analyte.model.y))/4))
else:
ax.annotate(r'$y = {}+{}x$'.format(round(analyte.model.fit.params[0],3),round(analyte.model.fit.params[1],3)),
xy = ((3*max(lin)+min(lin))/4,(3*max(analyte.model.y)+min(analyte.model.y))/4))
ax.annotate(r'$r^2 = {}$'.format(round(analyte.model.fit.rsquared,3)),
xy = ((3*max(lin)+min(lin))/4,(2.7*max(analyte.model.y)+1.3*min(analyte.model.y))/4))
plt.tight_layout()
plt.show()
def starplot(df = [],x = '',y = '',data = [],index = [],columns = [],
fold = False,foldcol = 0,mode = 3, errorbar = True,
plottype = 'barplot', stats = 'independent t test',
test_var = False, stats_var = 'f test', crit_var = 0.05, equal_var = True,
rotate = 0, elinewidth = 0.5, fontsize = 14, capsize = 4,
noffset_ylim = 35, noffset_fst = 10,noffset_diff = 10,star_size = 3,linewidth = 1,
crit = [0.05,0.01,0.001,0.0001]):
# data: list of data matrixs(or DataFrames) for comparison (row: obs, columns: var)
# index: var, columns: obs
# adjacent: annotate star for adjacent bar
# control: annotate star between all other bars to selctive control bar
# mix: mix mode
# 3: annotate star for all combination of bar (only 3 bars available)
crit = np.array(crit)
plt.rcParams['font.family'] = 'Times New Roman'
fig,ax = plt.subplots()
star = ['*','**','***','****']
n = len(data)
m = data[0].shape[1]
test = pd.DataFrame()
for i,j in enumerate(data):
if type(test) == type(j):
data[i] = j.values.reshape(len(j.index),len(j.columns))
if plottype == 'barplot':
error = pd.DataFrame()
mean = pd.DataFrame()
for i in range(m):
error[i] = [data[j][:,i].std() for j in range(n)]
mean[i] = [data[j][:,i].mean() for j in range(n)]
error = error.transpose()
mean = mean.transpose()
if len(index) != 0:
error.index = index
mean.index = index
if len(columns) != 0:
error.columns = columns
mean.columns = columns
if fold == True:
oldmean = mean.copy()
olderror = error.copy()
for i in range(len(mean.columns)):
mean.iloc[:,i] = oldmean.iloc[:,i]/oldmean.iloc[:,foldcol]
error.iloc[:,i] = olderror.iloc[:,i]/oldmean.iloc[:,foldcol]
if errorbar == True:
plot = plot = mean.plot.bar(yerr = error,ax = ax,rot=rotate,capsize = capsize,
error_kw=dict(elinewidth = elinewidth),fontsize = fontsize)
max_bar = [[mean.iloc[j,i]+error.iloc[j,i] for i in range(n)] for j in range(m)]
min_bar = [mean.iloc[j,i]-error.iloc[j,i] for i in range(n) for j in range(m)]
else:
plot = plot = mean.plot.bar(ax = ax,rot=rotate,capsize = capsize,
error_kw=dict(elinewidth = elinewidth),fontsize = fontsize)
max_bar = [[mean.iloc[j,i] for i in range(n)] for j in range(m)]
min_bar = [mean.iloc[j,i] for i in range(n) for j in range(m)]
elif plottype == 'boxplot':
print("under buiding")
ylim = 0
offset = max([max_bar[i][j] for i in range(m) for j in range(n)])/100
blank = []
if mode == 3:
for j in range(m):
level = np.zeros(n)
for i in range(n):
if i < n-1:
k = i+1
else:
k = 0
if test_var == True:
if stats_var == 'f test':
f = 0.5-abs(0.5-ftest.sf(data[i][:,j].var()/data[k][:,j].var(),len(data[i][:,j])-1,len(data[k][:,j])-1))
if crit_var/2 > f:
equal_var = False
else:
equal_var = True
else:
if stats_var == 'bartlett':
f = bartlett(data[i][:,j],data[k][:,j])[1]
elif stats_var == 'levene':
f = bartlett(data[i][:,j],data[k][:,j])[1]
elif stats_var == 'fligner':
f = fligner(data[i][:,j],data[k][:,j])[1]
if crit_var > f:
equal_var = False
else:
equal_var = True
if stats == 'independent t test':
p = ttest_ind(data[i][:,j],data[k][:,j],equal_var = equal_var)[1]
elif stats == 'paired t test':
if equal_var == True:
p = ttest_rel(data[i][:,j],data[k][:,j])[1]
else:
p = 0
elif stats == 'median test':
p = median_test(data[i][:,j],data[k][:,j])[1]
elif stats == 'mannwhitneyu':
if equal_var == True:
p = mannwhitneyu(data[i][:,j],data[k][:,j])[1]
else:
p = 0
elif stats == 'wilcoxon':
if equal_var == True:
p = wilcoxon(data[i][:,j],data[k][:,j])[1]
else:
p = 0
level[i] = len(crit) - len(crit.compress(p > crit))
for k in range(n):
height = 0
if level[k] != 0 and k != n-1:
center = [plot.patches[k*m+j].get_x(), plot.patches[k*m+m+j].get_x()]
height = max([max_bar[j][k],max_bar[j][k+1]])
h1 = max_bar[j][k]
h2 = max_bar[j][k+1]
width = plot.patches[k*m+j].get_width()
blank.append((center[0]+width/2,height+noffset_fst*offset+(-1)**k*2*offset))
blank.append((center[1]+width/2,height+noffset_fst*offset+(-1)**k*2*offset))
ax.vlines(x = center[0]+width/2,ymin = h1+offset*2,ymax = height+noffset_fst*offset+(-1)**k*2*offset,lw = linewidth)
ax.vlines(x = center[1]+width/2,ymin = h2+offset*2,ymax = height+noffset_fst*offset+(-1)**k*2*offset,lw = linewidth)
ax.annotate(star[int(level[k]-1)],
xy = ((center[0]+center[1])/2+width/2,height+(noffset_fst+1)*offset+(-1)**k*2*offset),
ha='center',size = star_size)
elif level[k] != 0 and k == n-1:
center = [plot.patches[j].get_x(), plot.patches[k*m+j].get_x()]
height = max(max_bar[j])
h1 = max_bar[j][0]
h2 = max_bar[j][k]
blank.append((center[0]+width/2,height+(noffset_fst+noffset_diff)*offset))
blank.append((center[1]+width/2,height+20*offset))
ax.vlines(x = center[0]+width/2,ymin = h1+offset*2,ymax = height+(noffset_fst+noffset_diff)*offset,lw = linewidth)
ax.vlines(x = center[1]+width/2,ymin = h2+offset*2,ymax = height+(noffset_fst+noffset_diff)*offset,lw = linewidth)
ax.annotate(star[int(level[k]-1)],
xy = ((center[0]+center[1])/2+width/2,height+(noffset_fst+noffset_diff+1)*offset),
ha='center',size = star_size)
if height > ylim:
ylim = height
if mode == 'adjacent':
for j in range(m):
level = np.zeros(n-1)
for i in range(n-1):
k = i+1
if test_var == True:
if stats_var == 'f test':
f = 0.5-abs(0.5-ftest.sf(data[i][:,j].var()/data[k][:,j].var(),len(data[i][:,j])-1,len(data[k][:,j])-1))
if crit_var/2 > f:
equal_var = False
else:
equal_var = True
else:
if stats_var == 'bartlett':
f = bartlett(data[i][:,j],data[k][:,j])[1]
elif stats_var == 'levene':
f = bartlett(data[i][:,j],data[k][:,j])[1]
elif stats_var == 'fligner':
f = fligner(data[i][:,j],data[k][:,j])[1]
if crit_var > f:
equal_var = False
else:
equal_var = True
if stats == 'independent t test':
p = ttest_ind(data[i][:,j],data[k][:,j],equal_var = equal_var)[1]
elif stats == 'paired t test':
if equal_var == True:
p = ttest_rel(data[i][:,j],data[k][:,j])[1]
else:
p = 0
elif stats == 'median test':
p = median_test(data[i][:,j],data[k][:,j])[1]
elif stats == 'mannwhitneyu':
if equal_var == True:
p = mannwhitneyu(data[i][:,j],data[k][:,j])[1]
else:
p = 0
elif stats == 'wilcoxon':
if equal_var == True:
p = wilcoxon(data[i][:,j],data[k][:,j])[1]
else:
p = 0
level[i] = len(crit) - len(crit.compress(p > crit))
for k in range(n-1):
height = 0
if level[k] != 0:
center = [plot.patches[k*m+j].get_x(), plot.patches[k*m+m+j].get_x()]
height = max([max_bar[j][k],max_bar[j][k+1]])
h1 = max_bar[j][k]
h2 = max_bar[j][k+1]
width = plot.patches[k*m+j].get_width()
blank.append((center[0]+width/2,height+noffset_fst*offset+(-1)**k*2*offset))
blank.append((center[1]+width/2,height+noffset_fst*offset+(-1)**k*2*offset))
ax.vlines(x = center[0]+width/2,ymin = h1+offset*2,ymax = height+noffset_fst*offset+(-1)**k*2*offset,lw = linewidth)
ax.vlines(x = center[1]+width/2,ymin = h2+offset*2,ymax = height+noffset_fst*offset+(-1)**k*2*offset,lw = linewidth)
ax.annotate(star[int(level[k]-1)],
xy = ((center[0]+center[1])/2+width/2,height+(noffset_fst+1)*offset+(-1)**k*2*offset),
ha='center',size = star_size)
if height > ylim:
ylim = height
ax.set_ylim(min(0,min(min_bar)-10*offset),ylim+noffset_ylim*offset)
for j,i in enumerate(blank):
ax.vlines(x = i[0], ymin = i[1],ymax = i[1]+offset*2,color = 'white',lw = 1.2*linewidth)
if j%2 == 1:
ax.hlines(y = i[1], xmin = blank[j-1], xmax = blank[j],lw = linewidth)
```
|
{
"source": "jekabsGritans/multi_user_steam_to_shield",
"score": 3
}
|
#### File: multi_user_steam_to_shield/wip/igdb.py
```python
from json import loads
from requests import post
from os.path import isfile as exists
def get_access_token(secret,id):
r = post(f"https://id.twitch.tv/oauth2/token?client_id={id}&client_secret={secret}&grant_type=client_credentials")
j = loads(r.text)
token = j['access_token']
with open('token','w') as f:
f.write(token)
return token
if exists('id'):
with open('id','r') as f:
id = f.read()
else:
print("Find out more about getting the ID and Secret - https://api-docs.igdb.com/#about")
id = input("Enter your twitch app id: ")
with open('id','w') as f:
f.write(id)
if exists('secret'):
with open('secret','r') as f:
secret = f.read()
else:
print("Find out more about getting the ID and Secret - https://api-docs.igdb.com/#about")
secret = input("Enter your twitch app secret: ")
with open('secret','w') as f:
f.write(secret)
if exists('token'):
with open('token','r') as f:
token = f.read()
else:
token = get_access_token(secret,id)
titles = ['csgo','Battlefield V']
HEADERS = {"Client-ID":id,"Authorization":f"Bearer {token}"}
```
|
{
"source": "jekader/fake_ilo",
"score": 3
}
|
#### File: jekader/fake_ilo/ilo.py
```python
import libvirt,time
from socket import *
from ssl import *
def print_vm_status(vmname):
# connect to ovirt
domains = { }
conn = libvirt.open('qemu:///system')
#active domains
active_ids = conn.listDomainsID()
for id in active_ids:
dom = conn.lookupByID(id)
id_str = str(id)
name = dom.name()
domains[name] = dom
# inactive domains
for name in conn.listDefinedDomains():
dom = conn.lookupByName(name)
domains[name] = dom
if vmname in domains:
if domains[vmname].isActive():
return "on"
else:
return "off"
else:
return "NaN"
def set_vm_status(vmname,vmstatus):
# check if VM is already in desired status, just return result if yes
if print_vm_status(vmname).lower() == vmstatus.lower():
return vmstatus
else:
#do actual fencing here
if print_vm_status(vmname) in ('on','off'):
conn = libvirt.open('qemu:///system')
dom = conn.lookupByName(vmname)
if vmstatus == "off":
dom.destroy()
return "off"
if vmstatus == "on":
dom.create()
return "on"
else:
#return error if VM not present
return "NaN"
def logprint(msg):
logfile = open('/var/log/fake_ilo.log','a')
logline = time.strftime("[%Y-%m-%d %H:%M:%S] - ") + msg + "\n"
logfile.write(logline)
logfile.close()
#create socket
server_socket=socket(AF_INET, SOCK_STREAM)
username = ''
#Bind to an unused port on the local machine
server_socket.bind(('',1234))
#listen for connection
server_socket.listen (1)
tls_server = wrap_socket(server_socket, ssl_version=PROTOCOL_SSLv23, cert_reqs=CERT_NONE, server_side=True, keyfile='/etc/fake_ilo/server.key', certfile='/etc/fake_ilo/server.crt')
logprint('server started')
while True:
#accept connection
connection, client_address= tls_server.accept()
#server is not finished
finnished =False
emptyresponse=0
#while not finished
while not finnished:
#send and receive data from the client socket
data_in=connection.recv(1024)
message=data_in.decode()
if message=='quit':
finnished= True
else:
#login = VM name
if message.find('USER_LOGIN') > 1:
username=message.split()[3].replace('"', '')
if message.find('xml') > 1:
response='<RIBCL VERSION="2.0"></RIBCL>'
data_out=response.encode()
connection.send(data_out)
# return firmware version
if message.find('GET_FW_VERSION') > 1:
response='<GET_FW_VERSION\r\n FIRMWARE_VERSION="1.91"\r\n MANAGEMENT_PROCESSOR="2.22"\r\n />'
data_out=response.encode()
connection.send(data_out)
# get power status
if message.find('GET_HOST_POWER_STATUS') > 1:
response='HOST_POWER="' + print_vm_status(username) + '"'
logprint('received status request for '+username+' from '+client_address[0]+':'+str(client_address[1])+' - responding with: ' + print_vm_status(username))
data_out=response.encode()
connection.send(data_out)
# set power status
if message.find('SET_HOST_POWER') > 1:
power=message.split()[6].replace('"', '')
response='HOST_POWER="' + set_vm_status(username,power) + '"'
logprint('received fencing command for '+username+' from '+client_address[0]+':'+str(client_address[1])+' - requested status: '+power+ ', status after fencing is: ' + print_vm_status(username))
data_out=response.encode()
connection.send(data_out)
# filter out the rest
else:
if len(message) > 0:
do_nothing = 0
else:
emptyresponse+=1
if emptyresponse > 30:
finnished=True
#close the connection
connection.shutdown(SHUT_RDWR)
connection.close()
#close the server socket
server_socket.shutdown(SHUT_RDWR)
server_socket.close()
```
|
{
"source": "jek/alfajor",
"score": 2
}
|
#### File: alfajor/browsers/_waitexpr.py
```python
__all__ = 'WaitExpression', 'SeleniumWaitExpression'
OR = object()
class WaitExpression(object):
"""Generic wait_for expression generator and compiler.
Expression objects chain in a jQuery/SQLAlchemy-esque fashion::
expr = (browser.wait_expression().
element_present('#druid').
ajax_complete())
Or can be configured at instantiation:
expr = browser.wait_expression(['element_present', '#druid'],
['ajax_complete'])
Expression components are and-ed (&&) together. To or (||), separate
components with :meth:`or_`::
element_present('#druid').or_().ajax_complete()
The expression object can be supplied to any operation which accepts
a ``wait_for`` argument.
"""
def __init__(self, *expressions):
for spec in expressions:
directive = spec[0]
args = spec[1:]
getattr(self, directive)(*args)
def or_(self):
"""Combine the next expression with an OR instead of default AND."""
return self
def element_present(self, finder):
"""True if *finder* is present on the page.
:param finder: a CSS selector or document element instance
"""
return self
def element_not_present(self, expr):
"""True if *finder* is not present on the page.
:param finder: a CSS selector or document element instance
"""
return self
def evaluate_element(self, finder, expr):
"""True if *finder* is present on the page and evaluated by *expr*.
:param finder: a CSS selector or document element instance
:param expr: literal JavaScript text; should evaluate to true or
false. The variable ``element`` will hold the *finder* DOM element,
and ``window`` is the current window.
"""
return self
def ajax_pending(self):
"""True if jQuery ajax requests are pending."""
return self
def ajax_complete(self):
"""True if no jQuery ajax requests are pending."""
return self
def __unicode__(self):
"""The rendered value of the expression."""
return u''
class SeleniumWaitExpression(WaitExpression):
"""Compound wait_for expression compiler for Selenium browsers."""
def __init__(self, *expressions):
self._expressions = []
WaitExpression.__init__(self, *expressions)
def or_(self):
self._expressions.append(OR)
return self
def element_present(self, finder):
js = self._is_element_present('element_present', finder, 'true')
self._expressions.append(js)
return self
def element_not_present(self, finder):
js = self._is_element_present('element_not_present', finder, 'false')
self._expressions.append(js)
return self
def evaluate_element(self, finder, expr):
locator = to_locator(finder)
log = evaluation_log('evaluate_element', 'result', locator, expr)
js = """\
(function () {
var element;
try {
element = selenium.browserbot.findElement('%s');
} catch (e) {
element = null;
};
var result = false;
if (element != null)
result = %s;
%s
return result;
})()""" % (js_quote(locator), expr, log)
self._expressions.append(js)
return self
def ajax_pending(self):
js = """\
(function() {
var pending = window.jQuery && window.jQuery.active != 0;
%s
return pending;
})()""" % predicate_log('ajax_pending', 'complete')
self._expressions.append(js)
return self
def ajax_complete(self):
js = """\
(function() {
var complete = window.jQuery ? window.jQuery.active == 0 : true;
%s
return complete;
})()""" % predicate_log('ajax_complete', 'complete')
self._expressions.append(js)
return self
def _is_element_present(self, label, finder, result):
locator = to_locator(finder)
log = evaluation_log(label, 'found', locator)
return u"""\
(function () {
var found = true;
try {
selenium.browserbot.findElement('%s');
} catch (e) {
found = false;
};
%s
return found == %s;
})()""" % (js_quote(locator), log, result)
def __unicode__(self):
last = None
components = []
for expr in self._expressions:
if expr is OR:
components.append(u'||')
else:
if last not in (None, OR):
components.append(u'&&')
components.append(expr)
last = expr
predicate = u' '.join(components).replace('\n', ' ')
return predicate
def js_quote(string):
"""Prepare a string for use in a 'single quoted' JS literal."""
string = string.replace('\\', r'\\')
string = string.replace('\'', r'\'')
return string
def to_locator(expr):
"""Convert a css selector or document element into a selenium locator."""
if isinstance(expr, basestring):
return 'css=' + expr
elif hasattr(expr, '_locator'):
return expr._locator
else:
raise RuntimeError("Unknown page element %r" % expr)
def predicate_log(label, result_variable):
"""Return JS for logging a boolean result test in the Selenium console."""
js = "LOG.info('wait_for %s ==' + %s);" % (
js_quote(label), result_variable)
return js
def evaluation_log(label, result_variable, *args):
"""Return JS for logging an expression eval in the Selenium console."""
inner = ', '.join(map(js_quote, args))
js = "LOG.info('wait_for %s(%s)=' + %s);" % (
js_quote(label), inner, result_variable)
return js
```
|
{
"source": "jekalmin/HASS-Line-Bot",
"score": 2
}
|
#### File: custom_components/line_bot/http.py
```python
import logging
import json
from typing import Any, Dict
from homeassistant.const import CONF_TOKEN
from homeassistant.components.http import HomeAssistantView
from homeassistant.core import HomeAssistant, callback
from homeassistant.util.decorator import Registry
from urllib.parse import parse_qsl
from aiohttp.web import Request, Response
from aiohttp.web_exceptions import HTTPBadRequest
from .const import (
DOMAIN, CONF_SECRET, CONF_ALLOWED_CHAT_IDS, EVENT_WEBHOOK_TEXT_RECEIVED, EVENT_WEBHOOK_POSTBACK_RECEIVED
)
from linebot import (
LineBotApi, WebhookParser
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
SourceUser, SourceGroup, SourceRoom,
TemplateSendMessage, ConfirmTemplate, MessageAction,
ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
PostbackAction, DatetimePickerAction,
CameraAction, CameraRollAction, LocationAction,
CarouselTemplate, CarouselColumn, PostbackEvent,
StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
ImageMessage, VideoMessage, AudioMessage, FileMessage,
UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
MemberJoinedEvent, MemberLeftEvent,
FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent,
TextComponent, SpacerComponent, IconComponent, ButtonComponent,
SeparatorComponent, QuickReply, QuickReplyButton,
ImageSendMessage
)
HANDLERS = Registry()
_LOGGER = logging.getLogger(__name__)
@callback
def async_register_http(hass: HomeAssistant, config: Dict[str, Any]):
lineBotConfig = LineBotConfig(hass, config)
hass.http.register_view(LineWebhookView(lineBotConfig))
class LineBotConfig:
def __init__(self, hass: HomeAssistant, config: Dict[str, Any]):
"""Initialize the config."""
self.hass = hass
self.config = config
self.channel_access_token = config[DOMAIN].get(CONF_TOKEN)
self.channel_secret = config[DOMAIN].get(CONF_SECRET)
self.allowed_chat_ids = config[DOMAIN].get(CONF_ALLOWED_CHAT_IDS, {})
class LineWebhookView(HomeAssistantView):
url = "/api/line/callback"
name = "api:line_bot"
requires_auth = False
def __init__(self, config: LineBotConfig):
self.config = config
self.line_bot_api = LineBotApi(config.channel_access_token)
self.parser = WebhookParser(config.channel_secret)
async def post(self, request: Request) -> Response:
"""Handle Webhook"""
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
body = await request.text()
# parse webhook body
try:
events = self.parser.parse(body, signature)
except InvalidSignatureError:
raise HTTPBadRequest()
for event in events:
if self.is_test(event.reply_token):
return 'OK'
if not self.is_allowed(event):
self.notify(event)
raise HTTPBadRequest()
handler_keys = [event.__class__.__name__]
if hasattr(event, 'message'):
handler_keys.append(event.message.__class__.__name__)
handler = HANDLERS.get("_".join(handler_keys))
handler(self.config.hass, self.line_bot_api, event)
return 'OK'
def is_test(self, reply_token):
if reply_token == '00000000000000000000000000000000':
return True
return False
def get_chat_id(self, source):
if source.type == 'user':
return source.user_id
elif source.type == 'group':
return source.group_id
elif source.type == 'room':
return source.room_id
return None
def is_allowed(self, event):
return self.get_chat_id(event.source) in self.config.allowed_chat_ids.values()
def notify(self, event):
chat_id = self.get_chat_id(event.source)
event_json = json.dumps(event, default=lambda x: x.__dict__, ensure_ascii=False)
message = f"chat_id: {chat_id}\n\nevent: {event_json}"
self.config.hass.components.persistent_notification.create(message, title="LineBot Request From Unknown ChatId", notification_id=chat_id)
@HANDLERS.register("MessageEvent_TextMessage")
def handle_message(hass: HomeAssistant, line_bot_api: LineBotApi, event: MessageEvent):
text = event.message.text
if text == 'bye':
exit_chat(line_bot_api, event)
return
hass.bus.fire(EVENT_WEBHOOK_TEXT_RECEIVED, {
'reply_token': event.reply_token,
'event': event.as_json_dict(),
'content': event.message.as_json_dict(),
'text': event.message.text
})
@HANDLERS.register("PostbackEvent")
def handle_message(hass: HomeAssistant, line_bot_api: LineBotApi, event: PostbackEvent):
hass.bus.fire(EVENT_WEBHOOK_POSTBACK_RECEIVED, {
'reply_token': event.reply_token,
'event': event.as_json_dict(),
'content': event.postback.as_json_dict(),
'data': event.postback.data,
'data_json': dict(parse_qsl(event.postback.data)),
'params': event.postback.params
})
def exit_chat(line_bot_api: LineBotApi, event: MessageEvent):
if isinstance(event.source, SourceGroup):
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text='Leaving group'))
line_bot_api.leave_group(event.source.group_id)
elif isinstance(event.source, SourceRoom):
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text='Leaving group'))
line_bot_api.leave_room(event.source.room_id)
else:
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text="Bot can't leave from 1:1 chat"))
```
|
{
"source": "JekaMas/ether_tester",
"score": 2
}
|
#### File: ether_tester/tester/status.py
```python
from .geth import Geth
# todo: implement
class Status(Geth):
'docker build -f {status_path} -t status_image:{tag} .'
def __init__(self, eth_host_volume_path, container_command=None, version='latest', description=None, init_time=1,
is_wait_sync=False):
port = Geth.port_default + Geth.port.increment()
json_rpc_port = Geth.json_rpc_port_default + Geth.json_rpc_port.increment()
docker_command = 'docker run -i --rm -p {json_rpc_port}:8545 -p {port}:30303 ' \
'-v {eth_host_volume_path}:/root/.ethereum'.format(
json_rpc_port=json_rpc_port, port=port, eth_host_volume_path=eth_host_volume_path)
if container_command is None:
container_command = Geth.ropsten_defaults
container_command = "ethereum/client-go:{version} {container_command}".format(version=version,
container_command=container_command)
container_command += " --rpc --rpcaddr \"0.0.0.0\" --verbosity 2 console"
self.docker_command = docker_command
self.container_command = container_command
self.description = description
self.init_time = init_time
self.is_wait_sync = is_wait_sync
super().__init__(self.docker_command, self.container_command, self.description, self.init_time)
```
|
{
"source": "JekaREMIXX/easyeditorphoto",
"score": 3
}
|
#### File: JekaREMIXX/easyeditorphoto/main.py
```python
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PIL import Image
from PIL import ImageFilter
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QListWidget, QLineEdit, QTextEdit, QInputDialog, QHBoxLayout, QVBoxLayout, QFormLayout,QFileDialog
import os
app = QApplication([])
main_win = QWidget()
main_win.show()
main_win.setWindowTitle("Easy Editor")
main_win.resize(700,500)
#кнопка папка
button1=QPushButton("Папка")
#список выбора фото
listphoto=QListWidget()
#картинка
photo=QLabel("Картинка")
#набор кнопок
buttonleft=QPushButton("Лево")
buttonright=QPushButton("Право")
buttonzerkalo=QPushButton("Зеркало")
buttonrezkoct=QPushButton("Резкость")
button4b=QPushButton("Ч/Б")
line1=QVBoxLayout()
line2=QVBoxLayout()
line3=QHBoxLayout()
line4=QHBoxLayout()
line1.addWidget(button1)
line1.addWidget(listphoto)
line2.addWidget(photo)
line3.addWidget(buttonleft)
line3.addWidget(buttonright)
line3.addWidget(buttonzerkalo)
line3.addWidget(buttonrezkoct)
line3.addWidget(button4b)
line4.addLayout(line1)
line2.addLayout(line3)
line4.addLayout(line2)
main_win.setLayout(line4)
workdir= ""
class ImageProessor():
def __init__(self):
self.image=None
self.currentimagename=None
self.folder=None
self.namefolder="photos"
def showImage(self,path):
photo.hide()
pixmapimage=QPixmap(path)
w,h=photo.width(), photo.height()
pixmapimage=pixmapimage.scaled(w, h, Qt.KeepAspectRatio)
photo.setPixmap(pixmapimage)
photo.show()
def loadImage(self,currentimagename):
self.currentimagename=currentimagename
photo=os.path.join(workdir,currentimagename)
self.image=Image.open(photo)
def saveImage(self):
path=os.path.join(workdir,self.namefolder)
if not(os.path.exists(path) or os.path.isdir(path)):
os.mkdir(path)
image_path=os.path.join(path, self.currentimagename)
self.image.save(image_path)
def do_flip(self):
self.image=self.image.transpose(Image.FLIP_LEFT_RIGHT)
self.saveImage()
image_path=os.path.join(workdir,self.namefolder,self.currentimagename)
self.showImage(image_path)
def do_bw(self):
self.image=self.image.convert("L")
self.saveImage()
image_path=os.path.join(workdir,self.namefolder,self.currentimagename)
self.showImage(image_path)
def left(self):
self.image=self.image.transpose(Image.ROTATE_270)
self.saveImage()
image_path=os.path.join(workdir,self.namefolder,self.currentimagename)
self.showImage(image_path)
def right(self):
self.image=self.image.transpose(Image.ROTATE_90)
self.saveImage()
image_path=os.path.join(workdir,self.namefolder,self.currentimagename)
self.showImage(image_path)
def rezkoct(self):
self.image=self.image.filter(ImageFilter.SHARPEN)
self.saveImage()
image_path=os.path.join(workdir,self.namefolder,self.currentimagename)
self.showImage(image_path)
workimage= ImageProessor()
def chooseWorkdir():
global workdir
workdir=QFileDialog.getExistingDirectory()
def filter(files,extensions):
result=[]
for photo1 in files:
for photo2 in extensions:
if photo1.endswith(photo2):
result.append(photo1)
return(result)
def showFilenamesList():
chooseWorkdir()
filenames=os.listdir(workdir)
expansions=[".jpg",".png",".jpeg",".gif",".bmp"]
save1=filter(filenames,expansions)
listphoto.clear()
for sa in save1:
listphoto.addItem(sa)
button1.clicked.connect(showFilenamesList)
def showChosenImage():
if listphoto.currentRow() >=0:
folder= listphoto.currentItem().text()
workimage.loadImage(folder)
photo=os.path.join(workdir,workimage.currentimagename)
workimage.showImage(photo)
listphoto.currentRowChanged.connect(showChosenImage)
buttonzerkalo.clicked.connect(workimage.do_flip)
button4b.clicked.connect(workimage.do_bw)
buttonleft.clicked.connect(workimage.left)
buttonright.clicked.connect(workimage.right)
buttonrezkoct.clicked.connect(workimage.rezkoct)
app.exec_()
```
|
{
"source": "JekaREMIXX/shootergame",
"score": 3
}
|
#### File: JekaREMIXX/shootergame/shooter_game.py
```python
from pygame import *
import random
from time import time as t
font.init()
font=font.SysFont('Arial', 40)
window = display.set_mode((700,500))
display.set_caption("pygame window")
background =transform.scale(image.load("galaxy.jpg"), (700,500))
rocket=transform.scale(image.load("rocket.png"), (100,100))
bullet =transform.scale(image.load("bullet.png"), (25,25))
ufo =transform.scale(image.load("ufo.png"), (100,100))
asteroid=transform.scale(image.load("asteroid.png"), (100,100))
x1=300
y1=400
x2=300
y2=10
x3=1
y3=1
speed=10
speed_player=10
class GameSprite(sprite.Sprite):
def __init__(self,rocket,x1,y1,speed):
super().__init__()
self.image = rocket
self.speed = speed_player
self.rect = self.image.get_rect()
self.rect.x = x1
self.rect.y = y1
def reset(self):
window.blit(self.image, (self.rect.x,self.rect.y))
class Player(GameSprite):
global bullet
def update(self):
keys_pressed = key.get_pressed()
if keys_pressed[K_LEFT] and self.rect.x >5:
self.rect.x -=10
if keys_pressed[K_RIGHT] and self.rect.x <600:
self.rect.x +=10
def fire(self):
bullet1= Bullet(bullet, self.rect.centerx,self.rect.top,-15)
bullets.add(bullet1)
ammo=5
numammo=0
score=0
lost=0
waitseconds=t()
wait=False
direction="down"
textscore=font.render("Счет: " + str(score), 1, (255, 255, 255))
textlose=font.render("Пропущено: " + str(lost), 1, (255, 255, 255))
finishlose=font.render("YOU LOSE", 1, (255, 0, 0))
finishwin=font.render("YOU WIN", 1, (255, 0, 0))
class Enemy(GameSprite):
def update(self):
global direction
global lost
speed=2
if direction=="down":
self.rect.y +=random.randint(1,5)
if self.rect.y>600:
self.rect.y =0
lost = lost+1
self.rect.x = random.randint(10,600)
class Asteroid(GameSprite):
def update(self):
global direction
global lost
speed=2
if direction=="down":
self.rect.y +=random.randint(1,5)
if self.rect.y>600:
self.rect.y =0
lost = lost+1
self.rect.x = random.randint(10,600)
class Bullet(GameSprite):
def update(self):
speed=8
direction="up"
if direction=="up":
self.rect.y -=1
if self.rect.y<5:
self.kill()
finish=False
game=True
clock = time.Clock()
FPS = 60
monsters=sprite.Group()
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
asteroids=sprite.Group()
asteroids.add(Asteroid(asteroid,random.randint(10,600),y2,speed))
asteroids.add(Asteroid(asteroid,random.randint(10,600),y2,speed))
asteroids.add(Asteroid(asteroid,random.randint(10,600),y2,speed))
bullets=sprite.Group()
gamesprite1 = Player(rocket,x1,y1,speed)
gamesprite2 = Player(ufo,x1,y1,speed)
gamesprite3 = Enemy(ufo,random.randint(10,600),y2,speed)
gamesprite4 = Bullet(bullet,x1,y1,speed)
gamesprite5 = Asteroid(asteroid,random.randint(10,600),y2,speed)
while game:
for e in event.get():
if e.type == QUIT:
game = False
if e.type == KEYDOWN:
if e.key == K_SPACE:
if ammo>=0 and wait==False:
gamesprite1.fire()
ammo=ammo-1
if ammo<=0 and wait==False:
waitseconds=t()
wait=True
timer=t()
if timer-waitseconds>=1 and wait==True:
ammo=5
wait=False
if finish != True:
window.blit(background,(0,0))
clock.tick(FPS)
gamesprite1.reset()
gamesprite1.update()
monsters.draw(window)
monsters.update()
asteroids.draw(window)
asteroids.update()
bullets.draw(window)
bullets.update()
if sprite.groupcollide(monsters, bullets, True, True):
score = score+1
monsters.add(Enemy(ufo,random.randint(10,600),y2,speed))
textscore=font.render("Счет: " + str(score), 1, (255, 255, 255))
textlose=font.render("Пропущено: " + str(lost), 1, (255, 255, 255))
if lost>3 or sprite.spritecollide(gamesprite1, monsters, True):
window.blit(finishlose,(300, 300))
finish = True
if lost>3 or sprite.spritecollide(gamesprite1, asteroids, True):
window.blit(finishlose,(300, 300))
finish = True
if score==10:
window.blit(finishwin,(300, 300))
finish = True
window.blit(textscore,(10, 20))
window.blit(textlose,(10, 50))
display.update()
```
|
{
"source": "JekaREMIXX/test",
"score": 3
}
|
#### File: JekaREMIXX/test/Untitled.py
```python
from pygame import *
import random
from time import time as t
font.init()
font=font.SysFont('Arial', 40)
window = display.set_mode((700,500))
display.set_caption("pygame window")
background =transform.scale(image.load("fon.png"), (700,500))
class GameSprite(sprite.Sprite):
def __init__(self,rocket,x1,y1,speed):
super().__init__()
self.image = 1
self.speed = 1
self.rect = self.image.get_rect()
self.rect.x = x1
self.rect.y = y1
def reset(self):
window.blit(self.image, (self.rect.x,self.rect.y))
class Player(GameSprite):
def update(self):
keys_pressed = key.get_pressed()
if keys_pressed[K_LEFT] and self.rect.x >5:
self.rect.x -=10
if keys_pressed[K_RIGHT] and self.rect.x <600:
self.rect.x +=10
def fire(self):
bullet1= Bullet(bullet, self.rect.centerx,self.rect.top,-15)
bullets.add(bullet1)
game=True
finish=False
while game:
for e in event.get():
if e.type == QUIT:
game = False
window.blit(background,(0,0))
display.update()
```
|
{
"source": "jekaterinak/mantis",
"score": 2
}
|
#### File: mantis/fixture/application.py
```python
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.project import ProjectHelper
from fixture.james import JamesHelper
from fixture.signup import SignupHelper
from fixture.mail import MailHelper
from fixture.soap import SoapHelper
import re
class Application:
def __init__(self, browser, config):
if browser == "firefox":
self.wd = webdriver.Firefox(capabilities={"marionette": False})
elif browser == "chrome":
self.wd = webdriver.Chrome()
elif browser == "ie":
self.wd = webdriver.Ie()
else:
raise ValueError("Unrecognized browser %s" % browser)
self.session = SessionHelper(self)
self.project = ProjectHelper(self)
self.james = JamesHelper(self)
self.signup = SignupHelper(self)
self.mail = MailHelper(self)
self.soap = SoapHelper(self, config["soap"])
self.config = config
self.base_url = config['web']['base_URL']
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False
def open_home_page(self):
if not (self.wd.current_url.endswith("/addressbook/") and len(
self.wd.find_elements_by_id("search-az")) > 0):
self.wd.get(self.base_url)
def clear_phones(self, s):
return re.sub("[() -]", "", s)
def remove_spaces(self, t):
trimmed = t.strip()
return re.sub("[ ]+", " ", trimmed)
def destroy(self):
self.wd.quit()
```
#### File: mantis/model/project.py
```python
class Project:
def __init__(self, id=None, project_name=None, status="development", enabled=True, inherit_global=True, view_status="public",
description=None):
self.project_name = project_name
self.status = status
self.enabled = enabled
self.inherit_global = inherit_global
self.view_status = view_status
self.description = description
self.id = id
def __repr__(self):
return '%s:%s' % (self.project_name, self.description)
def __eq__(self, other):
res = (self.project_name == other.project_name and self.status == other.status \
and self.enabled == other.enabled and self.view_status == other.view_status and \
self.description == other.description)
return res
def pr_name(self):
return self.project_name
```
|
{
"source": "jekaterinak/python_training",
"score": 3
}
|
#### File: python_training/data/contact.py
```python
import random
import string
from model.contact import Contact
constant = [
Contact(firstname="firstname1", lastname="lastname1", address="address1", homephone="1",
mobilephone="2", workphone="3", email="email1", email2="email1", email3="email1"),
Contact(firstname="firstname2", lastname="lastname2", address="address2", homephone="1",
mobilephone="2", workphone="3", email="email2", email2="email2", email3="email2")
]
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " " * 10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
testdata = [Contact(firstname="", lastname="", address="", homephone="",
mobilephone="", workphone="", email="", email2="", email3="")] + [
Contact(firstname=random_string("firstname", 10), lastname=random_string("lastname", 20),
address=random_string("address", 20), homephone=random_string("12", 5),
mobilephone=random_string("34", 5), workphone=random_string("56", 5),
email=random_string("email1", 5),
email2=random_string("email2", 5), email3=random_string("email3", 5))
for i in range(5)
]
```
#### File: python_training/fixture/contact.py
```python
from model.contact import Contact
import re
from selenium.webdriver.support.ui import Select
class ContactHelper:
def __init__(self, app):
self.app = app
def change_field_value(self, field_name, text):
if text is not None:
self.app.wd.find_element_by_name(field_name).click()
self.app.wd.find_element_by_name(field_name).clear()
self.app.wd.find_element_by_name(field_name).send_keys(text)
def fill_contact_data(self, contact):
self.change_field_value("firstname", contact.firstname)
self.change_field_value("lastname", contact.lastname)
self.change_field_value("address", contact.address)
self.change_field_value("home", contact.homephone)
self.change_field_value("mobile", contact.mobilephone)
self.change_field_value("work", contact.workphone)
self.change_field_value("fax", contact.fax)
self.change_field_value("email", contact.email)
self.change_field_value("email2", contact.email2)
self.change_field_value("email3", contact.email3)
def add(self, contact):
# init group creation
self.app.wd.find_element_by_link_text("add new").click()
# fill contact form
self.fill_contact_data(contact)
# submit contact creation
self.app.wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click()
self.contact_cache = None
def open_edit_view_for_first_contact(self):
self.open_edit_view_by_index(1)
def open_edit_view_by_index(self, index):
self.app.wd.find_elements_by_xpath("//table[@id='maintable']/tbody/tr/td[8]/a/img")[index].click()
def open_edit_view_by_id(self, id):
self.app.wd.find_element_by_css_selector("a[href*='edit.php?id=%s']" % id).click()
def open_details_view_by_index(self, index):
self.app.wd.find_elements_by_xpath("//*[@id='maintable']/tbody/tr/td[7]/a/img")[index].click()
def open_details_view_by_id(self, id):
self.app.wd.find_element_by_css_selector("a[href*='view.php?id=%s']" % id).click()
def select_first_contact(self):
self.select_contact_by_index(0)
def select_contact_by_index(self, index):
self.app.wd.find_elements_by_name("selected[]")[index].click()
def select_contact_by_id(self, id):
self.app.wd.find_element_by_css_selector("input[value='%s']" % id).click()
def delete_first_contact_by_index_via_main_view(self):
self.delete_contact_by_index_via_main_view(1)
def delete_contact_by_index_via_main_view(self, index):
self.app.open_home_page()
self.select_contact_by_index(index)
# click delete button
self.app.wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click()
# accept contact deletion
self.app.wd.switch_to.alert.accept()
self.contact_cache = None
def delete_contact_by_id_via_main_view(self, id):
self.app.open_home_page()
self.select_contact_by_id(id)
# click delete button
self.app.wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click()
# accept contact deletion
self.app.wd.switch_to.alert.accept()
self.contact_cache = None
def delete_first_contact_by_index_via_edit_view(self):
self.delete_contact_by_index_via_edit_view(1)
def delete_contact_by_index_via_edit_view(self, index):
self.app.open_home_page()
# click edit contact icon
self.open_edit_view_by_index(index)
# click delete button
self.app.wd.find_element_by_xpath("//div[@id='content']/form[2]/input[2]").click()
self.contact_cache = None
def delete_contact_by_id_via_edit_view(self, id):
self.app.open_home_page()
# click edit contact icon
self.open_edit_view_by_id(id)
# click delete button
self.app.wd.find_element_by_xpath("//div[@id='content']/form[2]/input[2]").click()
self.contact_cache = None
def edit_first_contact_by_index_via_main_view(self, contact):
self.edit_contact_by_index_via_main_view(1, contact)
def edit_contact_by_index_via_main_view(self, index, contact):
self.app.open_home_page()
# click edit contact icon
self.open_edit_view_by_index(index)
# fill contact form
self.fill_contact_data(contact)
# click update button
self.app.wd.find_element_by_name("update").click()
self.contact_cache = None
def edit_contact_by_id_via_main_view(self, contact):
self.app.open_home_page()
# click edit contact icon
self.open_edit_view_by_id(contact.id)
# fill contact form
self.fill_contact_data(contact)
# click update button
self.app.wd.find_element_by_name("update").click()
self.contact_cache = None
def edit_first_contact_by_index_via_details_view(self, contact):
self.edit_contact_by_index_via_details_view(1, contact)
def edit_contact_by_index_via_details_view(self, index, contact):
self.app.open_home_page()
# click details icon
self.open_details_view_by_index(index)
# click modify button
self.app.wd.find_element_by_xpath("//*[@id='content']/form[1]/input[2]").click()
self.fill_contact_data(contact)
# click update button
self.app.wd.find_element_by_name("update").click()
self.contact_cache = None
def edit_contact_by_id_via_details_view(self, contact):
self.app.open_home_page()
# click details icon
self.open_details_view_by_id(contact.id)
# click modify button
self.app.wd.find_element_by_xpath("//*[@id='content']/form[1]/input[2]").click()
self.fill_contact_data(contact)
# click update button
self.app.wd.find_element_by_name("update").click()
self.contact_cache = None
def count(self):
self.app.open_home_page()
return len(self.app.wd.find_elements_by_name("selected[]"))
contact_cache = None
def get_contact_list(self):
if self.contact_cache is None:
self.app.open_home_page()
self.contact_cache = []
for element in self.app.wd.find_elements_by_css_selector('tr[name="entry"]'):
cells = element.find_elements_by_tag_name("td")
lname = element.find_element_by_css_selector("td:nth-child(2)").text
fname = element.find_element_by_css_selector("td:nth-child(3)").text
address = element.find_element_by_css_selector("td:nth-child(4)").text
id = element.find_element_by_name("selected[]").get_attribute("value")
all_phones = cells[5].text
all_emails = cells[4].text
self.contact_cache.append(Contact(firstname=fname, lastname=lname, address=address, id=id,
all_phones_from_home_page=all_phones,
all_emails_from_home_page=all_emails))
return list(self.contact_cache)
def get_contact_info_from_edit_page(self, index):
self.app.open_home_page()
self.open_edit_view_by_index(index)
firstname = self.app.wd.find_element_by_name("firstname").get_attribute("value")
lastname = self.app.wd.find_element_by_name("lastname").get_attribute("value")
address = self.app.wd.find_element_by_name("address").get_attribute("value")
id = self.app.wd.find_element_by_name("id").get_attribute("value")
homephone = self.app.wd.find_element_by_name("home").get_attribute("value")
workphone = self.app.wd.find_element_by_name("work").get_attribute("value")
mobilephone = self.app.wd.find_element_by_name("mobile").get_attribute("value")
fax = self.app.wd.find_element_by_name("fax").get_attribute("value")
email = self.app.wd.find_element_by_name("email").get_attribute("value")
email2 = self.app.wd.find_element_by_name("email2").get_attribute("value")
email3 = self.app.wd.find_element_by_name("email3").get_attribute("value")
return Contact(firstname=firstname, lastname=lastname, address=address, id=id, homephone=homephone,
workphone=workphone, mobilephone=mobilephone, fax=fax, email=email, email2=email2, email3=email3)
def get_contact_from_view_page(self, index):
self.app.open_home_page()
self.open_details_view_by_index(index)
text = self.app.wd.find_element_by_id("content").text
homephone = re.search("H: (.*)", text).group(1)
mobilephone = re.search("M: (.*)", text).group(1)
workphone = re.search("W: (.*)", text).group(1)
return Contact(homephone=homephone, workphone=workphone, mobilephone=mobilephone)
def merge_phones_like_on_home_page(self, contact):
return "\n".join(filter(lambda x: x != "",
map(lambda x: self.app.clear_phones(x),
filter(lambda x: x is not None,
[contact.homephone, contact.mobilephone, contact.workphone]))))
def merge_emails_like_on_home_page(self, contact):
return "\n".join(
map(lambda x: self.app.remove_spaces(x),
filter(lambda x: x is not None and x != "",
[contact.email, contact.email2, contact.email3])))
def contact_like_on_webpage(self, contact):
contact.firstname = self.app.remove_spaces(contact.firstname)
contact.lastname = self.app.remove_spaces(contact.lastname)
contact.address = self.app.remove_spaces(contact.address)
contact.all_phones_from_home_page = self.app.contact.merge_phones_like_on_home_page(contact)
contact.all_emails_from_home_page = self.app.contact.merge_emails_like_on_home_page(contact)
return contact
def add_contact_to_group(self, contact, group):
self.app.open_home_page()
self.select_contact_by_id(contact.id)
select = Select(self.app.wd.find_element_by_name("to_group"))
select.select_by_value(group.id)
self.app.wd.find_element_by_name("add").click()
def delete_contact_from_group(self,contact,group):
self.app.open_home_page()
self.open_details_view_by_id(contact.id)
self.app.wd.find_element_by_css_selector("a[href*='index.php?group=%s']" % group.id).click()
self.select_contact_by_id(contact.id)
self.app.wd.find_element_by_name("remove").click()
```
#### File: python_training/fixture/group.py
```python
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def change_field_value(self, field_name, text):
if text is not None:
self.app.wd.find_element_by_name(field_name).click()
self.app.wd.find_element_by_name(field_name).clear()
self.app.wd.find_element_by_name(field_name).send_keys(text)
def fill_group_data(self, group):
self.change_field_value("group_name", group.name)
self.change_field_value("group_header", group.header)
self.change_field_value("group_footer", group.footer)
def open_groups_page(self):
if not (self.app.wd.current_url.endswith("/group.php") and len(self.app.wd.find_elements_by_name("new")) > 0):
self.app.wd.find_element_by_link_text("groups").click()
def create(self, group):
self.open_groups_page()
# init group creation
self.app.wd.find_element_by_name("new").click()
# fill group form
self.fill_group_data(group)
# submit group creation
self.app.wd.find_element_by_name("submit").click()
self.return_to_groups_page()
self.group_cache = None
def delete_first_group(self):
self.delete_group_by_index(0)
def delete_group_by_index(self, index):
self.open_groups_page()
# select first group
self.select_group_by_index(index)
# submit deletion
self.app.wd.find_element_by_name("delete").click()
self.return_to_groups_page()
self.group_cache = None
def delete_group_by_id(self, id):
self.open_groups_page()
# select first group
self.select_group_by_id(id)
# submit deletion
self.app.wd.find_element_by_name("delete").click()
self.return_to_groups_page()
self.group_cache = None
def select_first_group(self):
self.app.wd.find_element_by_name("selected[]").click()
def select_group_by_index(self, index):
self.app.wd.find_elements_by_name("selected[]")[index].click()
def select_group_by_id(self, id):
self.app.wd.find_element_by_css_selector("input[value='%s']" % id).click()
def edit_first_group(self, group):
self.edit_group_by_index(0, group)
def edit_group_by_index(self, index, group):
self.open_groups_page()
self.select_group_by_index(index)
# click edit group button
self.app.wd.find_element_by_name("edit").click()
self.fill_group_data(group)
# click update button
self.app.wd.find_element_by_name("update").click()
self.return_to_groups_page()
self.group_cache = None
def edit_group(self, group):
self.open_groups_page()
self.select_group_by_id(group.id)
# click edit group button
self.app.wd.find_element_by_name("edit").click()
self.fill_group_data(group)
# click update button
self.app.wd.find_element_by_name("update").click()
self.return_to_groups_page()
self.group_cache = None
def return_to_groups_page(self):
self.app.wd.find_element_by_link_text("group page").click()
def count(self):
self.open_groups_page()
return len(self.app.wd.find_elements_by_name("selected[]"))
group_cache = None
def get_group_list(self):
if self.group_cache is None:
self.open_groups_page()
self.group_cache = []
for element in self.app.wd.find_elements_by_css_selector('span.group'):
text = element.text
id = element.find_element_by_name("selected[]").get_attribute("value")
self.group_cache.append(Group(name=text, id=id))
return list(self.group_cache)
```
#### File: python_training/test/test_delete_contact_from_group.py
```python
from model.contact import Contact
from model.group import Group
from generator import contact as f
from generator import group as t
def test_delete_contact_from_group(app, orm):
contact_in_group = None
group_for_removing_contact = None
if len(orm.get_group_list()) == 0:
app.group.create(Group(name="grnew", header="res", footer="tes"))
existing_groups = orm.get_group_list()
for group in existing_groups:
available_contacts = orm.get_contacts_in_group(group=group)
if len(available_contacts) > 0:
contact_in_group = available_contacts[0]
group_for_removing_contact = group
break
if contact_in_group is None:
existing_contacts = orm.get_contact_list()
if len(existing_contacts) > 0:
contact_in_group = existing_contacts[0]
else:
app.contact.add(Contact(firstname="faname", lastname="lname", address="address"))
contact_in_group = orm.get_contact_list()[0]
group_for_removing_contact = existing_groups[0]
app.contact.add_contact_to_group(contact_in_group, group_for_removing_contact)
assert orm.is_contact_in_group(contact_in_group, group_for_removing_contact)
app.contact.delete_contact_from_group(contact_in_group, group_for_removing_contact)
assert not orm.is_contact_in_group(contact_in_group, group_for_removing_contact), 'Contact still in group!'
```
#### File: python_training/test/test_delete_contact.py
```python
from model.contact import Contact
import random
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_delete_some_contact_via_main_view(app, db,check_ui):
if len(db.get_contact_list()) == 0:
app.contact.add(Contact(firstname="faname", lastname="lname", address="address", homephone="1",
mobilephone="2", workphone="3", fax="3", email="e1", email2="e2", email3="e3"))
old_contacts = db.get_contact_list()
contact = random.choice(old_contacts)
app.contact.delete_contact_by_id_via_main_view(contact.id)
WebDriverWait(app.wd, 5).until(EC.url_matches(app.base_url), 'Delete failed, not redirected to main page?')
new_contacts = db.get_contact_list()
assert len(old_contacts) - 1 == len(new_contacts)
old_contacts.remove(contact)
assert old_contacts == new_contacts
if check_ui:
for index, contact_item in enumerate(old_contacts):
formatted_contact = app.contact.contact_like_on_webpage(contact_item)
old_contacts[index] = formatted_contact
assert sorted(old_contacts, key=Contact.id_or_max)==sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
def test_delete_some_contact_via_edit_view(app, db,check_ui):
if len(db.get_contact_list()) == 0:
app.contact.add(Contact(firstname="faname", lastname="lname", address="address", homephone="1",
mobilephone="2", workphone="3", fax="3", email="e1", email2="e2", email3="e3"))
old_contacts = db.get_contact_list()
contact = random.choice(old_contacts)
app.contact.delete_contact_by_id_via_edit_view(contact.id)
new_contacts = db.get_contact_list()
assert len(old_contacts) - 1 == len(new_contacts)
old_contacts.remove(contact)
assert old_contacts == new_contacts
if check_ui:
for index, contact_item in enumerate(old_contacts):
formatted_contact = app.contact.contact_like_on_webpage(contact_item)
old_contacts[index] = formatted_contact
assert sorted(old_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),
key=Contact.id_or_max)
```
#### File: python_training/test/test_edit_group.py
```python
from model.group import Group
import random
def test_edit_some_group_name(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="grnew", header="res", footer="tes"))
old_groups = db.get_group_list()
group = random.choice(old_groups)
group.name = "newname1"
app.group.edit_group(group)
new_groups = db.get_group_list()
assert len(old_groups) == len(new_groups)
for index, group_item in enumerate(old_groups):
if group_item.id == group.id:
old_groups[index] = group
break
assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
if check_ui:
assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
# def test_edit_first_group_header(app):
# if app.group.count() == 0:
# app.group.create(Group(name="grnew", header="res", footer="tes"))
# app.group.edit_first_group(Group(header="newheader1"))
```
|
{
"source": "jekel/gino",
"score": 2
}
|
#### File: gino/gino/__init__.py
```python
from .api import Gino # NOQA
from .engine import GinoEngine, GinoConnection # NOQA
from .exceptions import * # NOQA
from .strategies import GinoStrategy # NOQA
def create_engine(*args, **kwargs):
from sqlalchemy import create_engine
kwargs.setdefault('strategy', 'gino')
return create_engine(*args, **kwargs)
__version__ = '0.7.5'
```
#### File: gino/gino/json_support.py
```python
from datetime import datetime
import sqlalchemy as sa
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
NONE = object()
class Hook:
def __init__(self, parent):
self.parent = parent
self.method = None
def __call__(self, method):
self.method = method
return self.parent
def call(self, instance, val):
if self.method is not None:
val = self.method(instance, val)
return val
class JSONProperty:
def __init__(self, default=None, prop_name='profile'):
self.name = None
self.default = default
self.prop_name = prop_name
self.expression = Hook(self)
self.after_get = Hook(self)
self.before_set = Hook(self)
def __get__(self, instance, owner):
if instance is None:
exp = self.make_expression(
getattr(owner, self.prop_name)[self.name])
return self.expression.call(owner, exp)
val = self.get_profile(instance).get(self.name, NONE)
if val is NONE:
if callable(self.default):
val = self.default(instance)
else:
val = self.default
return self.after_get.call(instance, val)
def __set__(self, instance, value):
self.get_profile(instance)[self.name] = self.before_set.call(
instance, value)
def __delete__(self, instance):
self.get_profile(instance).pop(self.name, None)
def get_profile(self, instance):
if instance.__profile__ is None:
props = type(instance).__dict__
instance.__profile__ = {}
for key, value in (getattr(instance, self.prop_name, None)
or {}).items():
instance.__profile__[key] = props[key].decode(value)
return instance.__profile__
def save(self, instance, value=NONE):
profile = getattr(instance, self.prop_name, None)
if profile is None:
profile = {}
setattr(instance, self.prop_name, profile)
if value is NONE:
value = instance.__profile__[self.name]
if not isinstance(value, sa.sql.ClauseElement):
value = self.encode(value)
rv = profile[self.name] = value
return rv
def reload(self, instance):
if instance.__profile__ is None:
return
profile = getattr(instance, self.prop_name, None) or {}
value = profile.get(self.name, NONE)
if value is NONE:
instance.__profile__.pop(self.name, None)
else:
instance.__profile__[self.name] = self.decode(value)
def make_expression(self, base_exp):
return base_exp
def decode(self, val):
return val
def encode(self, val):
return val
def __hash__(self):
return hash(self.name)
class StringProperty(JSONProperty):
def make_expression(self, base_exp):
return base_exp.astext
class DateTimeProperty(JSONProperty):
def make_expression(self, base_exp):
return base_exp.astext.cast(sa.DateTime)
def decode(self, val):
if val:
val = datetime.strptime(val, DATETIME_FORMAT)
return val
def encode(self, val):
if isinstance(val, datetime):
val = val.strftime(DATETIME_FORMAT)
return val
class IntegerProperty(JSONProperty):
def make_expression(self, base_exp):
return base_exp.astext.cast(sa.Integer)
def decode(self, val):
if val is not None:
val = int(val)
return val
def encode(self, val):
if val is not None:
val = int(val)
return val
class BooleanProperty(JSONProperty):
def make_expression(self, base_exp):
return base_exp.astext.cast(sa.Boolean)
def decode(self, val):
if val is not None:
val = bool(val)
return val
def encode(self, val):
if val is not None:
val = bool(val)
return val
class ObjectProperty(JSONProperty):
def decode(self, val):
if val is not None:
val = dict(val)
return val
def encode(self, val):
if val is not None:
val = dict(val)
return val
class ArrayProperty(JSONProperty):
def decode(self, val):
if val is not None:
val = list(val)
return val
def encode(self, val):
if val is not None:
val = list(val)
return val
__all__ = ['JSONProperty', 'StringProperty', 'DateTimeProperty',
'IntegerProperty', 'BooleanProperty', 'ObjectProperty',
'ArrayProperty']
```
#### File: gino/tests/test_loader.py
```python
import random
from datetime import datetime
import pytest
from async_generator import yield_, async_generator
from gino.loader import AliasLoader
from .models import db, User, Team, Company
pytestmark = pytest.mark.asyncio
@pytest.fixture
@async_generator
async def user(bind, random_name):
c = await Company.create()
t1 = await Team.create(company_id=c.id)
t2 = await Team.create(company_id=c.id, parent_id=t1.id)
u = await User.create(nickname=random_name, team_id=t2.id)
u.team = t2
t2.parent = t1
t2.company = c
t1.company = c
await yield_(u)
await User.delete.gino.status()
await Team.delete.gino.status()
await Company.delete.gino.status()
async def test_model_alternative(user):
u = await User.query.gino.load(User).first()
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
async def test_scalar(user):
name = await User.query.gino.load(User.nickname).first()
assert user.nickname == name
uid, name = await User.query.gino.load((User.id, User.nickname)).first()
assert user.id == uid
assert user.nickname == name
async def test_model_load(user):
u = await User.query.gino.load(User.load('nickname', User.team_id)).first()
assert isinstance(u, User)
assert u.id is None
assert u.nickname == user.nickname
assert u.team_id == user.team.id
with pytest.raises(TypeError):
await User.query.gino.load(User.load(123)).first()
with pytest.raises(AttributeError):
await User.query.gino.load(User.load(Team.id)).first()
async def test_216_model_load_passive_partial(user):
u = await db.select([User.nickname]).gino.model(User).first()
assert isinstance(u, User)
assert u.id is None
assert u.nickname == user.nickname
async def test_load_relationship(user):
u = await User.outerjoin(Team).select().gino.load(
User.load(team=Team)).first()
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
assert isinstance(u.team, Team)
assert u.team.id == user.team.id
assert u.team.name == user.team.name
async def test_load_nested(user):
for u in (
await User.outerjoin(Team).outerjoin(Company).select().gino.load(
User.load(team=Team.load(company=Company))).first(),
await User.load(team=Team.load(company=Company)).gino.first(),
await User.load(team=Team.load(company=Company.on(
Team.company_id == Company.id))).gino.first(),
await User.load(team=Team.load(company=Company).on(
User.team_id == Team.id)).gino.first(),
await User.load(team=Team.on(User.team_id == Team.id).load(
company=Company)).gino.first(),
):
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
assert isinstance(u.team, Team)
assert u.team.id == user.team.id
assert u.team.name == user.team.name
assert isinstance(u.team.company, Company)
assert u.team.company.id == user.team.company.id
assert u.team.company.name == user.team.company.name
async def test_func(user):
def loader(row, context):
rv = User(id=row[User.id], nickname=row[User.nickname])
rv.team = Team(id=row[Team.id], name=row[Team.name])
rv.team.company = Company(id=row[Company.id], name=row[Company.name])
return rv
u = await User.outerjoin(Team).outerjoin(Company).select().gino.load(
loader).first()
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
assert isinstance(u.team, Team)
assert u.team.id == user.team.id
assert u.team.name == user.team.name
assert isinstance(u.team.company, Company)
assert u.team.company.id == user.team.company.id
assert u.team.company.name == user.team.company.name
async def test_adjacency_list(user):
group = Team.alias()
with pytest.raises(AttributeError):
group.non_exist()
# noinspection PyUnusedLocal
def loader(row, context):
rv = User(id=row[User.id], nickname=row[User.nickname])
rv.team = Team(id=row[Team.id], name=row[Team.name])
rv.team.parent = Team(id=row[group.id], name=row[group.name])
return rv
for exp in (loader,
User.load(team=Team.load(parent=group)),
User.load(team=Team.load(parent=group.load('id', 'name'))),
User.load(team=Team.load(parent=group.load()))):
u = await User.outerjoin(
Team
).outerjoin(
group, Team.parent_id == group.id
).select().gino.load(exp).first()
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
assert isinstance(u.team, Team)
assert u.team.id == user.team.id
assert u.team.name == user.team.name
assert isinstance(u.team.parent, Team)
assert u.team.parent.id == user.team.parent.id
assert u.team.parent.name == user.team.parent.name
async def test_alias_loader_columns(user):
user_alias = User.alias()
base_query = user_alias.outerjoin(Team).select()
query = base_query.execution_options(loader=AliasLoader(user_alias, 'id'))
u = await query.gino.first()
assert u.id is not None
async def test_adjacency_list_query_builder(user):
group = Team.alias()
u = await User.load(team=Team.load(parent=group.on(
Team.parent_id == group.id))).gino.first()
assert isinstance(u, User)
assert u.id == user.id
assert u.nickname == user.nickname
assert isinstance(u.team, Team)
assert u.team.id == user.team.id
assert u.team.name == user.team.name
assert isinstance(u.team.parent, Team)
assert u.team.parent.id == user.team.parent.id
assert u.team.parent.name == user.team.parent.name
async def test_literal(user):
sample = tuple(random.random() for _ in range(5))
now = db.Column('time', db.DateTime())
row = await db.first(db.text(
'SELECT now() AT TIME ZONE \'UTC\''
).columns(now).gino.load(
sample + (lambda r, c: datetime.utcnow(), now,)).query)
assert row[:5] == sample
assert isinstance(row[-2], datetime)
assert isinstance(row[-1], datetime)
assert row[-1] <= row[-2]
async def test_load_one_to_many(user):
# noinspection PyListCreation
uids = [user.id]
uids.append((await User.create(nickname='1', team_id=user.team.id)).id)
uids.append((await User.create(nickname='1', team_id=user.team.id)).id)
uids.append((await User.create(nickname='2',
team_id=user.team.parent.id)).id)
query = User.outerjoin(Team).outerjoin(Company).select()
companies = await query.gino.load(
Company.distinct(Company.id).load(
add_team=Team.load(add_member=User).distinct(Team.id))).all()
assert len(companies) == 1
company = companies[0]
assert isinstance(company, Company)
assert company.id == user.team.company_id
assert company.name == user.team.company.name
assert len(company.teams) == 2
for team in company.teams:
if team.id == user.team.id:
assert len(team.members) == 3
for u in team.members:
if u.nickname == user.nickname:
assert isinstance(u, User)
assert u.id == user.id
uids.remove(u.id)
if u.nickname in {'1', '2'}:
uids.remove(u.id)
else:
assert len(team.members) == 1
uids.remove(list(team.members)[0].id)
assert uids == []
# test distinct many-to-one
query = User.outerjoin(Team).select().where(Team.id == user.team.id)
users = await query.gino.load(
User.load(team=Team.distinct(Team.id))).all()
assert len(users) == 3
assert users[0].team is users[1].team
assert users[0].team is users[2].team
async def test_distinct_none(bind):
u = await User.create()
query = User.outerjoin(Team).select().where(User.id == u.id)
loader = User.load(team=Team)
u = await query.gino.load(loader).first()
assert u.team.id is None
query = User.outerjoin(Team).select().where(User.id == u.id)
loader = User.load(team=Team.distinct(Team.id))
u = await query.gino.load(loader).first()
assert not hasattr(u, 'team')
async def test_tuple_loader_279(user):
from gino.loader import TupleLoader
query = db.select([User, Team])
async with db.transaction():
async for row in query.gino.load((User, Team)).iterate():
assert len(row) == 2
async for row in query.gino.load(TupleLoader((User, Team))).iterate():
assert len(row) == 2
async def test_none_as_none_281(user):
import gino
if gino.__version__ < '0.9':
query = Team.outerjoin(User).select()
loader = Team, User.none_as_none()
assert any(row[1] is None
for row in await query.gino.load(loader).all())
loader = Team.distinct(Team.id).load(add_member=User.none_as_none())
assert any(not team.members
for team in await query.gino.load(loader).all())
if gino.__version__ >= '0.8.0':
query = Team.outerjoin(User).select()
loader = Team, User
assert any(row[1] is None
for row in await query.gino.load(loader).all())
loader = Team.distinct(Team.id).load(add_member=User)
assert any(not team.members
for team in await query.gino.load(loader).all())
```
#### File: gino/tests/test_tornado.py
```python
import pytest
import tornado.web
import tornado.httpclient
import tornado.ioloop
import tornado.options
import tornado.escape
from gino.ext.tornado import Gino, Application, GinoRequestHandler
from .models import DB_ARGS
# noinspection PyShadowingNames
@pytest.fixture
def app():
# Define your database metadata
# -----------------------------
db = Gino()
# Define tables as you would normally do
# --------------------------------------
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
nickname = db.Column(db.Unicode(), nullable=False)
# Now just use your tables
# ------------------------
class AllUsers(GinoRequestHandler):
async def get(self):
users = await User.query.gino.all()
for user in users:
self.write('<a href="{url}">{nickname}</a><br/>'.format(
url=self.application.reverse_url('user', user.id),
nickname=tornado.escape.xhtml_escape(user.nickname)))
class GetUser(GinoRequestHandler):
async def get(self, uid):
user = await User.get_or_404(int(uid))
self.write('Hi, {}!'.format(user.nickname))
class AddUser(GinoRequestHandler):
async def post(self):
user = await User.create(nickname=self.get_argument('name'))
self.write('Hi, {}!'.format(user.nickname))
options = {
'db_host': DB_ARGS['host'],
'db_port': DB_ARGS['port'],
'db_user': DB_ARGS['user'],
'db_password': DB_ARGS['password'],
'db_database': DB_ARGS['database'],
}
opts = tornado.options.options
for option, value in options.items():
# noinspection PyProtectedMember
opts._options[opts._normalize_name(option)].parse(value)
app = Application([
tornado.web.URLSpec(r'/', AllUsers, name='index'),
tornado.web.URLSpec(r'/user/(?P<uid>[0-9]+)', GetUser, name='user'),
tornado.web.URLSpec(r'/user', AddUser, name='user_add'),
], debug=True)
loop = tornado.ioloop.IOLoop.current().asyncio_loop
loop.run_until_complete(app.late_init(db))
loop.run_until_complete(db.gino.create_all())
try:
yield app
finally:
loop.run_until_complete(db.gino.drop_all())
@pytest.fixture
async def io_loop(event_loop):
from tornado.platform.asyncio import AsyncIOMainLoop
return AsyncIOMainLoop()
@pytest.mark.gen_test
def test_hello_world(http_client, base_url):
response = yield http_client.fetch(base_url)
assert response.code == 200
with pytest.raises(tornado.httpclient.HTTPError, match='404'):
yield http_client.fetch(base_url + '/user/1')
response = yield http_client.fetch(base_url + '/user', method='POST',
body='name=fantix')
assert response.code == 200
assert b'fantix' in response.body
response = yield http_client.fetch(base_url + '/user/1')
assert response.code == 200
assert b'fantix' in response.body
response = yield http_client.fetch(base_url)
assert response.code == 200
assert b'fantix' in response.body
```
|
{
"source": "jekel/sanic-jwt",
"score": 3
}
|
#### File: sanic-jwt/example/extra_verifications.py
```python
from sanic import Sanic
from sanic.response import json
from sanic_jwt import exceptions
from sanic_jwt import Initialize
from sanic_jwt import protected
class User:
def __init__(self, id, username, password):
self.user_id = id
self.username = username
self.password = password
def __repr__(self):
return "User(id='{}')".format(self.user_id)
def to_dict(self):
return {"user_id": self.user_id, "username": self.username}
users = [User(1, "user1", "<PASSWORD>"), User(2, "user2", "<PASSWORD>")]
username_table = {u.username: u for u in users}
userid_table = {u.user_id: u for u in users}
async def authenticate(request, *args, **kwargs):
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
raise exceptions.AuthenticationFailed("Missing username or password.")
user = username_table.get(username, None)
if user is None:
raise exceptions.AuthenticationFailed("User not found.")
if password != <PASSWORD>:
raise exceptions.AuthenticationFailed("Password is incorrect.")
return user
def user2(payload):
return payload.get("user_id") == 2
extra_verifications = [user2]
app = Sanic(__name__)
Initialize(
app, authenticate=authenticate, extra_verifications=extra_verifications
)
@app.route("/protected")
@protected()
async def protected(request):
return json({"protected": True})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8888, auto_reload=True)
```
#### File: sanic-jwt/sanic_jwt/cache.py
```python
import asyncio
import sys
from .exceptions import LoopNotRunning
def _get_current_task(loop): # noqa
if sys.version_info[:2] < (3, 7): # to avoid deprecation warning
return asyncio.Task.current_task(loop=loop)
else:
return asyncio.current_task(loop=loop)
def _check_event_loop():
if not asyncio.get_event_loop().is_running():
raise LoopNotRunning
def _get_or_create_cache():
loop = asyncio.get_event_loop()
try:
return _get_current_task(loop)._sanicjwt
except AttributeError:
_get_current_task(loop)._sanicjwt = {}
return _get_current_task(loop)._sanicjwt
def get_cached(value):
_check_event_loop()
return _get_or_create_cache().get(value, None)
def is_cached(value):
_check_event_loop()
return value in _get_or_create_cache()
def to_cache(key, value):
_check_event_loop()
_get_or_create_cache().update({key: value})
def clear_cache():
_check_event_loop()
loop = asyncio.get_event_loop()
try:
_get_current_task(loop)._sanicjwt = {}
except AttributeError: # noqa
pass
```
#### File: sanic-jwt/sanic_jwt/utils.py
```python
import binascii
import datetime
import inspect
import logging
import os
from pathlib import Path
from . import exceptions
logger = logging.getLogger(__name__)
def generate_token(n=24, *args, **kwargs):
return str(binascii.hexlify(os.urandom(n)), "utf-8")
def build_claim_iss(attr, *args, **kwargs):
return attr
def build_claim_iat(attr, *args, **kwargs):
return datetime.datetime.utcnow() if attr else None
def build_claim_nbf(attr, config, *args, **kwargs):
seconds = config.leeway() + config.claim_nbf_delta()
return (
datetime.datetime.utcnow() + datetime.timedelta(seconds=seconds)
if attr
else None
)
def build_claim_aud(attr, *args, **kwargs):
return attr
async def call(fn, *args, **kwargs):
if inspect.iscoroutinefunction(fn) or inspect.isawaitable(fn):
fn = await fn(*args, **kwargs)
elif callable(fn):
fn = fn(*args, **kwargs)
return fn
def load_file_or_str(path_or_str):
if isinstance(path_or_str, Path):
if os.path.isfile(str(path_or_str)):
logger.debug('reading file "{}"'.format(str(path_or_str)))
return path_or_str.read_text()
else:
raise exceptions.ProvidedPathNotFound
elif isinstance(path_or_str, str): # noqa
if os.path.isfile(path_or_str):
return Path(path_or_str).read_text()
return path_or_str
def algorithm_is_asymmetric(algorithm):
"""This is a simple method to verify the need to provide a private key to
a given ``algorithm``, as `documented by PyJWT
<https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_
:param algorithm: the given algorithm, like HS256, ES384, RS512, PS256, etc
:return: True if algorithm is asymmetric
"""
return algorithm.lower()[:2] in ("rs", "es", "ps")
```
#### File: sanic-jwt/tests/test_user_secret.py
```python
import jwt
import pytest
from sanic import Sanic
from sanic_jwt import exceptions, Initialize
def test_secret_not_enabled():
app = Sanic(__name__)
with pytest.raises(exceptions.UserSecretNotImplemented):
sanicjwt = Initialize(
app,
authenticate=lambda: {},
user_secret_enabled=True,
)
@pytest.mark.asyncio
async def test_user_secret(app_with_user_secrets):
app, sanicjwt = app_with_user_secrets
_, response = await app.asgi_client.post(
"/auth", json={"username": "user1", "password": "<PASSWORD>"}
)
access_token = response.json.get(sanicjwt.config.access_token_name(), None)
secret = await app.ctx.auth._get_secret(token=access_token)
assert access_token
assert secret == "foobar<1>"
_, response = await app.asgi_client.get(
"/protected",
headers={"Authorization": "Bearer {}".format(access_token)},
)
assert response.status == 200
assert response.json.get("protected") is True
```
#### File: sanic-jwt/tests/test_validators.py
```python
from sanic_jwt.validators import validate_single_scope
def test_validate_single_scope():
assert validate_single_scope("user", ["something"]) is False
assert validate_single_scope("user", ["user"])
assert validate_single_scope("user:read", ["user"])
assert validate_single_scope("user:read", ["user:read"])
assert validate_single_scope("user:read", ["user:write"]) is False
assert validate_single_scope("user:read", ["user:read:write"])
assert validate_single_scope("user", ["user:read"]) is False
assert validate_single_scope("user:read:write", ["user:read"]) is False
assert validate_single_scope("user:read:write", ["user:read:write"])
assert validate_single_scope("user:read:write", ["user:write:read"])
assert validate_single_scope("user:read:write", ["user:read"], False)
assert validate_single_scope("user", ["something", "else"]) is False
assert validate_single_scope("user", ["something", "else", "user"])
assert validate_single_scope("user:read", ["something:else", "user:read"])
assert validate_single_scope("user:read", ["user:read", "something:else"])
assert validate_single_scope(":read", [":read"])
assert validate_single_scope(":read", ["admin"])
assert validate_single_scope("user", []) is False
assert validate_single_scope("user", [None]) is False
assert validate_single_scope("user", [None, "user"])
```
|
{
"source": "jekel/transitions",
"score": 2
}
|
#### File: transitions/extensions/markup.py
```python
from six import string_types, iteritems
from functools import partial
import itertools
import importlib
from ..core import Machine, Enum
import numbers
class MarkupMachine(Machine):
# Special attributes such as NestedState._name/_parent or Transition._condition are handled differently
state_attributes = ['on_exit', 'on_enter', 'ignore_invalid_triggers', 'timeout', 'on_timeout', 'tags', 'label']
transition_attributes = ['source', 'dest', 'prepare', 'before', 'after', 'label']
def __init__(self, *args, **kwargs):
self._markup = kwargs.pop('markup', {})
self._auto_transitions_markup = kwargs.pop('auto_transitions_markup', False)
self.skip_references = True
self._needs_update = True
if self._markup:
models_markup = self._markup.pop('models', [])
super(MarkupMachine, self).__init__(None, **self._markup)
for m in models_markup:
self._add_markup_model(m)
else:
super(MarkupMachine, self).__init__(*args, **kwargs)
self._markup['before_state_change'] = [x for x in (rep(f) for f in self.before_state_change) if x]
self._markup['after_state_change'] = [x for x in (rep(f) for f in self.before_state_change) if x]
self._markup['prepare_event'] = [x for x in (rep(f) for f in self.prepare_event) if x]
self._markup['finalize_event'] = [x for x in (rep(f) for f in self.finalize_event) if x]
self._markup['send_event'] = self.send_event
self._markup['auto_transitions'] = self.auto_transitions
self._markup['ignore_invalid_triggers'] = self.ignore_invalid_triggers
self._markup['queued'] = self.has_queue
@property
def auto_transitions_markup(self):
return self._auto_transitions_markup
@auto_transitions_markup.setter
def auto_transitions_markup(self, value):
self._auto_transitions_markup = value
self._needs_update = True
@property
def markup(self):
self._markup['models'] = self._convert_models()
return self.get_markup_config()
# the only reason why this not part of markup property is that pickle
# has issues with properties during __setattr__ (self.markup is not set)
def get_markup_config(self):
if self._needs_update:
self._convert_states_and_transitions(self._markup)
self._needs_update = False
return self._markup
def add_transition(self, trigger, source, dest, conditions=None,
unless=None, before=None, after=None, prepare=None, **kwargs):
super(MarkupMachine, self).add_transition(trigger, source, dest, conditions=conditions, unless=unless,
before=before, after=after, prepare=prepare, **kwargs)
self._needs_update = True
def add_states(self, states, on_enter=None, on_exit=None, ignore_invalid_triggers=None, **kwargs):
super(MarkupMachine, self).add_states(states, on_enter=on_enter, on_exit=on_exit,
ignore_invalid_triggers=ignore_invalid_triggers, **kwargs)
self._needs_update = True
def _convert_states_and_transitions(self, root):
state = getattr(self, 'scoped', self)
if state.initial:
root['initial'] = state.initial
if state == self and state.name:
root['name'] = self.name[:-2]
self._convert_transitions(root)
self._convert_states(root)
def _convert_states(self, root):
key = 'states' if getattr(self, 'scoped', self) == self else 'children'
root[key] = []
for state_name, state in self.states.items():
s_def = _convert(state, self.state_attributes, self.skip_references)
if isinstance(state_name, Enum):
s_def['name'] = state_name.name
else:
s_def['name'] = state_name
if getattr(state, 'states', []):
with self(state_name):
self._convert_states_and_transitions(s_def)
root[key].append(s_def)
def _convert_transitions(self, root):
root['transitions'] = []
for event in self.events.values():
if self._omit_auto_transitions(event):
continue
for transitions in event.transitions.items():
for trans in transitions[1]:
t_def = _convert(trans, self.transition_attributes, self.skip_references)
t_def['trigger'] = event.name
con = [x for x in (rep(f.func, self.skip_references) for f in trans.conditions
if f.target) if x]
unl = [x for x in (rep(f.func, self.skip_references) for f in trans.conditions
if not f.target) if x]
if con:
t_def['conditions'] = con
if unl:
t_def['unless'] = unl
root['transitions'].append(t_def)
def _add_markup_model(self, markup):
initial = markup.get('state', None)
if markup['class-name'] == 'self':
self.add_model(self, initial)
else:
mod_name, cls_name = markup['class-name'].rsplit('.', 1)
cls = getattr(importlib.import_module(mod_name), cls_name)
self.add_model(cls(), initial)
def _convert_models(self):
models = []
for model in self.models:
state = getattr(model, self.model_attribute)
model_def = dict(state=state.name if isinstance(state, Enum) else state)
model_def['name'] = model.name if hasattr(model, 'name') else str(id(model))
model_def['class-name'] = 'self' if model == self else model.__module__ + "." + model.__class__.__name__
models.append(model_def)
return models
def _omit_auto_transitions(self, event):
return self.auto_transitions_markup is False and self._is_auto_transition(event)
# auto transition events commonly a) start with the 'to_' prefix, followed by b) the state name
# and c) contain a transition from each state to the target state (including the target)
def _is_auto_transition(self, event):
if event.name.startswith('to_') and len(event.transitions) == len(self.states):
state_name = event.name[len('to_'):]
try:
_ = self.get_state(state_name)
return True
except ValueError:
pass
return False
@classmethod
def _identify_callback(self, name):
callback_type, target = super(MarkupMachine, self)._identify_callback(name)
if callback_type:
self._needs_update = True
return callback_type, target
def rep(func, skip_references=False):
""" Return a string representation for `func`. """
if isinstance(func, string_types):
return func
if isinstance(func, numbers.Number):
return str(func)
if skip_references:
return None
try:
return func.__name__
except AttributeError:
pass
if isinstance(func, partial):
return "%s(%s)" % (
func.func.__name__,
", ".join(itertools.chain(
(str(_) for _ in func.args),
("%s=%s" % (key, value)
for key, value in iteritems(func.keywords if func.keywords else {})))))
return str(func)
def _convert(obj, attributes, skip):
s = {}
for key in attributes:
val = getattr(obj, key, False)
if not val:
continue
if isinstance(val, string_types):
s[key] = val
else:
try:
s[key] = [rep(v, skip) for v in iter(val)]
except TypeError:
s[key] = rep(val, skip)
return s
```
|
{
"source": "Jeketam/supertokens-flask",
"score": 2
}
|
#### File: supertokens-flask/supertokens_flask/exceptions.py
```python
def raise_general_exception(msg, previous=None):
if isinstance(msg, SuperTokensError):
raise msg
elif isinstance(msg, Exception):
raise SuperTokensGeneralError(msg) from None
raise SuperTokensGeneralError(msg) from previous
def raise_token_theft_exception(user_id, session_handle):
raise SuperTokensTokenTheftError(user_id, session_handle)
def raise_try_refresh_token_exception(msg):
if isinstance(msg, SuperTokensError):
raise msg
raise SuperTokensTryRefreshTokenError(msg) from None
def raise_unauthorised_exception(msg):
if isinstance(msg, SuperTokensError):
raise msg
raise SuperTokensUnauthorisedError(msg) from None
class SuperTokensError(Exception):
pass
class SuperTokensGeneralError(SuperTokensError):
pass
class SuperTokensTokenTheftError(SuperTokensError):
def __init__(self, user_id, session_handle):
super().__init__('token theft detected')
self.user_id = user_id
self.session_handle = session_handle
class SuperTokensUnauthorisedError(SuperTokensError):
pass
class SuperTokensTryRefreshTokenError(SuperTokensError):
pass
```
#### File: supertokens-flask/tests/test_handshake_info.py
```python
from supertokens_flask.handshake_info import HandshakeInfo
from .utils import (
reset, setup_st, clean_st, start_st,
set_key_value_in_config,
TEST_COOKIE_SECURE_VALUE,
TEST_COOKIE_SECURE_CONFIG_KEY,
TEST_SESSION_EXPIRED_STATUS_CODE_VALUE,
TEST_SESSION_EXPIRED_STATUS_CODE_CONFIG_KEY
)
from supertokens_flask import (
create_new_session
)
from supertokens_flask.exceptions import SuperTokensGeneralError
from flask import Response
def setup_function(f):
reset()
clean_st()
setup_st()
def teardown_function(f):
reset()
clean_st()
def test_core_not_available():
try:
create_new_session(Response(''), 'abc', {}, {})
assert False
except SuperTokensGeneralError:
assert True
def test_successful_handshake_and_update_jwt():
start_st()
info = HandshakeInfo.get_instance()
assert info.access_token_path == '/'
assert info.cookie_domain in {'supertokens.io', 'localhost', None}
assert isinstance(info.jwt_signing_public_key, str)
assert isinstance(info.cookie_secure, bool) and not info.cookie_secure
assert info.refresh_token_path == '/refresh'
assert isinstance(info.enable_anti_csrf, bool) and info.enable_anti_csrf
assert isinstance(info.access_token_blacklisting_enabled,
bool) and not info.access_token_blacklisting_enabled
assert isinstance(info.jwt_signing_public_key_expiry_time, int)
info.update_jwt_signing_public_key_info('test', 100)
updated_info = HandshakeInfo.get_instance()
assert updated_info.jwt_signing_public_key == 'test'
assert updated_info.jwt_signing_public_key_expiry_time == 100
def test_custom_config():
set_key_value_in_config(
TEST_SESSION_EXPIRED_STATUS_CODE_CONFIG_KEY,
TEST_SESSION_EXPIRED_STATUS_CODE_VALUE)
set_key_value_in_config(
TEST_COOKIE_SECURE_CONFIG_KEY,
TEST_COOKIE_SECURE_VALUE)
start_st()
assert HandshakeInfo.get_instance(
).session_expired_status_code == TEST_SESSION_EXPIRED_STATUS_CODE_VALUE
assert isinstance(
HandshakeInfo.get_instance().cookie_secure,
bool) and HandshakeInfo.get_instance().cookie_secure
```
#### File: supertokens-flask/tests/test_querier.py
```python
from supertokens_flask.querier import Querier
from supertokens_flask.utils import find_max_version
from supertokens_flask.exceptions import SuperTokensGeneralError
from .utils import (
reset, setup_st, clean_st, start_st,
API_VERSION_TEST_NON_SUPPORTED_SV,
API_VERSION_TEST_NON_SUPPORTED_CV,
API_VERSION_TEST_SINGLE_SUPPORTED_SV,
API_VERSION_TEST_SINGLE_SUPPORTED_CV,
API_VERSION_TEST_MULTIPLE_SUPPORTED_SV,
API_VERSION_TEST_MULTIPLE_SUPPORTED_CV,
API_VERSION_TEST_SINGLE_SUPPORTED_RESULT,
API_VERSION_TEST_MULTIPLE_SUPPORTED_RESULT,
SUPPORTED_CORE_DRIVER_INTERFACE_FILE
)
from json import load
from supertokens_flask.constants import (
HELLO,
SUPPORTED_CDI_VERSIONS
)
def setup_function(f):
reset()
clean_st()
setup_st()
def teardown_function(f):
reset()
clean_st()
def test_get_api_version():
try:
Querier.get_instance().get_api_version()
assert False
except SuperTokensGeneralError:
assert True
start_st()
cv = API_VERSION_TEST_SINGLE_SUPPORTED_CV
sv = API_VERSION_TEST_SINGLE_SUPPORTED_SV
assert find_max_version(cv, sv) == API_VERSION_TEST_SINGLE_SUPPORTED_RESULT
cv = API_VERSION_TEST_MULTIPLE_SUPPORTED_CV
sv = API_VERSION_TEST_MULTIPLE_SUPPORTED_SV
assert find_max_version(
cv, sv) == API_VERSION_TEST_MULTIPLE_SUPPORTED_RESULT
cv = API_VERSION_TEST_NON_SUPPORTED_CV
sv = API_VERSION_TEST_NON_SUPPORTED_SV
assert find_max_version(cv, sv) is None
def test_check_supported_core_driver_interface_versions():
f = open(SUPPORTED_CORE_DRIVER_INTERFACE_FILE, 'r')
sv = set(load(f)['versions'])
f.close()
assert sv == set(SUPPORTED_CDI_VERSIONS)
def test_core_not_available():
try:
querier = Querier.get_instance()
querier.send_get_request('/', [])
assert False
except SuperTokensGeneralError:
assert True
def test_three_cores_and_round_robin():
start_st()
start_st('localhost', 3568)
start_st('localhost', 3569)
Querier.init_instance('http://localhost:3567;http://localhost:3568/;http://localhost:3569', None)
querier = Querier.get_instance()
assert querier.send_get_request(HELLO, []) == 'Hello\n'
assert querier.send_get_request(HELLO, []) == 'Hello\n'
assert querier.send_get_request(HELLO, []) == 'Hello\n'
assert len(querier.get_hosts_alive_for_testing()) == 3
assert querier.send_delete_request(HELLO, []) == 'Hello\n'
assert len(querier.get_hosts_alive_for_testing()) == 3
assert 'http://localhost:3567' in querier.get_hosts_alive_for_testing()
assert 'http://localhost:3568' in querier.get_hosts_alive_for_testing()
assert 'http://localhost:3569' in querier.get_hosts_alive_for_testing()
def test_three_cores_one_dead_and_round_robin():
start_st()
start_st('localhost', 3568)
Querier.init_instance('http://localhost:3567;http://localhost:3568/;http://localhost:3569', None)
querier = Querier.get_instance()
assert querier.send_get_request(HELLO, []) == 'Hello\n'
assert querier.send_get_request(HELLO, []) == 'Hello\n'
assert len(querier.get_hosts_alive_for_testing()) == 2
assert querier.send_delete_request(HELLO, []) == 'Hello\n'
assert len(querier.get_hosts_alive_for_testing()) == 2
assert 'http://localhost:3567' in querier.get_hosts_alive_for_testing()
assert 'http://localhost:3568' in querier.get_hosts_alive_for_testing()
assert 'http://localhost:3569' not in querier.get_hosts_alive_for_testing()
```
|
{
"source": "Jeket/electron",
"score": 2
}
|
#### File: electron/script/build.py
```python
import argparse
import os
import subprocess
import sys
from lib.config import MIPS64EL_GCC, get_target_arch, build_env, \
enable_verbose_mode, is_verbose_mode
from lib.util import electron_gyp, import_vs_env
CONFIGURATIONS = ['Release', 'Debug']
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
VENDOR_DIR = os.path.join(SOURCE_ROOT, 'vendor')
LIBCC_SOURCE_ROOT = os.path.join(SOURCE_ROOT, 'vendor', 'libchromiumcontent')
LIBCC_DIST_MAIN = os.path.join(LIBCC_SOURCE_ROOT, 'dist', 'main')
GCLIENT_DONE = os.path.join(SOURCE_ROOT, '.gclient_done')
def main():
os.chdir(SOURCE_ROOT)
args = parse_args()
if args.verbose:
enable_verbose_mode()
# Update the VS build env.
import_vs_env(get_target_arch())
# decide which ninja executable to use
ninja_path = args.ninja_path
if not ninja_path:
ninja_path = os.path.join('vendor', 'depot_tools', 'ninja')
if sys.platform == 'win32':
ninja_path += '.exe'
# decide how to invoke ninja
ninja = [ninja_path]
if is_verbose_mode():
ninja.append('-v')
if args.libcc:
if ('D' not in args.configuration
or not os.path.exists(GCLIENT_DONE)
or not os.path.exists(os.path.join(LIBCC_DIST_MAIN, 'build.ninja'))):
sys.stderr.write('--libcc should only be used when '
'libchromiumcontent was built with bootstrap.py -d '
'--debug_libchromiumcontent' + os.linesep)
sys.exit(1)
script = os.path.join(LIBCC_SOURCE_ROOT, 'script', 'build')
subprocess.check_call([sys.executable, script, '-D', '-t',
get_target_arch()])
subprocess.check_call(ninja + ['-C', LIBCC_DIST_MAIN])
env = build_env()
for config in args.configuration:
build_path = os.path.join('out', config[0])
ret = subprocess.call(ninja + ['-C', build_path, args.target], env=env)
if ret != 0:
sys.exit(ret)
def parse_args():
parser = argparse.ArgumentParser(description='Build project')
parser.add_argument('-c', '--configuration',
help='Build with Release or Debug configuration',
nargs='+',
default=CONFIGURATIONS,
required=False)
parser.add_argument('-v', '--verbose',
action='store_true',
default=False,
help='Verbose output')
parser.add_argument('-t', '--target',
help='Build specified target',
default=electron_gyp()['project_name%'],
required=False)
parser.add_argument('--libcc',
help=(
'Build libchromiumcontent first. Should be used only '
'when libchromiumcontent as built with boostrap.py '
'-d --debug_libchromiumcontent.'
),
action='store_true', default=False)
parser.add_argument('--ninja-path',
help='Path of ninja command to use.',
required=False)
return parser.parse_args()
if __name__ == '__main__':
sys.exit(main())
```
|
{
"source": "Jeket/japonicus",
"score": 2
}
|
#### File: Jeket/japonicus/evolution_bayes.py
```python
import datetime
import json
import os
import numpy as np
import pandas as pd
import copy
# from plotInfo import plotEvolutionSummary
from bayes_opt import BayesianOptimization
from multiprocessing import Pool
import multiprocessing as mp
import promoterz
import evaluation
from Settings import getSettings
import evaluation
import resultInterface
from japonicus_options import options, args
dict_merge = lambda a, b: a.update(b) or a
gsettings = getSettings()['Global']
# Fix the shit below!
settings = getSettings()['bayesian']
bayesconf = getSettings('bayesian')
datasetconf = getSettings('dataset')
Strategy = None
percentiles = np.array([0.25, 0.5, 0.75])
all_val = []
stats = []
candleSize = 0
historySize = 0
watch = settings["watch"]
watch, DatasetRange = evaluation.gekko.dataset.selectCandlestickData(watch)
def expandGekkoStrategyParameters(IND, Strategy):
config = {}
IND = promoterz.parameterOperations.expandNestedParameters(IND)
config[Strategy] = IND
return config
def Evaluate(Strategy, parameters):
DateRange = evaluation.gekko.dataset.getRandomDateRange(
DatasetRange, deltaDays=settings['deltaDays']
)
params = expandGekkoStrategyParameters(parameters, Strategy)
BacktestResult = evaluation.gekko.backtest.Evaluate(
bayesconf, watch, [DateRange], params, gsettings['GekkoURLs'][0]
)
BalancedProfit = BacktestResult['relativeProfit']
return BalancedProfit
def gekko_search(**parameters):
parallel = settings['parallel']
num_rounds = settings['num_rounds']
# remake CS & HS variability;
candleSize = settings['candleSize']
historySize = settings['historySize']
if parallel:
p = Pool(mp.cpu_count())
param_list = list([(Strategy, parameters)] * num_rounds)
scores = p.starmap(Evaluate, param_list)
p.close()
p.join()
else:
scores = [Evaluate(Strategy, parameters) for n in range(num_rounds)]
series = pd.Series(scores)
mean = series.mean()
stats.append(
[series.count(), mean, series.std(), series.min()] +
[series.quantile(x) for x in percentiles] +
[series.max()]
)
all_val.append(mean)
return mean
def flatten_dict(d):
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_dict(value).items():
yield key + "." + subkey, subvalue
else:
yield key, value
return dict(items())
def gekko_bayesian(strategy):
print("")
global Strategy
Strategy = strategy
TargetParameters = getSettings()["strategies"][Strategy]
TargetParameters = promoterz.parameterOperations.parameterValuesToRangeOfValues(
TargetParameters, bayesconf.parameter_spread
)
print("Starting search %s parameters" % Strategy)
bo = BayesianOptimization(gekko_search, copy.deepcopy(TargetParameters))
# 1st Evaluate
print("")
print("Step 1: BayesianOptimization parameter search")
bo.maximize(init_points=settings['init_points'], n_iter=settings['num_iter'])
max_val = bo.res['max']['max_val']
index = all_val.index(max_val)
s1 = stats[index]
# 2nd Evaluate
print("")
print("Step 2: testing searched parameters on random date")
max_params = bo.res['max']['max_params'].copy()
# max_params["persistence"] = 1
print("Starting Second Evaluation")
gekko_search(**max_params)
s2 = stats[-1]
# 3rd Evaluate
print("")
print("Step 3: testing searched parameters on new date")
watch = settings["watch"]
print(max_params)
result = Evaluate(Strategy, max_params)
resultjson = expandGekkoStrategyParameters(max_params, Strategy) # [Strategy]
s3 = result
# config.js like output
percentiles = np.array([0.25, 0.5, 0.75])
formatted_percentiles = [str(int(round(x * 100))) + "%" for x in percentiles]
stats_index = (['count', 'mean', 'std', 'min'] + formatted_percentiles + ['max'])
print("")
print("// " + '-' * 50)
print("// " + Strategy + ' Settings')
print("// " + '-' * 50)
print("// 1st Evaluate: %.3f" % s1[1])
for i in range(len(s1)):
print('// %s: %.3f' % (stats_index[i], s1[i]))
print("// " + '-' * 50)
print("// 2nd Evaluate: %.3f" % s2[1])
for i in range(len(s2)):
print('// %s: %.3f' % (stats_index[i], s2[i]))
print("// " + '-' * 50)
print("// 3rd Evaluted: %f" % s3)
print("// " + '-' * 50)
print("config.%s = {%s};" % (Strategy, json.dumps(resultjson, indent=2)[1:-1]))
print('\n\n')
print(resultInterface.parametersToTOML(resultjson))
print("// " + '-' * 50)
return max_params
```
#### File: japonicus/promoterz/evolutionHooks.py
```python
from deap import base, tools
from copy import deepcopy
import random
import promoterz.supplement.age
import promoterz.supplement.PRoFIGA
import promoterz.supplement.phenotypicDivergence
import itertools
# population as last positional argument, to blend with toolbox;
def immigrateHoF(HallOfFame, population):
if not HallOfFame.items:
return population
for Q in range(1):
CHP = deepcopy(random.choice(HallOfFame))
del CHP.fitness.values
population += [CHP]
return population
def immigrateRandom(populate, nb_range, population): # (populate function)
number = random.randint(*nb_range)
population += populate(number)
return population
def filterAwayWorst(population, N=5):
aliveSize = len(population) - 5
population = tools.selBest(population, aliveSize)
return population
def filterAwayThreshold(locale, Threshold, minimum):
remove = [ind for ind in locale.population if ind.fitness.values[0] <= Threshold]
locale.population = [
ind for ind in locale.population if ind.fitness.values[0] > Threshold
]
NBreturn = max(0, min(minimum - len(locale.population), minimum))
if NBreturn and remove:
for k in range(NBreturn):
locale.population.append(random.choice(remove))
def evaluatePopulation(locale):
individues_to_simulate = [ind for ind in locale.population if not ind.fitness.valid]
fitnesses = locale.World.parallel.starmap(
locale.extratools.Evaluate, zip(individues_to_simulate)
)
for i, fit in zip(range(len(individues_to_simulate)), fitnesses):
individues_to_simulate[i].fitness.values = fit
return len(individues_to_simulate)
def getLocaleEvolutionToolbox(World, locale):
toolbox = base.Toolbox()
toolbox.register("ImmigrateHoF", immigrateHoF, locale.HallOfFame)
toolbox.register("ImmigrateRandom", immigrateRandom, World.tools.population)
toolbox.register("filterThreshold", filterAwayThreshold, locale)
toolbox.register('ageZero', promoterz.supplement.age.ageZero)
toolbox.register(
'populationAges',
promoterz.supplement.age.populationAges,
World.genconf.ageBoundaries,
)
toolbox.register(
'populationPD',
promoterz.supplement.phenotypicDivergence.populationPhenotypicDivergence,
World.tools.constructPhenotype,
)
toolbox.register('evaluatePopulation', evaluatePopulation)
return toolbox
def getGlobalToolbox(representationModule):
# GLOBAL FUNCTION TO GET GLOBAL TBX UNDER DEVELOPMENT (ITS COMPLICATED);
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create(
"Individual",
list,
fitness=creator.FitnessMax,
PromoterMap=None,
Strategy=genconf.Strategy,
)
toolbox.register("mate", representationModule.crossover)
toolbox.register("mutate", representationModule.mutate)
PromoterMap = initPromoterMap(Attributes)
toolbox.register("newind", initInd, creator.Individual, PromoterMap)
toolbox.register("population", tools.initRepeat, list, toolbox.newind)
toolbox.register("constructPhenotype", representationModule.constructPhenotype)
return toolbox
def getFitness(individual):
R = sum(individual.wvalues)
# selectCriteria = lambda x: sum(x.fitness.wvalues)
def selectCriteria(ind):
p = ind.fitness.wvalues[0]
s = (1 + ind.fitness.wvalues[1])
R = p * s
if p < 0 and s < 0:
R = - abs(R)
return R
def selBest(individuals, number):
chosen = sorted(individuals, key=selectCriteria, reverse=True)
return chosen[:number]
def Tournament(individuals, finalselect, tournsize):
chosen = []
for i in range(finalselect):
aspirants = tools.selRandom(individuals, tournsize)
chosen.append(max(individuals, key=selectCriteria))
return chosen
```
#### File: japonicus/promoterz/logger.py
```python
import datetime
import os
import pandas as pd
class Logger():
def __init__(self, logfilename):
date = datetime.datetime.now()
if not os.path.isdir('logs'):
os.mkdir('logs')
self.logfilename = logfilename
self.Header = ""
self.Summary = ""
self.Body = ""
def log(self, message, target="Body", show=True):
self.__dict__[target] += message + '\n'
if show:
print(message)
def updateFile(self):
File = open('logs/%s.log' % self.logfilename, 'w')
File.write(self.Header)
File.write(self.Summary)
File.write(self.Body)
File.close()
def write_evolution_logs(self, i, stats, localeName):
filename = "logs/%s_%s.csv" % (self.logfilename, localeName)
df = pd.DataFrame(stats)
df.to_csv(filename)
```
#### File: japonicus/promoterz/statistics.py
```python
from deap import tools
import pandas as pd
import numpy as np
import os
statisticsNames = {
'avg': 'Average profit',
'std': 'Profit variation',
'min': 'Minimum profit',
'max': 'Maximum profit',
'size': 'Population size',
'maxsize': 'Max population size',
'avgTrades': 'Avg trade number',
'sharpe': 'Avg sharpe ratio',
'evaluationScore': "Evaluation Score",
'evaluationScoreOnSecondary': "Score on Secondary Dataset",
}
def getStatisticsMeter():
stats = tools.Statistics( lambda ind: ind.fitness.values[0])
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)
return stats
def compileStats(locale):
# --get proper evolution statistics;
Stats = locale.stats.compile(locale.population)
Stats['dateRange'] = None
Stats['maxsize'] = locale.POP_SIZE
Stats['size'] = len(locale.population)
Stats['avgTrades'] = locale.extraStats['avgTrades']
Stats['sharpe'] = np.mean([x.fitness.values[1] for x in locale.population])
Stats['evaluationScoreOnSecondary'] = locale.lastEvaluationOnSecondary
Stats['evaluationScore'] = locale.lastEvaluation
locale.lastEvaluationOnSecondary = None
locale.lastEvaluation = None
Stats['id'] = locale.EPOCH
locale.EvolutionStatistics.append(Stats)
LOGPATH = "output/evolution_gen_%s.csv" % locale.name
locale.World.logger.write_evolution_logs(
locale.EPOCH, locale.EvolutionStatistics, locale.name
)
def showStats(locale):
# show information;
Stats = locale.EvolutionStatistics[locale.EPOCH]
print("EPOCH %i\t&%i" % (locale.EPOCH, locale.extraStats['nb_evaluated']))
statnames = ['max', 'avg', 'min', 'std', 'size', 'maxsize', 'avgTrades', 'sharpe']
statText = ""
for s in range(len(statnames)):
SNAME = statnames[s]
SVAL = Stats[SNAME]
statText += "%s" % statisticsNames[SNAME]
if not SVAL % 1:
statText += " %i\t" % SVAL
else:
statText += " %.3f\t" % SVAL
if s % 2:
statText += '\n'
print(statText)
print('Elder dies %i' % locale.extraStats['elder'])
print('')
```
#### File: Jeket/japonicus/Settings.py
```python
import os
import js2py
from pathlib import Path
from configStrategies import cS
from configIndicators import cI
class _settings:
def __init__(self, **entries):
'''
print(entries)
def iterate(self, DATA):
for W in DATA.keys():
if type(DATA[W]) == dict:
iterate(self,DATA[W])
else:
self.__dict__.update(DATA)
iterate(self,entries)
'''
self.__dict__.update(entries)
def getstrat(self, name):
return self.strategies[name]
def getSettings(specific=None):
HOME = str(Path.home())
s = {
'Global': {'gekkoPath': HOME + '/gekko', 'configFilename': 'example-config.js', 'save_dir': "output", 'log_name': 'evolution_gen.csv', 'RemoteAWS': '../AmazonSetup/hosts', 'GekkoURLs': ['http://localhost:3000'], 'showFailedStrategies': False},
# Hosts list of remote machines running gekko, to distribute evaluation load;
# option values: path to HOSTS file list OR False;
# Your gekko local URL - CHECK THIS!
# genetic algorithm settings
'generations': {'gekkoDebug': True, 'showIndividualEvaluationInfo': False, 'parameter_spread': 60, 'POP_SIZE': 30, 'NBEPOCH': 800, 'evaluateSettingsPeriodically': 20, 'deltaDays': 90, 'ParallelCandlestickDataset': 1, 'cxpb': 0.8, 'mutpb': 0.2, '_lambda': 7, 'PRoFIGA_beta': 0.005, 'ageBoundaries': (9, 19), 'candleSize': 10, 'proofSize': 12, 'DRP': 70, 'ParallelBacktests': 6, 'finaltest': {'NBBESTINDS': 1, 'NBADDITIONALINDS': 4}, 'chromosome': {'GeneSize': 2, 'Density': 3}, 'weights': {'profit': 1.0, 'sharpe': 0.1}, 'interpreteBacktestProfit': 'v3'},
# show gekko verbose (strat info) - gekko must start with -d flag;
# Verbose single evaluation results;
# if parameter is set to value rather than tuple limits at settings, make the value
# a tuple based on chosen spread value (percents); value: 10 --spread=50--> value: (5,15)
# Initial population size, per locale
# number of epochs to run
# show current best settings on every X epochs. (or False)
# time window size on days of candlesticks for each evaluation
# Number of candlestick data loaded simultaneously in each locale;
# slower EPOCHS, theoretical better evolution;
# seems broken. values other than 1 makes evolution worse.
# -- Genetic Algorithm Parameters # Probabilty of crossover # Probability of mutation; # size of offspring generated per epoch; # weight of PRoFIGA calculations on variability of population size # minimum age to die, age when everyone dies (on EPOCHS) # candle size for gekko backtest, in minutes
# Date range persistence; Number of subsequent rounds
# until another time range in dataset is selected;
# mode of profit interpretation: v1, v2 or v3.
# please check the first functions at evaluation.gekko.backtest
# to understand what is this. has big impact on evolutionary agenda.
# bayesian optimization settings
'bayesian': {'gekkoDebug': False, 'deltaDays': 60, 'num_rounds': 10, 'random_state': 2017, 'num_iter': 50, 'init_points': 9, 'parallel': False, 'show_chart': False, 'save': True, 'parameter_spread': 100, 'candleSize': 30, 'historySize': 10, 'watch': {"exchange": "poloniex", "currency": 'USDT', "asset": 'BTC'}, 'interpreteBacktestProfit': 'v3'},
# show gekko verbose (strat info) - gekko must start with -d flag;
# time window size on days of candlesticks for each evaluation
# number of evaluation rounds
# seed for randomziation of values
# number of iterations on each round
# number of random values to start bayes evaluation
# candleSize & historySize on Gekko, for all evals
'dataset': {'dataset_source': None, '!dataset_source': {"exchange": "kraken", "currency": 'USD', "asset": 'LTC'}, 'eval_dataset_source': None, 'dataset_span': 0, 'eval_dataset_span': 0},
# -- Gekko Dataset Settings
# leave the ! on the ignored entry as convenient;
# dataset_source can be set to None so it searches from any source; # in case of specifying exchange-currency-asset, rename this removing the '!', and del the original key above.
# span in days from the end of dataset to the beggining. Or zero.
# (to restrain length);
'strategies': cS,
'indicators': cI,
'skeletons': {'ontrend': {"SMA_long": 1000, "SMA_short": 50}},
}
if specific != None:
if not specific:
return _settings(**s)
else:
return _settings(** s[specific])
return s
def get_configjs(filename="example-config.js"):
with open(filename, "r") as f:
text = f.read()
text = text.replace("module.exports = config;", "config;")
return js2py.eval_js(text).to_dict()
```
|
{
"source": "jekhokie/ansible-modules",
"score": 2
}
|
#### File: cloud/vmware/vra_guest.py
```python
ANSIBLE_METADATA = {
'metadata_version': '0.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vra_guest
short_description: Provisioning of a VMware vRA guest from a blueprint
version_added: "2.6"
description:
- "Create a VM from a Blueprint via vRealizeAutomation (vRA)"
options:
blueprint_instance_id:
description:
- ID of the instance within the Blueprint - there should only ever be a single ID for this module to work
required: true
blueprint_name:
description:
- Name of the Blueprint to use for provisioning
required: true
cpu:
description:
- Number of CPUs for the VM (integer)
required: true
extra_disks:
description:
- Array of additional disks to add to the VM - these are *in addition to* the base/root disk (Disk0 - which cannot be modified)
- 'Valid attributes are:'
- ' - C(size_gb) (integer): Disk storage size in specified unit.'
- ' - C(mount_point) (str): Mount point (Linux) or drive letter (Windows).'
required: false
hostname:
description:
- Hostname of the VM - note that this requires a custom "Hostname" property be added to the Blueprint
required: true
memory:
description:
- Amount of memory, in GB (integer)
required: true
network_adapter:
description:
- Name of the 'Network Adapter' (network) to attach the VM to - this will drive the target network for the VM
required: true
vra_hostname:
description:
- Hostname of the vRA instance to communicate with
required: true
vra_password:
description:
- Password of the user interacting with the API
required: true
vra_tenant:
description:
- Tenant name for the vRA provisioning
required: true
vra_username:
description:
- Name of the user interacting with the API
required: true
wait_timeout:
description:
- Number of seconds to wait for a VM to boot on creation
type: int
default: 600
required: false
requirements:
- copy
- json
- requests
- time
author:
- <NAME> (@jekhokie) <<EMAIL>>
'''
EXAMPLES = '''
- name: Create a VM from a Blueprint
delegate_to: localhost
vra_guest:
blueprint_instance_id: "vSphere__vCenter__Machine_1"
blueprint_name: "Linux"
cpu: 2
extra_disks:
- size_gb: 60
mount_point: "/mnt1"
- size_gb: 80
mount_point: "/mnt2"
hostname: "Test-VM"
memory: 4096
network_adapter: "network-adapter-name"
vra_hostname: "my-vra-host.localhost"
vra_password: "<PASSWORD>"
vra_tenant: "vsphere.local"
vra_username: "automation-user"
wait_timeout: 300
'''
RETURN = '''
instance:
description: Metadata about the newly-created VM
type: dict
returned: always
sample: none
'''
import copy
import json
import requests
import time
from ansible.module_utils.basic import AnsibleModule
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# ignore annoyances
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class VRAHelper(object):
'''Helper class for managing interaction with vRA and corresponding resources.'''
def __init__(self, module):
"""
Default constructor
Args:
module: object containing parameters passed by playbook
Returns: (VRAHelper) Instance of the VRAHelper class
"""
self.module = module
self.blueprint_instance_id = module.params['blueprint_instance_id']
self.blueprint_name = module.params['blueprint_name']
self.cpu = module.params['cpu']
self.extra_disks = module.params['extra_disks']
self.hostname = module.params['hostname']
self.memory = module.params['memory']
self.network_adapter = module.params['network_adapter']
self.vra_hostname = module.params['vra_hostname']
self.vra_password = module.params['vra_password']
self.vra_tenant = module.params['vra_tenant']
self.vra_username = module.params['vra_username']
self.ip = None
self.headers = {
"accept": "application/json",
"content-type": "application/json"
}
# initialize bearer token for auth
self.get_auth()
def get_auth(self):
"""
Get a bearer token and update the instance headers for authorization
Returns: None (updates the instance headers with token)
"""
try:
url = "https://%s/identity/api/tokens" % (self.vra_hostname)
payload = '{"username":"%s","password":"%s","tenant":"%s"}' % (self.vra_username, self.vra_password, self.vra_tenant)
response = requests.request("POST", url, data=payload, headers=self.headers, verify=False)
# format bearer token into correct auth pattern
token = response.json()['id']
self.headers["authorization"] = "Bearer %s" % token
except Exception as e:
self.module.fail_json(msg="Failed to get bearer token: %s" % (e))
def get_catalog_id(self):
"""
Retrieve the catalog ID for the Blueprint requested
Returns: None (updates the instance with the catalog ID)
"""
catalog_dict = {}
try:
url = "https://%s/catalog-service/api/consumer/entitledCatalogItems" % (self.vra_hostname)
response = requests.request("GET", url, headers=self.headers, verify=False)
for i in response.json()['content']:
item_name = i['catalogItem']['name']
item_id = i['catalogItem']['id']
catalog_dict[item_name] = item_id
self.catalog_id = catalog_dict[self.blueprint_name]
except Exception as e:
self.module.fail_json(msg="Failed to get catalog ID for blueprint %s: %s" % (self.blueprint_name, e))
def get_template_json(self):
"""
Retrieve a template JSON object for the Blueprint being requested
Returns: None (updates the instance with the template JSON object)
"""
try:
url = "https://%s/catalog-service/api/consumer/entitledCatalogItems/%s/requests/template" % (self.vra_hostname, self.catalog_id)
response = requests.request("GET", url, headers=self.headers, verify=False)
self.template_json = response
except Exception as e:
self.module.fail_json(msg="Failed to get template JSON for creating the VM: %s" % (e))
def customize_template(self):
"""
Customize the Blueprint template for the customizations requested by the playbook
Returns: None (updates the instance template JSON with customizations)
"""
template = dict(self.template_json.json())
metadata = template['data'][self.blueprint_instance_id]['data']
metadata['cpu'] = self.cpu
metadata['memory'] = self.memory
metadata['Hostname'] = self.hostname
metadata['VirtualMachine.Network0.Name'] = self.network_adapter
# add custom additional disk drives if requested
if len(self.extra_disks) >= 1:
disk_meta_orig = copy.deepcopy(metadata['disks'][0])
disk_id = disk_meta_orig['data']['id']
for i, disk in enumerate(self.extra_disks):
disk_id += 1
disk_meta = copy.deepcopy(disk_meta_orig)
disk_meta['data']['capacity'] = self.extra_disks[i]['size_gb']
disk_meta['data']['label'] = "Hard disk %s" % (i + 2)
disk_meta['data']['volumeId'] = (i + 1)
disk_meta['data']['id'] = disk_id
disk_meta['data']['userCreated'] = "true"
disk_meta['data']['is_clone'] = "false"
disk_meta['data']['initial_location'] = self.extra_disks[i]['mount_point']
metadata['disks'].append(disk_meta)
self.template_json = template
def create_vm_from_template(self):
"""
Make a request to provision a VM with the custom template specified
Returns: None (updates the instance with the request ID)
"""
try:
url = "https://%s/catalog-service/api/consumer/entitledCatalogItems/%s/requests" % (self.vra_hostname, self.catalog_id)
response = requests.request("POST", url, headers=self.headers, data=json.dumps(self.template_json), verify=False)
self.request_id = response.json()['id']
except Exception as e:
self.module.fail_json(msg="Failed to create VM from template: %s" % (e))
def get_vm(self):
"""
Make a request for the details of a VM having a specific hostname
Returns: None (updates the instance with the VM details)
"""
try:
url = "https://%s/catalog-service/api/consumer/resources/types/Infrastructure.Virtual/?limit=5000" % (self.vra_hostname)
response = requests.request("GET", url, headers=self.headers, verify=False)
vms = [i for i in response.json()['content'] if i['name'] == self.hostname]
if len(vms) > 1:
self.module.fail_json(msg="Duplicate VMs with hostname %s." % (self.hostname))
elif len(vms) == 1:
self.request_id = vms[0]['requestId']
# get details about the VM
url = "https://%s/catalog-service/api/consumer/requests/%s/resources" % (self.vra_hostname, self.request_id)
response = requests.request("GET", url, headers=self.headers, verify=False)
# get the Destroy ID and VM Name using list comprehension
meta_dict = [element for element in response.json()['content'] if element['providerBinding']['providerRef']['label'] == 'Infrastructure Service'][0]
self.destroy_id = meta_dict['id']
# get the VM IP address using list comprehension
vm_data = [element for element in meta_dict['resourceData']['entries'] if element['key'] == 'ip_address'][0]
self.ip = vm_data['value']['value']
except Exception as e:
self.module.fail_json(msg="Failed to get VM details for '%s': %s" % (self.hostname, e))
def get_vm_state(self):
"""
Make a request to find the state of a VM (running, stopped, etc.). This needs to happen
via the resourceData attribute search due to the fact that the top-level resource request
via the "get_vm" function above does not return the requestData dictionary that contains the
required state information.
Options are:
- On
- TurningOn
- TurningOff
- Off
- Rebooting
Returns: None (updates the instance with the VM state information)
"""
try:
if self.request_id == None:
self.module.fail_json(msg="No request ID to request VM state information for")
url = "https://%s/catalog-service/api/consumer/resources/%s" % (self.vra_hostname, self.destroy_id)
response = requests.request("GET", url, headers=self.headers, verify=False)
meta_dict = [element for element in response.json()['resourceData']['entries'] if element['key'] == 'MachineStatus'][0]
self.state = meta_dict['value']['value']
except Exception as e:
self.module.fail_json(msg="Failed to get VM state information for '%s': %s" % (self.hostname, e))
def get_vm_build_status(self):
"""
Check on the status of a VM that had been requested to be built
Returns: None (updates the instance with the VM build details)
"""
try:
url = "https://%s/catalog-service/api/consumer/requests/%s" % (self.vra_hostname, self.request_id)
response = requests.request("GET", url, headers=self.headers, verify=False)
self.build_status = response.json()['stateName']
explanation = response.json()['requestCompletion']
if explanation is None:
self.build_explanation = ""
else:
self.build_explanation = explanation['completionDetails']
except Exception as e:
self.module.fail_json(msg="Failed to get VM create status: %s" % (e))
def run_module():
# available options for the module
module_args = dict(
blueprint_instance_id=dict(type='str', required=True),
blueprint_name=dict(type='str', required=True),
cpu=dict(type='int', required=True),
extra_disks=dict(type='list', default=[]),
hostname=dict(type='str', required=True),
memory=dict(type='int', required=True),
network_adapter=dict(type='str', required=True),
vra_hostname=dict(type='str', required=True),
vra_password=dict(type='str', required=True, no_log=True),
vra_tenant=dict(type='str', required=True),
vra_username=dict(type='str', required=True),
wait_timeout=dict(type='int', default=600)
)
# seed result dict that is returned
result = dict(
changed=False,
failed=False,
state='',
destroy_id='',
ip='',
hostname=''
)
# default Ansible constructor
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
# initialize the interface and get a bearer token
vra_helper = VRAHelper(module)
vra_helper.get_vm()
# check mode - see whether the VMs need to be created
if module.check_mode:
if vra_helper.ip == None:
result['changed'] = True
module.exit_json(**result)
# only create the VM if it doesn't already exist
if vra_helper.ip == None:
result['changed'] = True
vra_helper.get_catalog_id()
vra_helper.get_template_json()
vra_helper.customize_template()
vra_helper.create_vm_from_template()
timer = 0
timeout_seconds = module.params['wait_timeout']
while True:
vra_helper.get_vm_build_status()
if timer >= timeout_seconds:
module.fail_json(msg="Failed to create VM in %s seconds" % (module.params['wait_timeout']))
elif vra_helper.build_status == 'Failed':
module.fail_json(msg="Failed to create VM: %s" % vra_helper.build_explanation)
elif vra_helper.build_status == 'Successful':
break
time.sleep(15)
timer += 15
vra_helper.get_vm()
# assign results for output
vra_helper.get_vm_state()
result['state'] = vra_helper.state
result['destroy_id'] = vra_helper.destroy_id
result['ip'] = vra_helper.ip
result['hostname'] = vra_helper.hostname
# successful run
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
```
|
{
"source": "jekhokie/electronicsbox",
"score": 4
}
|
#### File: electronicsbox/raspi3--08-7seg-led-display/main.py
```python
import RPi.GPIO as GPIO
import time
# use BCM pin mode
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# set the pins being used to control the LEDs
#LED_PINS = [2, 3, 4, 9, 10, 17, 22, 27]
# store the ordered A-G pins for output
# A B C D E F G
DIGIT_PINS = [4, 17, 10, 22, 27, 3, 2]
# configure all pins as output drivers
for led in DIGIT_PINS:
GPIO.setup(led, GPIO.OUT, initial=1)
# define segments for displaying digits
# in order, left to right in array are segments:
#
# A, B, C, D, E, F, G
#
# referencing above diagram of segments to light up:
#
# G F COM A B
# | | | | |
# |---------|
# | A |
# | F B |
# | G |
# | E C |
# | D dp|
# |---------|
# | | | | |
# E D COM C DP
#
# this means, for instance, if we want to show "2", we need to
# light segments A, B, G, E, D, which corresponds to [1, 1, 0, 1, 1, 0, 1]
digit0 = [1, 1, 1, 1, 1, 1, 1]
digit1 = [0, 1, 1, 0, 0, 0, 0]
digit2 = [1, 1, 0, 1, 1, 0, 1]
digit3 = [1, 1, 1, 1, 0, 0, 1]
digit4 = [0, 1, 1, 0, 0, 1, 1]
digit5 = [1, 0, 1, 1, 0, 1, 1]
digit6 = [1, 0, 1, 1, 1, 1, 1]
digit7 = [1, 1, 1, 0, 0, 0, 0]
digit8 = [1, 1, 1, 1, 1, 1, 1]
digit9 = [1, 1, 1, 0, 0, 1, 1]
# store all digits in array for easy parsing
digit_list = [digit0, digit1, digit2, digit3, digit4,
digit5, digit6, digit7, digit8, digit9]
# function to clear the LED screen
def clear_screen():
for d in range(0, 7):
GPIO.output(DIGIT_PINS[d], 0)
# light up a digit
def write_digit(digit):
for x in range(0, 7):
GPIO.output(DIGIT_PINS[x], digit[x])
# loop through digit list and display each digit in sequence
try:
while True:
# print digits 0-9 in sequence
for digit in digit_list:
clear_screen()
write_digit(digit)
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
```
#### File: electronicsbox/raspi3--11-xbee-send-receive/receiver.py
```python
import serial, time
import RPi.GPIO as GPIO
from xbee import XBee
# assign the LED pins and XBee device settings
LED_UP_PIN = 21
LED_DOWN_PIN = 20
LED_LEFT_PIN = 16
LED_RIGHT_PIN = 12
SERIAL_PORT = "/dev/ttyS0"
BAUD_RATE = 9600
# set the pin mode
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# initialize GPIO outputs for LEDs
for l in [LED_UP_PIN, LED_DOWN_PIN, LED_LEFT_PIN, LED_RIGHT_PIN]:
GPIO.setup(l, GPIO.OUT)
# handler for whenever data is received from transmitters - operates asynchronously
def receive_data(data):
print("Received data: {}".format(data))
rx = data['rf_data'].decode('utf-8')
state, led = rx[:1], rx[1:]
# parse the received contents and activate the respective LED if the data
# received is actionable
if state in ("0", "1"):
if led in ("UP", "DOWN", "LEFT", "RIGHT"):
# TODO: Use some meta-programming here to translate received led and state
# to the actual LED state, removing all conditionals
if led == "UP":
GPIO.output(LED_UP_PIN, int(state))
elif led == "DOWN":
GPIO.output(LED_DOWN_PIN, int(state))
elif led == "LEFT":
GPIO.output(LED_LEFT_PIN, int(state))
elif led == "RIGHT":
GPIO.output(LED_RIGHT_PIN, int(state))
else:
print("ERROR: Received invalid LED '{}' - ignoring transmission".format(state))
else:
print("ERROR: Received invalid STATE '{}' - ignoring transmission".format(state))
print("Packet: {}".format(data))
print("Data: {}".format(data['rf_data']))
# configure the xbee and enable asynchronous mode
ser = serial.Serial(SERIAL_PORT, baudrate=BAUD_RATE)
xbee = XBee(ser, callback=receive_data, escaped=False)
while True:
try:
# operate in async mode where all messages will go to handler
time.sleep(0.001)
except KeyboardInterrupt:
break
# clean up
GPIO.cleanup()
xbee.halt()
ser.close()
```
#### File: electronicsbox/raspi3--15-joystick-controlled-xbee-comm-robot/robot.py
```python
import serial, time
import RPi.GPIO as GPIO
from xbee import XBee
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
# assign the pins and XBee device settings
LIGHT_PIN = 12
HORN_PIN = 19
READY_PIN = 21
SERIAL_PORT = "/dev/ttyS0"
BAUD_RATE = 9600
# set the pin mode
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# set up the horn and ready pins as output
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.setup(HORN_PIN, GPIO.OUT)
GPIO.setup(READY_PIN, GPIO.OUT)
# set up the motor controllers
mh = Adafruit_MotorHAT(addr=0x60)
left_motor_1 = mh.getMotor(1)
left_motor_2 = mh.getMotor(2)
right_motor_1 = mh.getMotor(3)
right_motor_2 = mh.getMotor(4)
# handler for whenever data is received from transmitters - operates asynchronously
def receive_data(data):
print("Received data: {}".format(data))
rx = data['rf_data'].decode('utf-8')
# sanity check we received the correct number of inputs for horn, left, and right motor
if len(rx) != 10:
print("received invalid data: {}".format(rx))
return
# gather the control signals
light, horn, l_motor_dir, l_speed, r_motor_dir, r_speed = rx[0], rx[1], rx[2], rx[3:-4], rx[6], rx[7:]
# parse the received contents and take action as appropriate
# - light control
if light == "1":
GPIO.output(LIGHT_PIN, GPIO.HIGH)
else:
GPIO.output(LIGHT_PIN, GPIO.LOW)
# - horn control
if horn == "1":
GPIO.output(HORN_PIN, GPIO.HIGH)
else:
GPIO.output(HORN_PIN, GPIO.LOW)
# attempt to convert string to integer which is what the library expects
l_motor_speed = 0
r_motor_speed = 0
try:
l_motor_speed = int(l_speed)
r_motor_speed = int(r_speed)
except(Exception):
raise("Could not convert motor speed to integer for left/right motors: {}/{}".format(l_speed, r_speed))
return
# - motor movement for left motor control
if l_motor_dir == "0":
left_motor_1.run(Adafruit_MotorHAT.BACKWARD)
left_motor_2.run(Adafruit_MotorHAT.BACKWARD)
left_motor_1.setSpeed(l_motor_speed)
left_motor_2.setSpeed(l_motor_speed)
elif l_motor_dir == "1":
left_motor_1.run(Adafruit_MotorHAT.RELEASE)
left_motor_2.run(Adafruit_MotorHAT.RELEASE)
left_motor_1.setSpeed(0)
left_motor_2.setSpeed(0)
elif l_motor_dir == "2":
left_motor_1.run(Adafruit_MotorHAT.FORWARD)
left_motor_2.run(Adafruit_MotorHAT.FORWARD)
left_motor_1.setSpeed(l_motor_speed)
left_motor_2.setSpeed(l_motor_speed)
else:
print("Invalid entry for left motor control: {}".format(lmc))
# - motor movement for right motor control
if r_motor_dir == "0":
right_motor_1.run(Adafruit_MotorHAT.BACKWARD)
right_motor_2.run(Adafruit_MotorHAT.BACKWARD)
right_motor_1.setSpeed(r_motor_speed)
right_motor_2.setSpeed(r_motor_speed)
elif r_motor_dir == "1":
right_motor_1.run(Adafruit_MotorHAT.RELEASE)
right_motor_2.run(Adafruit_MotorHAT.RELEASE)
right_motor_1.setSpeed(0)
right_motor_2.setSpeed(0)
elif r_motor_dir == "2":
right_motor_1.run(Adafruit_MotorHAT.FORWARD)
right_motor_2.run(Adafruit_MotorHAT.FORWARD)
right_motor_1.setSpeed(r_motor_speed)
right_motor_2.setSpeed(r_motor_speed)
else:
print("Invalid entry for right motor control: {}".format(lmc))
print("Packet: {}".format(data))
print("Data: {}".format(data['rf_data']))
# configure the xbee and enable asynchronous mode
ser = serial.Serial(SERIAL_PORT, baudrate=BAUD_RATE)
xbee = XBee(ser, callback=receive_data, escaped=False)
# trigger the "I'm ready" LED
GPIO.output(READY_PIN, GPIO.HIGH)
# main execution loop
while True:
try:
# operate in async mode where all messages will go to handler
time.sleep(0.001)
except KeyboardInterrupt:
break
# clean up
GPIO.cleanup()
xbee.halt()
left_motor_1.run(Adafruit_MotorHAT.RELEASE)
left_motor_2.run(Adafruit_MotorHAT.RELEASE)
right_motor_1.run(Adafruit_MotorHAT.RELEASE)
right_motor_2.run(Adafruit_MotorHAT.RELEASE)
ser.close()
```
|
{
"source": "jekhokie/python-parallel-ci-tests",
"score": 3
}
|
#### File: python-parallel-ci-tests/app/__init__.py
```python
import os
from flask import Flask, request, app
import socket
import mysql.connector
import yaml
app = Flask(__name__)
# import configuration settings or defaults if none exists
config = {}
cfg_file = os.path.join('config', 'settings.yml')
if os.path.isfile(cfg_file):
with open(cfg_file) as yml:
config = yaml.load(yml, Loader=yaml.FullLoader)
else:
config['db_host'] = '10.11.13.40'
config['db_port'] = '3306'
config['db_user'] = 'remote_user'
config['db_pass'] = '<PASSWORD>'
config['db_name'] = 'testdb'
# create initial sql connector
db_conn = mysql.connector.connect(
host = config['db_host'],
port = config['db_port'],
user = config['db_user'],
passwd = config['db_pass'],
database = config['db_name']
)
# a simple page that says hello
@app.route('/', methods=['GET'])
def hello():
hostname = request.args.get('hostname')
job_id = request.args.get('job_id')
mysql_results = ""
# query MySQL database
c = db_conn.cursor(dictionary=True)
c.execute("SELECT * FROM test_table")
for row in c:
mysql_results += "<tr><td>{}</td></tr>".format(row['test_col'])
html = """
<h3>Hello World from {}!</h3>
<h4>Job ID: {}</h4>
<h4>MySQL DB: {}@{}:{}/{}</h4>
<table style='border: 1px solid black;'>
<thead>
<tr>
<th>Data from Database</th>
</tr>
</thead>
<tbody>
{}
</tbody>
</table>
""".format(hostname, job_id, config['db_user'], config['db_host'], config['db_port'], config['db_name'], mysql_results)
return html.format(hostname=socket.gethostname(), job_id=job_id)
```
|
{
"source": "jekhokie/scriptbox",
"score": 4
}
|
#### File: 2020/3/solve.py
```python
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def get_trees(lines, right, down):
trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[down::down]:
if (pos + right) >= line_len:
pos = right - (line_len - pos)
else:
pos += right
if line[pos] == '#':
trees += 1
return trees
trees = get_trees(lines, 3, 1)
print("Solution to challenge 1: {}".format(trees))
#--- challenge 2
tree_list = []
sequences = [[1,1], [3,1], [5,1], [7,1], [1,2]]
for check in sequences:
tree_list.append(get_trees(lines, check[0], check[1]))
product = 1
for trees in tree_list:
product *= trees
print("Solution to challenge 2: {}".format(product))
```
#### File: 2020/4/solve.py
```python
import re
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
def get_passports(lines):
passport = ''
passports = []
for line in lines:
if line != '':
passport += ' {}'.format(line)
else:
try:
birth_year = re.findall(r'byr:([^\s]+)', passport)[0]
issue_year = re.findall(r'iyr:([^\s]+)', passport)[0]
exp_year = re.findall(r'eyr:([^\s]+)', passport)[0]
height = re.findall(r'hgt:([^\s]+)', passport)[0]
hair_color = re.findall(r'hcl:([^\s]+)', passport)[0]
eye_color = re.findall(r'ecl:([^\s]+)', passport)[0]
passport_id = re.findall(r'pid:([^\s]+)', passport)[0]
passports.append({'birth_year': birth_year,
'issue_year': issue_year,
'exp_year': exp_year,
'height': height,
'hair_color': hair_color,
'eye_color': eye_color,
'passport_id': passport_id})
passport = ''
except:
# do nothing - invalid passport
passport = ''
continue
return passports
def year_check(check_val, digits, min, max):
try:
if len(check_val) == digits and int(check_val) >= min and int(check_val) <= max:
return True
except:
return False
return False
def height_check(check_val):
try:
(height, unit) = re.findall(r'([0-9]+)(in|cm)', check_val)[0]
height = int(height)
if unit == 'cm':
return (height >= 150 and height <= 193)
else:
return (height >= 59 and height <= 76)
except:
# do nothing - didn't find expected values
return False
return False
passports = get_passports(lines)
#--- challenge 1
print("Solution to challenge 1: {}".format(len(passports)))
#--- challenge 2
valid_passports = 0
for passport in passports:
if (year_check(passport['birth_year'], 4, 1920, 2002) and
year_check(passport['issue_year'], 4, 2010, 2020) and
year_check(passport['exp_year'], 4, 2020, 2030) and
height_check(passport['height']) and
re.match('^#[0-9a-f]{6}$', passport['hair_color']) and
re.match('(amb|blu|brn|gry|grn|hzl|oth)', passport['eye_color']) and
re.match('^[0-9]{9}$', passport['passport_id'])):
valid_passports += 1
print("Solution to challenge 2: {}".format(valid_passports))
```
#### File: repository/models/car_datamodels.py
```python
from sqlalchemy import Column, Integer, String
from ...models.car_viewmodels import Car
from .base_model import BaseModel
class CarDataModel(BaseModel):
__tablename__ = "cars"
id = Column("id", Integer, primary_key=True)
year = Column("year", Integer)
make = Column("make", String(255))
model = Column("model", String(255))
def to_view_model(self) -> Car:
return Car(
year=self.year,
make=self.make,
model=self.model,
)
```
#### File: python--fastapi-template/python__fastapi_template/settings.py
```python
import yaml
from dataclasses import dataclass
@dataclass
class AppConfig:
environment: str = "development"
dbtype: str = ""
dbname: str = ""
def get_settings() -> AppConfig:
"""Get application settings from configuration file"""
with open('config/settings.yaml', 'r') as yml:
config = yaml.load(yml, Loader=yaml.FullLoader)['app']
return AppConfig(
environment=config['environment'],
dbtype=config['dbtype'],
dbname=config['dbname'],
)
```
#### File: scriptbox/python--kafka-produce-consume/start_producer.py
```python
import random
import signal
import sys
import time
import yaml
from kafka import KafkaProducer
print('Starting producer...')
def handle_terminate(sig, frame):
'''
Terminate the script when CTRL-C is pressed.
'''
print('SIGINT received - terminating')
sys.exit(0)
# ensure terminate (SIGINT) can be handled
signal.signal(signal.SIGINT, handle_terminate)
# load configs
with open('config/settings.yml', 'r') as yml:
config = yaml.load(yml, Loader=yaml.FullLoader)
def main():
'''
Main execution loop for producing messages - can be terminated
by issuing SIGINT (CTRL-C).
'''
# set up some variables, and get the word list for random publishing
rwords = open('config/wordlist.txt').read().splitlines()
producer = KafkaProducer(bootstrap_servers=config['bootstrap-server'])
# loop and publish random words every 1 second
while True:
w1 = random.choice(rwords)
w2 = random.choice(rwords)
rw = '{} {}'.format(w1, w2)
print('Publishing "{}"'.format(rw))
producer.send(config['topic'], str.encode(rw))
time.sleep(1)
if __name__ == '__main__':
main()
```
#### File: scriptbox/python--ldap-list-users-data/get_ldap_info.py
```python
import argparse
import ldap
import time
import yaml
import datetime
from datetime import datetime, timedelta
from tabulate import tabulate
# specific attributes we need
ldap_attrs = ["dn", "name", "displayName", "mail", "accountExpires", "memberOf"]
# load configs
with open('config/settings.yml', 'r') as yml:
config = yaml.load(yml, Loader=yaml.FullLoader)
# determine if groups should be output
parser = argparse.ArgumentParser(description='Capture and display user information and groups')
parser.add_argument('-g', action='store_true', default=False, dest='show_groups', help='Include group information for each user in output')
parser.add_argument('-d', action='store_true', default=False, dest='debug_output', help='Whether to include debug output during search')
args = parser.parse_args()
# initialize and attempt to bind - will fail if unsuccessful
l = ldap.initialize("{}://{}".format(config['protocol'], config['host']))
l.simple_bind_s(config['user'], config['passwd'])
# convert an LDAP-provided timestamp to something human readable
def convert_ad_timestamp(ts):
epoch_sec = ts / 10**7
expiry_date = "NEVER"
is_expired = ""
try:
expiry = datetime.fromtimestamp(epoch_sec) - timedelta(days=(1970-1601) * 365 + 89)
expiry_date = expiry.strftime("%a, %d %b %Y %H:%M:%S %Z")
if expiry < datetime.now():
is_expired = "X"
except:
pass # some date way in the future to prevent expiry
return (expiry_date, is_expired)
user_table = []
user_groups = []
users = config['users']
for user in users:
# set up some reasonable default values for printing
(given_name, surname) = user.split(" ", 1)
name = user
display_name = ""
email = ""
expires_date = "NO ACCOUNT/NOT FOUND"
is_expired = ""
memberships = ""
# search for user
if args.debug_output:
print("Searching values for: {}".format(user))
user_result = l.search_s(config['base_dn'], ldap.SCOPE_SUBTREE, "(&(givenName={})(sn={}))".format(given_name, surname), ldap_attrs)
if user_result:
dn, attrs = user_result[0]
name = attrs['name'][0].decode('utf-8')
display_name = attrs['displayName'][0].decode('utf-8')
email = attrs['mail'][0].decode('utf-8')
# output values if requested
if args.debug_output:
print(" dn:{}|display_name:{}|email:{}".format(dn, display_name, email))
# manipulate memberships into something useful
if attrs['memberOf']:
memberships = "\n".join(sorted([x.decode('utf-8') for x in attrs['memberOf']]))
# convert account expiration into something useful
if attrs['accountExpires']:
ldap_ts = float(attrs['accountExpires'][0])
(expires_date, is_expired) = convert_ad_timestamp(ldap_ts)
elif args.debug_output:
print(" No user data found!")
# add table row for user info
user_table.append([name, display_name, email, is_expired, expires_date])
user_groups.append([name, memberships])
# sort results for easier viewing
user_table.sort(key=lambda x: x[0])
# print the tabular results
print(tabulate(user_table, headers=['Name', 'displayName', 'Mail', 'Expired?', 'Account Expiry'],
tablefmt='fancy_grid',
colalign=('left','center','center','center','center')))
# print the results of memberships
if args.show_groups:
print(tabulate(user_groups, headers=['Name', 'Memberships'],
tablefmt='fancy_grid',
colalign=('left','left')))
```
#### File: python--learnings/coding-practice/capitalize_words.py
```python
def solve(s):
prev_space = False
new_string = ""
for pos, i in enumerate(s):
if i == " ":
new_string += i
prev_space = True
continue
if i.isalpha():
if prev_space == True or pos == 0:
new_string += i.upper()
else:
new_string += i
prev_space = False
else:
new_string += i
prev_space = False
return new_string
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
```
#### File: python--learnings/coding-practice/char_to_upper.py
```python
def convert_third_upper(my_str):
if len(my_str) < 3:
print(my_str)
return
letter = my_str[2]
new_str = my_str[0:2] + letter.upper()
if len(my_str) >= 3:
new_str += my_str[3:]
print(new_str)
if __name__ == '__main__':
convert_third_upper('hello')
convert_third_upper('he')
convert_third_upper('hel')
```
#### File: python--learnings/coding-practice/get_response_json.py
```python
import requests
import json
def run():
res = requests.get('https://jsonplaceholder.typicode.com/todos/1')
resp_json = json.loads(res.text)
print(resp_json)
if __name__ == '__main__':
run()
```
#### File: python--learnings/coding-practice/pairs_of_socks.py
```python
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
keys = set(ar)
vals = [ar.count(i) for i in keys]
socks = dict(zip(keys, vals))
pairs = [(i // 2) for i in socks.values()]
return(sum(pairs))
if __name__ == '__main__':
n = 10
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
result = sockMerchant(n, ar)
print(result)
'''
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
'''
```
#### File: multi-module/cls/animal.py
```python
class Animal:
def __init__(self):
self.name = "Animal"
def __repr__(self):
return "I am an animal with name {}".format(self.name)
```
#### File: multi-module/cls/randomfunc.py
```python
def random_func():
print("Hello from random function")
```
#### File: python--learnings/multi-module/run.py
```python
from cls.randomfunc import random_func
from cls.animal import Animal
from cls.zebra import Zebra
def run():
# general module import
random_func()
# class import
animal = Animal()
print(animal)
# sub-class import
zebra = Zebra()
print(zebra)
if __name__ == '__main__':
run()
```
#### File: scriptbox/python--learnings/multiple_assignment.py
```python
import unittest
# test functionality
class TestMethods(unittest.TestCase):
def test_assignments(self):
a, b = 5, 10
self.assertEqual(a, 5)
self.assertEqual(b, 10)
def test_unpacking(self):
people = {'name': 'Joe'}
for k, v in people.items():
self.assertEqual(k, 'name')
self.assertEqual(v, 'Joe')
def test_failed_assignment_count(self):
with self.assertRaises(ValueError):
(x, y) = 'a'
def test_remaining_assignments(self):
first, *rest = [1, 2, 3, 4]
self.assertEqual(first, 1)
self.assertEqual(rest, [2, 3, 4])
# main execution
if __name__ == '__main__':
unittest.main()
```
|
{
"source": "jeking3/boost-deptree",
"score": 2
}
|
#### File: jeking3/boost-deptree/deptree.py
```python
import json
import networkx
import re
from pathlib import Path
class BoostDependencyTree(object):
"""
Generates a PlantUML dependency tree to visualize the dependencies.
One of the benefits of generating a visual graph is that cycles become
immediately evident.
"""
EDGES = {
2: "-->",
1: "..>"
}
STRENGTHS = {
"include": 2,
"src": 2,
"test": 1,
"tests": 1
}
def __init__(self, root: Path, out: Path):
"""
Arguments:
root: path to BOOST_ROOT
out: path to output file
"""
self.exp = re.compile(r"^\s*#\s*include\s*[<\"](?P<header>[^>\"]+)[>\"]\s*$")
self.graph = networkx.DiGraph()
self.headers = {} # key: header include path; value: repo key
self.repos = {} # key: repo key; value: repo path
self.out = out
self.root = root
self.libs = self.root / "libs"
with (self.libs / "config" / "include" / "boost" / "version.hpp").open() as fp:
vlines = fp.readlines()
for vline in vlines:
if "BOOST_LIB_VERSION" in vline:
#define BOOST_LIB_VERSION "1_71"
tokens = vline.split(" ")
self.boost_version = tokens[2].strip()[1:-1].replace("_", ".")
def load(self):
self.collect()
self.analyze()
def collect(self):
"""
Locate every .hpp and .h file and associate it with a repository.
"""
metas = self.libs.glob("**/libraries.json")
for meta in metas:
with meta.open() as fp:
metadata = json.loads(fp.read())
repodir = meta.parent.parent
metadata = metadata[0] if isinstance(metadata, list) else metadata # for boost/core
repokey = metadata["key"]
repoinc = repodir / "include"
if repoinc.is_dir(): # libs/geometry/index has no include but looks like a repo?
self.graph.add_node(repokey)
self.repos[repokey] = repodir
headers = repoinc.glob("**/*.h??")
for header in headers:
# print(str(header))
incpath = header.relative_to(repoinc)
assert incpath not in self.headers,\
f"{incpath} in {repokey} already in header map from "\
f"{self.headers[incpath]} - duplicate header paths!"
self.headers[str(incpath)] = repokey
def analyze(self):
"""
Find every include statement and create a graph of dependencies.
"""
for repokey, repodir in self.repos.items():
for ext in ["c", "cpp", "h", "hpp", "ipp"]:
files = repodir.glob("**/*." + ext)
for code in files:
inside = code.relative_to(repodir).parts[0]
if inside not in self.STRENGTHS.keys():
continue
weight = self.STRENGTHS[inside]
with code.open() as fp:
try:
#print(str(code))
source = fp.readlines()
except UnicodeDecodeError:
continue
for line in source:
match = self.exp.search(line)
if match:
include = match.group("header")
if include in self.headers:
deprepo = self.headers[include]
if repokey != deprepo: # avoid self-references
data = self.graph.get_edge_data(repokey, deprepo, {"weight": 0})
if data["weight"] > 0 and data["weight"] < weight:
self.graph.remove_edge(repokey, deprepo)
data["weight"] = 0
if data["weight"] == 0:
self.graph.add_edge(repokey, deprepo, weight=weight)
def report_cycles(self):
with self.out.open("w") as fp:
fp.write("@startuml\n")
fp.write("\n")
fp.write(f"title Boost {self.boost_version} Direct Dependency Cycles\n")
fp.write("footer Generated by boost-deptree (C) 2019 <NAME> III\n")
fp.write("\n")
for edge in self.graph.edges:
fwdweight = self.graph.get_edge_data(edge[0], edge[1])["weight"]
if fwdweight > 1:
if self.graph.get_edge_data(edge[1], edge[0], {"weight": 0})["weight"] > 1:
fp.write(f"['{edge[0]}'] --> ['{edge[1]}']\n")
fp.write("\n")
fp.write("@enduml\n")
def report_dependencies_from(self, repokey):
with self.out.open("w") as fp:
fp.write("@startuml\n")
fp.write("\n")
fp.write(f"title Boost {self.boost_version} dependencies of {repokey}\n")
fp.write("footer Generated by boost-deptree (C) 2019 <NAME> III\n")
fp.write("\n")
for edge in self.graph.edges:
if edge[0] == repokey:
fwdweight = self.graph.get_edge_data(edge[0], edge[1])["weight"]
fp.write(f"['{edge[0]}'] {self.EDGES[fwdweight]} ['{edge[1]}']\n")
fp.write("\n")
fp.write("@enduml\n")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Generate PlantUML dependency tree.')
parser.add_argument('root', type=str, help='Boost root directory.')
parser.add_argument('out', type=str, help='Output filename.')
require_one = parser.add_mutually_exclusive_group(required=True)
require_one.add_argument('--cycles', action='store_true', help='Show direct repository dependency cycles.')
require_one.add_argument('--from', help='Show dependencies from a given repository.')
args = parser.parse_args()
root = Path(args.root)
assert root.is_dir(), "root is not a directory"
out = Path(args.out)
tree = BoostDependencyTree(root, out)
tree.load()
if args.cycles:
tree.report_cycles()
else:
tree.report_dependencies_from(args.__dict__["from"])
```
|
{
"source": "jeking3/tempenv",
"score": 2
}
|
#### File: jeking3/tempenv/setup.py
```python
from pathlib import Path
from pkg_resources import parse_version
from setuptools import setup
# Configurables
name = "tempenv"
description = "Environment Variable Context Manager"
packages = ["tempenv"]
versionfile = "tempenv/version.py"
# Everything below should be cookie-cutter
def get_requirements(name: str) -> list:
"""
Return the contents of a requirements file
Arguments:
- name: the name of a file in the requirements directory
Returns:
- a list of requirements
"""
return read_file(Path(f"requirements/{name}.txt")).splitlines()
def read_file(path: Path) -> str:
"""
Return the contents of a file
Arguments:
- path: path to the file
Returns:
- contents of the file
"""
with path.open() as desc_file:
return desc_file.read().rstrip()
def version():
"""
Return the version string for the package stored in versionfile.
"""
_version = {}
exec(read_file(Path(versionfile)), _version)
return str(parse_version(_version["__version__"]))
requirements = {}
for type in ["run", "test"]:
requirements[type] = get_requirements(type)
setup(
name=name,
version=version(),
python_requires=">=3.6",
description=description,
long_description=read_file(Path("README.md")),
long_description_content_type="text/markdown",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Security",
"Topic :: System :: Shells",
"Topic :: Utilities",
"Typing :: Typed",
],
keywords="temporary, environment variable, context manager, test, testing",
download_url="https://github.com/jeking3/tempenv/archive/main.zip",
url="https://github.com/jeking3/tempenv",
author="<NAME>",
author_email="<EMAIL>",
license="Apache License 2.0",
install_requires=requirements["run"],
tests_require=requirements["test"],
test_suite="unittest",
packages=packages,
include_package_data=True,
package_data={"tempenv": ["py.typed"]},
)
```
#### File: tempenv/tempenv/tempenv.py
```python
import os
import warnings
from contextlib import AbstractContextManager
from typing import Dict
from typing import Optional
class EnvironmentVariableChangedWarning(ResourceWarning):
"""
An environment variable being managed by a TemporaryEnvironment was
changed by the context it was managing.
"""
pass
class TemporaryEnvironment(AbstractContextManager):
"""
Manages a temporary environment.
Sets or removes environment variables when entering, and will undo those
changes on exit. It does not save the entire environment, it will only
modify the items it was directed to modify.
If an environment variable is part of the directives and is changed
by the context being managed, a warning is issued.
"""
def __init__(self, directives: Dict[str, str], restore_if_changed: bool = True):
"""
Initializer.
Arguments:
directives (Dict[str, str]):
A list of environment variables to add/overwrite or
remove. To remove an environment variable set the value
to None. To remove the content of an environment variable
but leave it defined, set the value to str().
restore_if_changed (bool):
Restore each tracked environment variable to the original state
even if it was changed during the context.
"""
# arguments
self.directives = directives
self.restore_if_changed = restore_if_changed
# internals
self._originals: Dict[
str, Optional[str]
] = {} # key: envvar name, value: string or None (not there)
def __enter__(self):
"""
Entering scope.
Add any additions and remove any removals from the environment.
Save the original values for restoration later.
"""
for ename, dvalue in self.directives.items():
self._originals[ename] = os.environ.get(ename)
if dvalue is not None:
os.environ[ename] = dvalue
elif ename in os.environ:
del os.environ[ename]
def __exit__(self, *exc):
"""
Leaving scope.
Check for any changes and issue warnings if required, then restore
things to their proper state if required.
"""
for ename, ovalue in self._originals.items():
dvalue = self.directives[ename]
evalue = os.environ.get(ename)
if evalue != dvalue:
warnings.warn(ename, EnvironmentVariableChangedWarning)
if not self.restore_if_changed:
continue
if evalue != ovalue:
if ovalue is not None:
os.environ[ename] = ovalue
else:
del os.environ[ename]
def __call__(self, f):
"""
Set temporary environment variables as a decorator.
"""
def wrapped_f(*args, **kwargs):
try:
self.__enter__()
f(*args, **kwargs)
finally:
self.__exit__(None)
return wrapped_f
```
|
{
"source": "jekir/nmcli",
"score": 3
}
|
#### File: nmcli/data/connection.py
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class Connection:
name: str
uuid: str
conn_type: str
device: str
def to_json(self):
return {
'name': self.name,
'uuid': self.uuid,
'conn_type': self.conn_type,
'device': self.device
}
```
#### File: nmcli/data/device.py
```python
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Device:
device: str
device_type: str
state: str
connection: Optional[str]
def to_json(self):
return {
'device': self.device,
'device_type': self.device_type,
'state': self.state,
'connection': self.connection
}
@dataclass(frozen=True)
class DeviceWifi:
in_use: bool
ssid: str
mode: str
chan: int
rate: int
signal: int
security: str
def to_json(self):
return {
'in_use': self.in_use,
'ssid': self.ssid,
'mode': self.mode,
'chan': self.chan,
'rate': self.rate,
'signal': self.signal,
'security': self.security
}
```
#### File: nmcli/dummy/_device.py
```python
from typing import List, Tuple
from .._device import DeviceControlInterface
from ..data.device import Device, DeviceWifi
class DummyDeviceControl(DeviceControlInterface):
@property
def wifi_connect_args(self):
return self._wifi_connect_args
def __init__(self, result_call: List[Device] = None,
result_wifi: List[DeviceWifi] = None, raise_error: Exception = None):
self._raise_error = raise_error
self._result_call = [] if result_call is None else result_call
self._result_wifi = [] if result_wifi is None else result_wifi
self._wifi_connect_args: List[Tuple] = []
def __call__(self) -> List[Device]:
if not self._raise_error is None:
raise self._raise_error
return self._result_call
def wifi(self) -> List[DeviceWifi]:
if not self._raise_error is None:
raise self._raise_error
return self._result_wifi
def wifi_connect(self, ssid: str, password: str) -> None:
if not self._raise_error is None:
raise self._raise_error
self._wifi_connect_args.append((ssid, password))
```
#### File: nmcli/dummy/_general.py
```python
from .._general import GeneralControlInterface
from ..data.general import General
class DummyGeneralControl(GeneralControlInterface):
def __init__(self, result_call: General = None,
raise_error: Exception = None):
self._raise_error = raise_error
self._result_call = result_call
def __call__(self) -> General:
if not self._raise_error is None:
raise self._raise_error
if not self._result_call is None:
return self._result_call
raise ValueError("'result_call' is not properly initialized")
```
#### File: jekir/nmcli/setup.py
```python
from setuptools import setup
from setuptools.command.test import test
class PyTest(test):
def run_tests(self):
import pytest
pytest.main(self.test_args)
setup(
name='nmcli',
version='0.2.2',
packages=['nmcli', 'nmcli.data', 'nmcli.dummy'],
package_data={
'nmcli': ['py.typed'],
},
test_suite='tests',
python_requires='>=3.7',
install_requires=[
],
tests_require=[
'pytest'
],
cmdclass={'test': PyTest}
)
```
|
{
"source": "jekku0966/router_status_check",
"score": 3
}
|
#### File: jekku0966/router_status_check/router_channel_status.py
```python
import requests
from bs4 import BeautifulSoup
def RouterCheck(url):
data_pwr = []
data_snr = []
data_up = []
i = 0
j = 0
soup = BeautifulSoup(url.content, 'html5lib')
table = soup.find('table', {'summary': 'Downstream Channels'})
cols_pwr = table.findAll('td', {'headers': 'ch_pwr'})
cols_snr = table.findAll('td', {'headers': 'ch_snr'})
table = soup.find('table', {'summary': 'Upstream Channels'})
cols_up_pwr = table.findAll('td', {'headers': 'up_pwr'})
for power in cols_pwr:
data_pwr.append(power.text[1:-11])
for snr in cols_snr:
data_snr.append(snr.text[:-9])
for up_pwr in cols_up_pwr:
data_up.append(up_pwr.text[:-11])
for pwr, snr in zip(data_pwr, data_snr):
i += 1
print('Channel ' + str(i) + ': ' +
str(pwr) + 'dBmV, ' + str(snr) + 'dB')
print('')
print('Upstream Channel data:')
for up_data in data_up:
j += 1
print('Channel ' + str(j) + ': ' + str(up_data) + 'dB')
url = requests.get('http://192.168.100.1/Docsis_system.asp')
if __name__ == '__main__':
if bridged.status_code != 200:
RouterCheck(url)
else:
url = requests.get('http://192.168.0.1/Docsis_system.asp')
RouterCheck(url)
```
|
{
"source": "jekku0966/xblstatus",
"score": 3
}
|
#### File: jekku0966/xblstatus/status_live.py
```python
import requests
from bs4 import BeautifulSoup
import cherrypy
import json
class xblStatus(object):
exposed = True
def GET(self):
return json.dumps({'text': 'I\'m ALIVE!'})
def POST(*args, **kwargs):
r = requests.get(
'http://support.xbox.com/en-US/xbox-live-status?icid=furl_status')
soup = BeautifulSoup(r.content, 'html5lib')
g_data = soup.find_all("ul", {"class": "core"})
status = {}
for item in g_data:
for service in item.findAll('h3', {'class': 'servicename'}):
status[service.text] = []
for platform in item.findAll('div', {'class': 'label'}):
status[service.text].append(platform.text)
outputOk = []
outputDown = []
for service, platform in status.items():
if platform:
platString = ''.join(platform)
outputDown.append(
'{} is limited. Platforms: {}\n'.format(service, platString))
else:
outputOk.append('{} is up and running.\n'.format(service))
strOk = ''.join(outputOk)
strDown = ''.join(outputDown)
if strDown and strOk:
return json.dumps({'attachments': [{'fallback': strOk, 'title': 'These systems are online:', 'text': strOk, 'color': '#008000'}, {'fallback': strDown, 'title': 'These systems are down:', 'text': strDown, 'color': '#FF0000'}]})
elif strDown and not strOk:
return json.dumps({'attachments': [ {'fallback': strDown, 'title': 'These systems are down:', 'text': strDown, 'color': '#FF0000'}]})
else:
return json.dumps({'attachments': [{'fallback': strOk, 'title': 'These systems are online:', 'text': strOk, 'color': '#008000'}]})
# Start the Cherrypy server
if __name__ == '__main__':
cherrypy.config.update("server.conf")
cherrypy.quickstart(xblStatus(), '/', "app.conf")
```
|
{
"source": "jekky/jquery-douban",
"score": 2
}
|
#### File: jquery-douban/apps/test.py
```python
import os
import cgi
import logging
from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
testcases = (
'collection',
'event',
'miniblog',
'note',
'oauth',
'recommendation',
'review',
'subject',
'tag',
'user',
'gears',
'jquery',
'parser',
)
class TestHandler(webapp.RequestHandler):
def get(self):
self.response.out.write(self.build_json())
def post(self):
self.response.out.write(self.build_json())
def put(self):
self.response.out.write(self.build_json())
def delete(self):
self.response.out.write(self.build_json())
def build_json(self):
return json.dumps({
'url': self.request.url,
'params': dict(cgi.parse_qsl(self.request.query_string)),
'headers': {
'h1': self.request.headers.get('H1'),
'h2': self.request.headers.get('H2'),
},
'data': self.request.body,
})
class TestcasePage(webapp.RequestHandler):
def get(self, testcase_name):
if testcase_name not in testcases:
return self.error(404)
template_path = 'templates/tests/%s.html' % testcase_name
template_values = {
'testcase_name': testcase_name,
}
path = os.path.join(os.path.dirname(__file__), template_path)
return self.response.out.write(template.render(path, template_values))
urls = (
(r'/test/handler/', TestHandler),
(r'/test/(.*)/', TestcasePage),
)
def main():
application = webapp.WSGIApplication(urls, debug=True)
run_wsgi_app(application)
if __name__ == "__main__":
main()
```
#### File: jekky/jquery-douban/build.py
```python
import os
from optparse import OptionParser
""" Usage: python build.py [-acemnrRstu] [-AgGMj] [-h|--help] """
src_dir = 'src'
build_dir = 'build'
dist_dir = 'dist'
douban_js = '%s/jquery.douban.js' % dist_dir
min_js = '%s/jquery.douban.min.js' % dist_dir
version = 'VERSION'
core = ['core', 'utils', 'parser', 'client']
services = ['collection', 'event', 'miniblog', 'note', 'recommendation', \
'review', 'subject', 'tag', 'user']
handlers = ['jquery', 'gears', 'gadget', 'greasemonkey']
options = (
('-a', '--all', 'include all services'),
('-c', '--collection', 'include collection service'),
('-e', '--event', 'include event service'),
('-m', '--miniblog', 'include miniblog service'),
('-n', '--note', 'include note service'),
('-r', '--recommendation', 'include recommendation service'),
('-R', '--review', 'include review service'),
('-s', '--subject', 'include subject service'),
('-t', '--tag', 'include tag service'),
('-u', '--user', 'include user service'),
('-A', '--all-handlers', 'include all handlers'),
('-g', '--gadget', 'include gadget handler'),
('-G', '--gears', 'include gears handler'),
('-M', '--greasemonkey', 'include greasemonkey handler'),
('-j', '--jquery', 'include jquery handler'),
)
def main():
my_services = []
my_handlers = []
my_files = []
parser = OptionParser()
for short, long, help in options:
parser.add_option(long, short, action='store_true',
default=False, help=help)
opts, args = parser.parse_args()
if opts.all:
my_services = services
else:
for service in services:
if getattr(opts, service):
my_services.append(service)
if not my_services:
my_services = services
if opts.all_handlers:
my_handlers = handlers
else:
for handler in handlers:
if getattr(opts, handler):
my_handlers.append(handler)
if not my_handlers:
my_handlers = handlers
my_handlers = ['%s_handler' % handler for handler in my_handlers]
my_files = ['intro'] + core + my_services + my_handlers + ['outro']
print "Files need to build...\n%s" % ", ".join(my_files)
my_path = ['%s/%s.js' % (src_dir, file) for file in my_files]
try:
os.mkdir(dist_dir)
except OSError:
# Directory exists
pass
# Build js
print "\nBuilding..."
try:
os.system("cat %s | sed s/@VERSION/`cat %s`/ > %s" % \
(" ".join(my_path), version, douban_js))
print "Built: %s" % douban_js
print "\nMinifying..."
try:
os.system("java -jar %s/js.jar %s/build/min.js %s %s" % \
(build_dir, build_dir, douban_js, min_js))
print "Minified: %s" % min_js
except:
print "Failed to minifiy: %s" % min_js
except:
print "Failed to build: %s" % douban_js
if __name__ == '__main__':
main()
```
|
{
"source": "jeklein/rubicon-ml",
"score": 2
}
|
#### File: ui/views/header.py
```python
import dash_html_components as html
def make_header_layout():
"""The html layout for the dashboard's header view."""
return html.Div(
id="header",
className="header",
children=[
html.Div(id="title", className="header--project", children="rubicon-ml"),
html.Div(
id="links",
className="header--links",
children=[
html.A(
className="header--link",
href="https://capitalone.github.io/rubicon-ml",
children="Docs",
),
html.A(
className="header--link",
href="https://github.com/capitalone/rubicon-ml",
children="Github",
),
],
),
],
)
```
#### File: unit/sklearn/test_pipeline.py
```python
from unittest.mock import patch
from rubicon_ml.sklearn import RubiconPipeline
from rubicon_ml.sklearn.estimator_logger import EstimatorLogger
from rubicon_ml.sklearn.filter_estimator_logger import FilterEstimatorLogger
from rubicon_ml.sklearn.pipeline import Pipeline
def test_get_default_estimator_logger(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
pipeline = RubiconPipeline(project, steps)
logger = pipeline.get_estimator_logger()
assert type(logger) == EstimatorLogger
def test_get_user_defined_estimator_logger(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
logger = pipeline.get_estimator_logger("est")
assert type(logger) == FilterEstimatorLogger
def test_fit_logs_parameters(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
user_defined_logger = {"est": FilterEstimatorLogger(ignore_all=True)}
pipeline = RubiconPipeline(project, steps, user_defined_logger)
with patch.object(Pipeline, "fit", return_value=None):
with patch.object(
FilterEstimatorLogger, "log_parameters", return_value=None
) as mock_log_parameters:
pipeline.fit(["fake data"])
mock_log_parameters.assert_called_once()
def test_score_logs_metric(project_client, fake_estimator_cls):
project = project_client
estimator = fake_estimator_cls()
steps = [("est", estimator)]
pipeline = RubiconPipeline(project, steps)
with patch.object(Pipeline, "score", return_value=None):
with patch.object(EstimatorLogger, "log_metric", return_value=None) as mock_log_metric:
pipeline.score(["fake data"])
mock_log_metric.assert_called_once()
```
#### File: tests/unit/test_cli.py
```python
from unittest.mock import patch
import click
from click.testing import CliRunner
from rubicon_ml.cli import cli
def mock_click_output(**server_args):
click.echo("Running the mock server")
@patch("rubicon_ml.ui.dashboard.Dashboard.run_server")
@patch("rubicon_ml.ui.dashboard.Dashboard.__init__")
def test_cli(mock_init, mock_run_server):
mock_init.return_value = None
mock_run_server.side_effect = mock_click_output
runner = CliRunner()
result = runner.invoke(
cli,
["ui", "--root-dir", "/path/to/root"],
)
assert result.exit_code == 0
assert "Running the mock server" in result.output
```
|
{
"source": "jeKnowledge/horarios-inforestudante",
"score": 3
}
|
#### File: jeKnowledge/horarios-inforestudante/TimetableMaker.py
```python
from itertools import combinations
# Recebe dicionario de aulas de estrutura:
# { CLASS_ID:{
# T:{
# CLASS_T1,
# CLASS_T...
# },
# TP:{
# CLASS_TP...
# },
# ...
# }, ...
# }
# Devolve array de todas as combinacoes de turmas possiveis
# Refere-se aos elementos no dicionario por tuples: (aula, tipo, turma)
# IGNORA SOBREPOSICOES
def possibleCombinations(dictionary):
# Combinacoes de turmas validos (todos os tipos presentes)
# Para cada aula, i.e., e necessario fazer combinacao de turmas
combTurmasValidas = []
aulas = [] # List de todas as aulas por numero
#Fazer combinacoes dentro de cada aula
for aula in dictionary:
turmas = [] # List de de todas as turmas nesta aula (disciplina), como tuple
tipos = [] # Tipos de aula (T/TP/PL)
for tipo in dictionary[aula]:
tipos.append(tipo)
for turma in dictionary[aula][tipo]:
turmas.append((aula, tipo, turma))
combTurmas = combinations(turmas, len(tipos)) # Todas as combinacoes possiveis, incluindo (TP,TP,TP,TP)
for comb in combTurmas:
tiposNaComb = [] # Quais os tipos de aula nesta combinacao; deverao ser todos
for turma in comb:
tipo = turma[1] # Cada turma é representada por uma tuple (aula, tipo, turma); turma[1] devolve tipo
if tipo not in tiposNaComb:
tiposNaComb.append(tipo)
#Se a combinacao nao possuir todos os tipos de aula nao e valida
if set(tiposNaComb) != set(tipos):
continue
combTurmasValidas.append(comb)
aulas.append(aula)
# Fazer combinacoes de aulas, tendo em conta combinacoes "legais" de turmas
# Pelo mesmo processo que para as aulas:
# Fazer todas as combinacoes possiveis e remover as que nao incluirem todas as aulas
combAulas = combinations(combTurmasValidas, len(aulas))
combAulasValidas = [] # Todas as combinacoes de turmas
for comb in combAulas:
aulasInComb = [] # List de aulas incluidas nesta combinacao; deverao ser todas
for turmaComb in comb: # Combinacao de turmas para uma aula; tira-se o id da aula pelo primeiro elemento
if turmaComb[0][0] not in aulasInComb:
aulasInComb.append(turmaComb[0][0]) # comb[0] == (aula, tipo, turma); tuple[0] == aula
# Se esta combinacao de turmas possuir nao todas as aulas, nao e valida
if set(aulasInComb) != set(aulas):
continue
# Verificar se a combinação nao existe ja sob outra ordem
existe = False
for combValida in combAulasValidas:
if set(combValida) == set(comb):
existe = True
break
if existe:
continue
combAulasValidas.append(comb)
return combAulasValidas
# Recebe input:
# Dicionario:
# { CLASS_ID:{
# T:{
# [T1_obj, T1_obj, T1_obj,...],
# CLASS_T...
# },
# TP:{
# CLASS_TP...
# },
# ...
# }, ...
# Combinacoes validas de aulas:
# ( ( ((aula1, tipo1, turma1), (aula1, tipo2, turma1)), ((aula2, tipo1, turma1), (aula2, tipo2, turma1)) ), ... )
# Verifica se ha sobreposicao de aulas e se houver, remove-as
# Devolve lista de combinacoes sem sobreposicoes
def removeOverlaps(dictionary, validCombinations):
noOverlaps = [] # Resultado a devolver
for comb in validCombinations:
turmas = [] # turmas com "coordenadas", sob a forma (horaInicio, horaFim, (aula, tipo, turma))
# Criar tuples de horas e colocar na array
for aulaComb in comb:
for turma in aulaComb:
aulas = dictionary[turma[0]][turma[1]][turma[2]] # Tirar objetos Aula do dicionario (multiplos!)
for aula in aulas:
# Criar tuple com horas inicio/fim, dia e turma (disciplina/tipo/turma)
ref = (aula.horaInicio, aula.horaFim, aula.dia, (turma[0], turma[1], turma[2]))
turmas.append(ref)
# Criar pares
todosPares = combinations(turmas, 2)
pares = []
# Retirar pares de mesmas aulas
for par in todosPares:
# Verificar se turmas diferentes
turmaA = par[0][3]
turmaB = par[1][3]
if turmaA[0] != turmaB[0] or turmaA[1] != turmaB[1] or turmaA[2] != turmaB[2]:
pares.append(par)
# Verificar sobreposicao em cada par
combSemSobreposicoes = True
for par in pares:
a = par[0]
b = par[1]
# Dias diferentes?
if a[2] != b[2]:
continue
cedo = min(a[0], b[0])
tarde = max(a[1], b[1])
delta = tarde - cedo
# Aulas sobrepoem-se
if a[1]-a[0]+b[1]-b[0] > delta:
combSemSobreposicoes = False
break
if combSemSobreposicoes:
noOverlaps.append(comb)
return noOverlaps
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Style, Fill, Font
from random import randint
# Recebe input:
# Dicionario:
# { CLASS_ID:{
# T:{
# [T1_obj, T1_obj, T1_obj,...],
# CLASS_T...
# },
# TP:{
# CLASS_TP...
# },
# ...
# }, ...
# Combinacoes de aulas:
# ( ( ((aula1, tipo1, turma1), (aula1, tipo2, turma1)), ((aula2, tipo1, turma1), (aula2, tipo2, turma1)) ), ... )
# Grava um ficheiro xlsm (output.xlsm)
# Devolve workbook do openpyxl
def outputExcel(dictionary, combinations):
if len(combinations) == 0:
print("No combinations!")
return
wb = Workbook()
wb.remove_sheet(wb.active) # Apagar folha default
combinationNumber = 0
for comb in combinations:
ws = wb.create_sheet(str(combinationNumber)) # Criar uma nova folha com um id para referencia
# Labels de dia
ws['B1'] = "Segunda"
ws['C1'] = "Terça"
ws['D1'] = "Quarta"
ws['E1'] = "Quinta"
ws['F1'] = "Sexta"
ws['G1'] = "Sabado"
ws['H1'] = "Domingo"
# Labels de hora (30/30 minutos, das 8 as 22)
i = 2
for n in range(80,220,5):
ws['A'+str(i)] = str(int(n/10)) + "h" + str(int(((n/10)%1)*60)) + "m"
i += 1
# Desenhar aulas
for disciplina in comb:
for coord in disciplina:
aulaObjList = dictionary[coord[0]][coord[1]][coord[2]]
for aulaObj in aulaObjList:
# Tirar meia hora ao fim, para que nao haja merge sobreposto
cellRange = diaParaLetra(aulaObj.dia) + horaParaNumero(aulaObj.horaInicio) + ":"\
+ diaParaLetra(aulaObj.dia) + horaParaNumero(aulaObj.horaFim - 0.5)
ws.merge_cells(cellRange)
# Add label
ws[diaParaLetra(aulaObj.dia) + horaParaNumero(aulaObj.horaInicio)] = aulaObj.aulaNome +\
"," + aulaObj.turma
combinationNumber += 1 # Para referencia
wb.save('output.xlsx')
return wb
# ______ Helper functions para output: _________
def diaParaLetra(dia):
if dia == 0:
return "B"
if dia == 1:
return "C"
if dia == 2:
return "D"
if dia == 3:
return "E"
if dia == 4:
return "F"
if dia == 5:
return "G"
if dia == 6:
return "H"
def horaParaNumero(hora):
delta = hora - 8
return str(int(delta/0.5) + 2)
# _____________________________________________
# XLSXtoHTMLdemo
# Program to convert the data from an XLSX file to HTML.
# Uses the openpyxl library.
# Author: <NAME> - http://www.dancingbison.com
# Altered by <NAME> for the purposes of this program
import openpyxl
from openpyxl import load_workbook
def convertExcelToWeb(workbook):
worksheets = workbook._sheets
for worksheet in worksheets:
html_data = """
<html>
<head>
<title>
Horario
</title>
<head>
<body>
<table>
"""
ws_range = worksheet.iter_rows('A1:I30')
for row in ws_range:
html_data += "<tr>"
for cell in row:
if cell.value is None:
html_data += "<td>" + ' ' + "<td>"
else:
html_data += "<td>" + str(cell.value) + "<td>"
html_data += "<tr>"
html_data += "</table>\n</body>\n</html>"
with open(worksheet.title + ".html", "w") as html_fil:
html_fil.write(html_data)
# EOF
```
|
{
"source": "jeKnowledge/JekOffice",
"score": 2
}
|
#### File: JekOffice/interno/views.py
```python
from django.shortcuts import render,redirect
from django.http import HttpResponseNotFound,HttpResponse,HttpResponseRedirect
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.urls import resolve,reverse
import os
import docx
from .forms import RecrutamentoForm
from .models import Relatorios_recrutamento
from users.models import CustomUser
@login_required
def relatorio_novo_view(request):
my_form = RecrutamentoForm()
doc = docx.Document()
try:
if request.method == 'POST':
my_form = RecrutamentoForm(request.POST)
if my_form.is_valid():
dados_form = my_form.cleaned_data
relatorio = Relatorios_recrutamento.objects.create(**dados_form)
for instance in dados_form:
doc.add_paragraph(str(dados_form[instance]))
doc.save(os.getcwd() + '/media/relatorios/' + 'Recrutamento' + str(relatorio.ano) + '-'+relatorio.semestre[0] + '.docx')
print()
relatorio.documento.name = '/relatorios/' + 'Recrutamento' + str(relatorio.ano) +'-'+ relatorio.semestre[0] + '.docx'
relatorio.save()
return HttpResponseRedirect(reverse('criar_relatorios'))
except:
return HttpResponseNotFound('<h1>Error</h1>')
return render(request,"recrutamento_novo.html",{'form':my_form})
@login_required
def relatorio_lista_view(request):
lista = Relatorios_recrutamento.objects.all()
return render(request,"recrutamento_lista.html",{'lista':lista})
@login_required
def download_relatorio_recrutamento_view(request,relatorio_pk,*args,**kargs):
object = Relatorios_recrutamento.objects.get(pk=relatorio_pk)
file_path = object.documento.url[1:]
print(file_path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="")
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
return response
return HttpResponseNotFound('<h1>Error</h1>')
```
|
{
"source": "jekot1234/img_permutation",
"score": 3
}
|
#### File: jekot1234/img_permutation/hue_shift.py
```python
import os
import sys
import numpy as np
from PIL import Image
from pathlib import Path
import colorsys
import pygame
rgb_to_hsv = np.vectorize(colorsys.rgb_to_hsv)
hsv_to_rgb = np.vectorize(colorsys.hsv_to_rgb)
def shift_hue(arr, hout):
r, g, b, a = np.rollaxis(arr, axis=-1)
h, s, v = rgb_to_hsv(r, g, b)
h += hout
r, g, b = hsv_to_rgb(h, s, v)
arr = np.dstack((r, g, b, a))
return arr
def colorize(img, hue):
"""
Colorize PIL image `original` with the given
`hue` (hue within 0-360); returns another PIL image.
"""
arr = np.array(np.asarray(img).astype('float'))
new_img = Image.fromarray(shift_hue(arr, hue/360.).astype('uint8'), 'RGBA')
return new_img
try:
main_path = Path(sys.argv[1])
except:
print('No path given')
exit()
if not os.path.isdir(main_path):
print('No such directory exists')
exit()
file_paths = []
dirs = os.listdir(main_path)
dirs.sort()
i = 0
try:
hue = int(sys.argv[2])
except:
hue = 1
try:
offset = int(sys.argv[3])
except:
offset = 0
hue_arr = np.arange(start = 0, stop = 360, step=360/hue, dtype=np.uint16) + offset
for dir in dirs:
if os.path.isdir(os.path.join(main_path, dir)):
files = os.listdir(os.path.join(main_path, dir))
for file in files:
path = os.path.join(main_path, dir, file)
if os.path.isfile(path) and path.endswith('png'):
file_paths.append(path)
i += 1
print(file_paths)
for p in file_paths:
counter = 0
for h in hue_arr:
image = Image.open(p)
im = colorize(image, h)
im.save(p[:-4] + str(counter) + '.png')
counter += 1
```
|
{
"source": "jekot1234/serial_port_controll",
"score": 2
}
|
#### File: serial_port_controll/modbus/followerUI.py
```python
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(512, 535)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(10, 150, 491, 191))
self.groupBox_2.setObjectName("groupBox_2")
self.command_preview_2 = QtWidgets.QTextEdit(self.groupBox_2)
self.command_preview_2.setGeometry(QtCore.QRect(10, 50, 451, 41))
self.command_preview_2.setObjectName("command_preview_2")
self.label_12 = QtWidgets.QLabel(self.groupBox_2)
self.label_12.setGeometry(QtCore.QRect(10, 30, 101, 16))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.groupBox_2)
self.label_13.setGeometry(QtCore.QRect(10, 100, 101, 16))
self.label_13.setObjectName("label_13")
self.respoonse_preview_2 = QtWidgets.QTextEdit(self.groupBox_2)
self.respoonse_preview_2.setGeometry(QtCore.QRect(10, 120, 451, 41))
self.respoonse_preview_2.setObjectName("respoonse_preview_2")
self.address = QtWidgets.QLineEdit(self.centralwidget)
self.address.setGeometry(QtCore.QRect(160, 40, 151, 20))
self.address.setObjectName("address")
self.retries = QtWidgets.QLineEdit(self.centralwidget)
self.retries.setGeometry(QtCore.QRect(160, 70, 151, 20))
self.retries.setObjectName("retries")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 491, 131))
self.groupBox.setObjectName("groupBox")
self.run_station = QtWidgets.QPushButton(self.groupBox)
self.run_station.setGeometry(QtCore.QRect(330, 90, 75, 23))
self.run_station.setObjectName("run_station")
self.label_5 = QtWidgets.QLabel(self.groupBox)
self.label_5.setGeometry(QtCore.QRect(30, 30, 111, 21))
self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_5.setObjectName("label_5")
self.label_8 = QtWidgets.QLabel(self.groupBox)
self.label_8.setGeometry(QtCore.QRect(400, 60, 81, 21))
self.label_8.setObjectName("label_8")
self.baudrate = QtWidgets.QLineEdit(self.groupBox)
self.baudrate.setGeometry(QtCore.QRect(330, 60, 61, 20))
self.baudrate.setObjectName("baudrate")
self.label_6 = QtWidgets.QLabel(self.groupBox)
self.label_6.setGeometry(QtCore.QRect(10, 60, 131, 21))
self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_6.setObjectName("label_6")
self.listen = QtWidgets.QPushButton(self.groupBox)
self.listen.setGeometry(QtCore.QRect(230, 90, 75, 23))
self.listen.setObjectName("listen")
self.com_port = QtWidgets.QLineEdit(self.centralwidget)
self.com_port.setGeometry(QtCore.QRect(340, 40, 61, 20))
self.com_port.setObjectName("com_port")
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(410, 40, 81, 21))
self.label_7.setObjectName("label_7")
self.incoming_text = QtWidgets.QTextEdit(self.centralwidget)
self.incoming_text.setGeometry(QtCore.QRect(270, 380, 231, 131))
self.incoming_text.setObjectName("incoming_text")
self.outcoming_text = QtWidgets.QTextEdit(self.centralwidget)
self.outcoming_text.setGeometry(QtCore.QRect(10, 380, 231, 131))
self.outcoming_text.setObjectName("outcoming_text")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 360, 101, 16))
self.label.setObjectName("label")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(270, 360, 101, 16))
self.label_3.setObjectName("label_3")
self.groupBox.raise_()
self.groupBox_2.raise_()
self.address.raise_()
self.retries.raise_()
self.com_port.raise_()
self.label_7.raise_()
self.incoming_text.raise_()
self.outcoming_text.raise_()
self.label.raise_()
self.label_3.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.groupBox_2.setTitle(_translate("MainWindow", "Rozkaz"))
self.label_12.setText(_translate("MainWindow", "Podgląd rozkazu"))
self.label_13.setText(_translate("MainWindow", "Podgląd odpowiedzi"))
self.groupBox.setTitle(_translate("MainWindow", "Parametry stacji Follower"))
self.run_station.setText(_translate("MainWindow", "Uruchom"))
self.label_5.setText(_translate("MainWindow", "Adres stacji"))
self.label_8.setText(_translate("MainWindow", "Baudrate"))
self.label_6.setText(_translate("MainWindow", " Odstęp pomiedzy znakami"))
self.listen.setText(_translate("MainWindow", "Nasłuch"))
self.label_7.setText(_translate("MainWindow", "Port szeregowy"))
self.label.setText(_translate("MainWindow", "Tekst do wysłania"))
self.label_3.setText(_translate("MainWindow", "Tekst odebrany"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
```
#### File: serial_port_controll/modbus/MODBUS.py
```python
import serial as pyserial
import struct
import numpy as np
class ASCII_Station():
def __init__(self, port, baudrate) -> None:
self.serial = pyserial.Serial(port, baudrate, timeout=0)
```
|
{
"source": "jekriske-lilly/vision",
"score": 3
}
|
#### File: vision/test/test_image.py
```python
import os
import unittest
import sys
import torch
import torchvision
from PIL import Image
from torchvision.io.image import read_png, decode_png
import numpy as np
IMAGE_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
IMAGE_DIR = os.path.join(IMAGE_ROOT, "fakedata", "imagefolder")
def get_images(directory, img_ext):
assert os.path.isdir(directory)
for root, _, files in os.walk(directory):
for fl in files:
_, ext = os.path.splitext(fl)
if ext == img_ext:
yield os.path.join(root, fl)
class ImageTester(unittest.TestCase):
def test_read_png(self):
# Check across .png
for img_path in get_images(IMAGE_DIR, ".png"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
img_lpng = read_png(img_path)
self.assertTrue(img_lpng.equal(img_pil))
def test_decode_png(self):
for img_path in get_images(IMAGE_DIR, ".png"):
img_pil = torch.from_numpy(np.array(Image.open(img_path)))
size = os.path.getsize(img_path)
img_lpng = decode_png(torch.from_file(img_path, dtype=torch.uint8, size=size))
self.assertTrue(img_lpng.equal(img_pil))
with self.assertRaises(ValueError):
decode_png(torch.empty((), dtype=torch.uint8))
with self.assertRaises(RuntimeError):
decode_png(torch.randint(3, 5, (300,), dtype=torch.uint8))
if __name__ == '__main__':
unittest.main()
```
|
{
"source": "jekstrand/ev3opt",
"score": 2
}
|
#### File: ev3opt/gen/parse_enums.py
```python
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
"""
from mako.template import Template
import re
import sys
RENAMES = {
'OP' : 'Opcode',
'HWTYPE' : 'HWType',
'NXTCOLOR' : 'NXTColor',
'BLACKCOLOR' : 'BLACK',
'BLUECOLOR' : 'BLUE',
'GREENCOLOR' : 'GREEN',
'YELLOWCOLOR' : 'YELLOW',
'REDCOLOR' : 'RED',
'WHITECOLOR' : 'WHITE',
'ADDF' : 'AddF',
'SUBF' : 'SubF',
'MULF' : 'MulF',
'DIVF' : 'DivF',
'MOVEF_8' : 'MoveF_8',
'MOVEF_16' : 'MoveF_16',
'MOVEF_32' : 'MoveF_32',
'MOVEF_F' : 'MoveF_F',
'MATHTYPE' : 'MathSubcode',
'STRINGS' : 'String',
'INPUT_READSI' : 'InputReadSi',
'INPUT_READEXT' : 'InputReadExt',
}
def to_camel_case(s):
words = []
upper = True
for w in s.split('_'):
# Leave numbers separated by _
if words and words[-1][-1].isnumeric():
words.append('_')
words.append(w.lower().capitalize())
return ''.join(words)
def sanitize_name(name, camel_case):
if name != 'TST_SUBCODE' and name.startswith('TST_'):
name = name[4:]
if name in RENAMES:
return RENAMES[name]
elif camel_case:
return to_camel_case(name)
else:
return name
class Enum(object):
def __init__(self):
self._name = None
self._values = { }
def set_name(self, name):
self._name = name
def add_value(self, key, value):
self._values[key] = value
def name(self):
return sanitize_name(self._name, True)
def items(self):
for key, value in self._values.items():
yield sanitize_name(key, self._name == 'OP'), value
def parse_enums(f):
enums = { }
enum = None
for line in f.readlines():
if re.match(r'typedef *enum', line):
assert enum is None
enum = Enum()
elif re.match(r'[A-Z_]*;', line):
enum.set_name(line[0:-2])
assert enum._values
enums[enum.name()] = enum
enum = None
else:
m = re.match(' *(op)?(?P<name>[0-9A-Z_]+) *= *(?P<value>[x0-9A-F]+).*', line)
if m:
enum.add_value(m.group('name'), m.group('value'))
return enums
TEMPLATE = Template(LICENSE + """\
/* This file is auto-generated via gen/parse_enums.py. DO NOT EDIT */
% for enum in enums.values():
#[allow(dead_code)]
pub enum ${enum.name()} {
% for key, value in enum.items():
#[allow(non_camel_case_types)]
${key} = ${value},
% endfor
}
impl ${enum.name()} {
#[allow(dead_code)]
pub fn from_i32(i: i32) -> std::result::Result<${enum.name()}, &'static str> {
match i {
% for key, value in enum.items():
${value} => Ok(${enum.name()}::${key}),
% endfor
_ => Err("Invalid enum value for ${enum.name()}")
}
}
#[allow(dead_code)]
pub fn to_str(&self) -> &'static str {
match self {
% for key, value in enum.items():
${enum.name()}::${key} => "${key}",
% endfor
}
}
}
% endfor
""")
def main():
try:
with open(sys.argv[1]) as f:
print(TEMPLATE.render(enums=parse_enums(f)))
except Exception:
# In the event there's an error, this imports some helpers from mako
# to print a useful stack trace and prints it, then exits with
# status 1, if python is run with debug; otherwise it just raises
# the exception
if __debug__:
from mako import exceptions
sys.stderr.write(exceptions.text_error_template().render() + '\n')
sys.exit(1)
raise
if __name__ == '__main__':
main()
```
|
{
"source": "jekwatt/lightning_talks",
"score": 3
}
|
#### File: lightning_talks/name_main/two.py
```python
import one
print(">>>Top level in two.py")
print(repr(__name__))
print(repr(__name__))
one.main()
one.func()
def main():
print("hello from two.py")
if __name__ == '__main__':
print("two.py is being run directly")
main()
else:
print("two.py is being imported into another module")
```
|
{
"source": "Jekyll1021/gym",
"score": 2
}
|
#### File: assets/random_urdfs/parsing_script.py
```python
import trimesh
import os
import numpy as np
import xml.etree.ElementTree as ET
def generate_grasp_env(model_path, obj_index, out_path):
# step 0: read file
obj_index = str(obj_index).zfill(3)
mesh = trimesh.load(os.path.join(model_path, os.path.join(obj_index, obj_index+'.obj')))
# step 2: write as stl file
new_model_path = os.path.join(model_path, os.path.join(obj_index, obj_index+'.stl'))
mesh.export(new_model_path)
# step 3: record center of mass and box size
convex_com = mesh.center_mass
half_length = mesh.bounding_box.primitive.extents * 0.5
scale = np.random.uniform(0.02, 0.04)/np.median(half_length)
convex_com *= scale
half_length *= scale
# step 4: read template, change template and write to xml
tree = ET.parse(os.path.join("../fetch/random_obj_xml", "grasp_template.xml"))
root = tree.getroot()
root[3][0].attrib["file"] = os.path.join("..", new_model_path)
root[3][0].attrib["scale"] = str(scale) + ' ' + str(scale) + ' ' + str(scale)
# root[3][0].attrib -- {'file': path, 'name': 'obj0', 'scale': scale}
root[4][4].attrib["pos"] = str(half_length[0]) + ' ' + str(half_length[1]) + ' ' + str(half_length[2])
root[4][4][2].attrib["pos"] = str(convex_com[0]) + ' ' + str(convex_com[1]) + ' ' + str(convex_com[2])
root[4][4][2].attrib["size"] = str(half_length[0]/2) + ' ' + str(half_length[1]/2) + ' ' + str(half_length[2]/2)
# root[4][4][2].attrib["pos"] = str(convex_com[0]) + ' ' + str(convex_com[1]) + ' ' + str(convex_com[2])
# root[4][4][2].attrib -- {'type': 'box', 'size': bbox size, 'pos': centroid, 'rgba': '1 0 0 0', 'condim': '3', 'material': 'block_mat', 'mass': '2'}
tree.write(out_path)
def generate_peg_env(model_path, obj_index, out_path):
# step 0: read file
obj_index = str(obj_index).zfill(3)
mesh = trimesh.load(os.path.join(model_path, os.path.join(obj_index, obj_index+'.obj')))
# step 2: write as stl file
new_model_path = os.path.join(model_path, os.path.join(obj_index, obj_index+'.stl'))
mesh.export(new_model_path)
# step 3: record center of mass and box size
convex_com = mesh.center_mass
half_length = mesh.bounding_box.primitive.extents * 0.5
scale = 0.04/np.max(half_length)
convex_com *= scale
half_length *= scale
zaxis = np.zeros(3)
zaxis[np.argmin(half_length)] = 1
# step 4: read template, change template and write to xml
tree = ET.parse(os.path.join("../fetch/random_obj_xml", "peg_insert_template.xml"))
root = tree.getroot()
root[3][0].attrib["file"] = os.path.join("..", new_model_path)
root[3][0].attrib["scale"] = str(scale) + ' ' + str(scale) + ' ' + str(scale)
# root[3][0].attrib -- {'file': path, 'name': 'obj0', 'scale': scale}
root[4][5].attrib["pos"] = str(half_length[0]) + ' ' + str(half_length[1]) + ' ' + str(half_length[2])
root[4][5].attrib["zaxis"] = str(zaxis[0]) + ' ' + str(zaxis[1]) + ' ' + str(zaxis[2])
root[4][5][1].attrib["zaxis"] = str(zaxis[0]) + ' ' + str(zaxis[1]) + ' ' + str(zaxis[2])
max_offset = np.median(half_length)
handle_size_x, handle_size_y, handle_size_z = np.random.uniform(0.01, max_offset), np.random.uniform(0.01, max_offset), np.random.uniform(0.04, 0.06)
offset_x, offset_y = np.random.uniform(-max_offset + handle_size_x, max_offset - handle_size_x), np.random.uniform(-max_offset + handle_size_y, max_offset - handle_size_y)
root[4][5][2].attrib["zaxis"] = str(zaxis[0]) + ' ' + str(zaxis[1]) + ' ' + str(zaxis[2])
root[4][5][2].attrib["size"] = str(handle_size_x) + ' ' + str(handle_size_y) + ' ' + str(handle_size_z)
root[4][5][2].attrib["pos"] = str(convex_com[0] + offset_x) + ' ' + str(convex_com[1] + offset_y) + ' ' + str(convex_com[2] + handle_size_z - np.min(half_length))
# root[4][4][2].attrib -- {'type': 'box', 'size': bbox size, 'pos': centroid, 'rgba': '1 0 0 0', 'condim': '3', 'material': 'block_mat', 'mass': '2'}
root[4][5][3].attrib["pos"] = str(convex_com[0]) + ' ' + str(convex_com[1]) + ' ' + str(convex_com[2])
# root[4][5][3].attrib["size"] = str(half_length[0]/2) + ' ' + str(half_length[1]/2) + ' ' + str(half_length[2]/2)
root[4][5][4].attrib["pos"] = str(convex_com[0] + offset_x) + ' ' + str(convex_com[1] + offset_y) + ' ' + str(convex_com[2] + handle_size_z - 0.01 - np.min(half_length))
tree.write(out_path)
def generate_slide_env(model_path, obj_index, out_path):
# step 0: read file
obj_index = str(obj_index).zfill(3)
mesh = trimesh.load(os.path.join(model_path, os.path.join(obj_index, obj_index+'.obj')))
# step 2: write as stl file
new_model_path = os.path.join(model_path, os.path.join(obj_index, obj_index+'.stl'))
mesh.export(new_model_path)
# step 3: record center of mass and box size
convex_com = mesh.center_mass
half_length = mesh.bounding_box.primitive.extents * 0.5
scale = np.random.uniform(0.02, 0.04)/np.median(half_length)
convex_com *= scale
half_length *= scale
# step 4: read template, change template and write to xml
tree = ET.parse(os.path.join("../fetch/random_obj_xml", "slide_template.xml"))
root = tree.getroot()
root[3][0].attrib["file"] = os.path.join("..", new_model_path)
root[3][0].attrib["scale"] = str(scale) + ' ' + str(scale) + ' ' + str(scale)
# root[3][0].attrib -- {'file': path, 'name': 'obj0', 'scale': scale}
root[4][3][2].attrib["pos"] = str(half_length[0]) + ' ' + str(half_length[1]) + ' ' + str(half_length[2] + 0.2)
# root[4][3][2][2].attrib["size"] = str(half_length[0]) + ' ' + str(half_length[1]) + ' ' + str(half_length[2])
# root[4][3][2][2].attrib["pos"] = str(convex_com[0]) + ' ' + str(convex_com[1]) + ' ' + str(convex_com[2])
# root[4][4][2].attrib -- {'type': 'box', 'size': bbox size, 'pos': centroid, 'rgba': '1 0 0 0', 'condim': '3', 'material': 'block_mat', 'mass': '2'}
tree.write(out_path)
if __name__ == "__main__":
# loop
for i in range(1000):
for j in range(10):
generate_grasp_env("../stls/fetch/random_urdfs", i, os.path.join("../fetch/random_obj_xml", str(10*i+j)+"_grasp.xml"))
generate_peg_env("../stls/fetch/random_urdfs", i, os.path.join("../fetch/random_obj_xml", str(10*i+j)+"_peg.xml"))
generate_slide_env("../stls/fetch/random_urdfs", i, os.path.join("../fetch/random_obj_xml", str(10*i+j)+"_slide.xml"))
```
#### File: robotics/push/cam_push.py
```python
import os
from gym import utils
from gym.envs.robotics import push_env
# Ensure we get the path separator correct on windows
MODEL_XML_PATH = os.path.join('fetch', 'push.xml')
class CamPushEnv(push_env.PushEnv, utils.EzPickle):
def __init__(self, reward_type='sparse', goal_type='random', cam_type='fixed', gripper_init_type='fixed', act_noise=False, obs_noise=False, depth=False, two_cam=False, use_task_index=False, random_obj=False):
initial_qpos = {
'robot0:slide0': 0.405,
'robot0:slide1': 0.48,
'robot0:slide2': 0.0,
'object0:joint': [1.25, 0.53, 0.4, 1., 0., 0., 0.],
}
push_env.PushEnv.__init__(
self, MODEL_XML_PATH, block_gripper=True, n_substeps=20,
gripper_extra_height=0.0, target_in_the_air=False, target_offset=0.0,
obj_range=0.03, target_range=0.03, distance_threshold=0.03,
initial_qpos=initial_qpos, reward_type=reward_type, goal_type=goal_type,
cam_type=cam_type, gripper_init_type=gripper_init_type, act_noise=act_noise, obs_noise=obs_noise, depth=depth, two_cam=two_cam, use_task_index=use_task_index, random_obj=random_obj)
utils.EzPickle.__init__(self)
```
|
{
"source": "Jekyll1021/hindsight-experience-replay",
"score": 2
}
|
#### File: Jekyll1021/hindsight-experience-replay/actor_agent.py
```python
import torch
import os
from datetime import datetime
import numpy as np
from models import actor, actor_image, critic, critic_image
# from utils import sync_networks, sync_grads
from replay_buffer import replay_buffer
from her import her_sampler
import time
"""
ddpg with HER (MPI-version)
"""
def next_q_estimator(input_tensor, box_pose_tensor):
# counter = 1-input_tensor[:, -1:]
gripper_state_tensor = input_tensor[:, :3]
# next q = 1 if satisfied all conditions: x, y, z bound and norm magnitude bound.
offset_tensor = box_pose_tensor - gripper_state_tensor
# print(offset_tensor, box_pose_tensor, gripper_state_tensor)
# check upper-lower bound for each of x, y, z
x_offset = offset_tensor[:, 0]
_below_x_upper = (x_offset <= 0.04)
_beyond_x_lower = (x_offset >= -0.04)
y_offset = offset_tensor[:, 1]
_below_y_upper = (y_offset <= 0.045)
_beyond_y_lower = (y_offset >= -0.045)
z_offset = offset_tensor[:, 2]
_below_z_upper = (z_offset <= 0.)
_beyond_z_lower = (z_offset >= -0.086)
# check norm magnitude with in range:
norm = torch.norm(offset_tensor, dim=-1)
_magnitude_in_range = (norm <= 0.087)
next_q = torch.unsqueeze(_below_x_upper & _beyond_x_lower & \
_below_y_upper & _beyond_y_lower & \
_below_z_upper & _beyond_z_lower & \
_magnitude_in_range, 1).float()
return next_q
class actor_agent:
def __init__(self, args, env, env_params, image=True):
self.args = args
self.env = env
self.env_params = env_params
self.image = image
# create the network
if self.image:
self.actor_network = actor_image(env_params, env_params['obs'])
self.critic_network = critic_image(env_params, env_params['obs'] + env_params['action'])
else:
self.actor_network = actor(env_params, env_params['obs'])
self.critic_network = critic(env_params, env_params['obs'] + env_params['action'])
# load model if load_path is not None
if self.args.load_dir != '':
actor_load_path = self.args.load_dir + '/actor.pt'
model = torch.load(actor_load_path)
self.actor_network.load_state_dict(model)
critic_load_path = self.args.load_dir + '/critic.pt'
model = torch.load(critic_load_path)
self.critic_network.load_state_dict(model)
# sync the networks across the cpus
# sync_networks(self.actor_network)
# sync_networks(self.critic_network)
# build up the target network
# if self.image:
# self.actor_target_network = actor_image(env_params, env_params['obs'])
# else:
# self.actor_target_network = actor(env_params, env_params['obs'])
# # load the weights into the target networks
# self.actor_target_network.load_state_dict(self.actor_network.state_dict())
# if use gpu
if self.args.cuda:
self.actor_network.cuda()
# self.actor_target_network.cuda()
self.critic_network.cuda()
# create the optimizer
self.actor_optim = torch.optim.Adam(self.actor_network.parameters(), lr=self.args.lr_actor)
self.critic_optim = torch.optim.Adam(self.critic_network.parameters(), lr=self.args.lr_critic)
# her sampler
self.her_module = her_sampler(self.args.replay_strategy, self.args.replay_k, self.env().compute_reward)
# create the replay buffer
self.buffer = replay_buffer(self.env_params, self.args.buffer_size, self.her_module.sample_her_transitions, image=self.image)
# path to save the model
self.model_path = os.path.join(self.args.save_dir, self.args.env_name)
def learn(self):
"""
train the network
"""
# start to collect samples
for epoch in range(self.args.n_epochs):
total_actor_loss, total_critic_loss, count = 0, 0, 0
for _ in range(self.args.n_cycles):
if self.image:
mb_obs, mb_ag, mb_g, mb_sg, mb_actions, mb_hidden, mb_image = [], [], [], [], [], [], []
else:
mb_obs, mb_ag, mb_g, mb_sg, mb_actions, mb_hidden = [], [], [], [], [], []
for _ in range(self.args.num_rollouts_per_mpi):
# reset the rollouts
if self.image:
ep_obs, ep_ag, ep_g, ep_sg, ep_actions, ep_hidden, ep_image = [], [], [], [], [], [], []
else:
ep_obs, ep_ag, ep_g, ep_sg, ep_actions, ep_hidden = [], [], [], [], [], []
# reset the environment
e = self.env()
observation = e.reset()
obs = observation['observation']
ag = observation['achieved_goal']
g = observation['desired_goal']
img = observation['image']
sg = np.zeros(4)
hidden = np.zeros(64)
if self.image:
image_tensor = torch.tensor(observation['image'], dtype=torch.float32).unsqueeze(0)
if self.args.cuda:
image_tensor = image_tensor.cuda()
# start to collect samples
for _ in range(self.env_params['max_timesteps']):
with torch.no_grad():
input_tensor = self._preproc_inputs(obs)
if self.image:
pi = self.actor_network(input_tensor, image_tensor).detach()
else:
pi = self.actor_network(input_tensor).detach()
action = self._select_actions(pi, observation)
# feed the actions into the environment
observation_new, r, _, info = e.step(action)
obs_new = observation_new['observation']
ag_new = observation_new['achieved_goal']
img_new = observation_new['image']
# append rollouts
ep_obs.append(obs.copy())
ep_ag.append(ag.copy())
ep_g.append(g.copy())
ep_sg.append(sg.copy())
ep_actions.append(action.copy())
ep_hidden.append(hidden.copy())
if self.image:
ep_image.append(img.copy())
# re-assign the observation
obs = obs_new
ag = ag_new
img = img_new
observation = observation_new
ep_obs.append(obs.copy())
ep_ag.append(ag.copy())
ep_sg.append(sg.copy())
ep_hidden.append(hidden.copy())
if self.image:
ep_image.append(img.copy())
mb_obs.append(ep_obs)
mb_ag.append(ep_ag)
mb_g.append(ep_g)
mb_sg.append(ep_sg)
mb_actions.append(ep_actions)
mb_hidden.append(ep_hidden)
if self.image:
mb_image.append(ep_image)
# convert them into arrays
mb_obs = np.array(mb_obs)
mb_ag = np.array(mb_ag)
mb_g = np.array(mb_g)
mb_sg = np.array(mb_sg)
mb_actions = np.array(mb_actions)
mb_hidden = np.array(mb_hidden)
if self.image:
mb_image = np.array(mb_image)
self.buffer.store_episode([mb_obs, mb_ag, mb_g, mb_actions, mb_sg, mb_hidden, mb_image])
# store the episodes
else:
self.buffer.store_episode([mb_obs, mb_ag, mb_g, mb_actions, mb_sg, mb_hidden])
# train the network
actor_loss, critic_loss = self._update_network()
total_actor_loss += actor_loss
total_critic_loss += critic_loss
count += 1
# soft update
# self._soft_update_target_network(self.actor_target_network, self.actor_network)
# start to do the evaluation
success_rate = self._eval_agent()
print('[{}] epoch is: {}, actor loss is: {:.5f}, critic loss is: {:.5f}, eval success rate is: {:.3f}'.format(
datetime.now(), epoch, total_actor_loss/count, total_critic_loss/count, success_rate))
if self.args.cuda:
torch.cuda.empty_cache()
torch.save(self.actor_network.state_dict(), \
self.model_path + '/actor.pt')
torch.save(self.critic_network.state_dict(), \
self.model_path + '/critic.pt')
# pre_process the inputs
def _preproc_inputs(self, obs):
# concatenate the stuffs
inputs = obs
inputs = torch.tensor(inputs, dtype=torch.float32).unsqueeze(0)
if self.args.cuda:
inputs = inputs.cuda()
return inputs
# this function will choose action for the agent and do the exploration
def _select_actions(self, pi, observation):
action = pi.cpu().numpy().squeeze()
# add the gaussian
action += self.args.noise_eps * self.env_params['action_max'] * np.random.randn(*action.shape)
action = np.clip(action, -self.env_params['action_max'], self.env_params['action_max'])
# random actions...
# random_actions = np.random.uniform(low=-self.env_params['action_max'], high=self.env_params['action_max'], \
# size=self.env_params['action'])
offset = (observation["achieved_goal"] - observation["gripper_pose"])
# if observation['observation'][-1] < 1:
offset /= 0.05
offset += self.args.noise_eps * self.env_params['action_max'] * np.random.randn(*offset.shape)
offset = np.clip(offset, -self.env_params['action_max'], self.env_params['action_max'])
offset *= 0.05
offset /= np.random.uniform(0.04, 0.06)
# else:
# offset /= np.random.uniform(0.03, 0.07)
# offset += self.args.noise_eps * self.env_params['action_max'] * np.random.randn(*offset.shape)
good_action = np.clip(np.array([offset[0], offset[1], offset[2], np.random.uniform(-1, 1)]), -self.env_params['action_max'], self.env_params['action_max'])
# choose if use the random actions
if np.random.uniform() < self.args.random_eps:
action = good_action
if np.any(np.isnan(action)) or np.any(np.absolute(action) > 1):
action = np.random.uniform(-1, 1, 4)
return action
def _preproc_og(self, o):
o = np.clip(o, -self.args.clip_obs, self.args.clip_obs)
return o
# soft update
def _soft_update_target_network(self, target, source):
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_((1 - self.args.polyak) * param.data + self.args.polyak * target_param.data)
# update the network
def _update_network(self):
# sample the episodes
transitions = self.buffer.sample(self.args.batch_size)
# pre-process the observation and goal
o, o_next = transitions['obs'], transitions['obs_next']
input_tensor = torch.tensor(o, dtype=torch.float32)
counter = 1-input_tensor[:, -1:]
input_next_tensor = torch.tensor(o_next, dtype=torch.float32)
transitions['obs'] = self._preproc_og(o)
transitions['obs_next'] = self._preproc_og(o_next)
# start to do the update
inputs_norm = transitions['obs']
inputs_next_norm = transitions['obs_next']
# print("avg rewards {}".format(np.mean(transitions['r'])))
# transfer them into the tensor
inputs_norm_tensor = torch.tensor(inputs_norm, dtype=torch.float32)
inputs_next_norm_tensor = torch.tensor(inputs_next_norm, dtype=torch.float32)
actions_tensor = torch.tensor(transitions['actions'], dtype=torch.float32)
r_tensor = torch.tensor(transitions['r'], dtype=torch.float32)
box_tensor = torch.tensor(transitions['ag'], dtype=torch.float32)
box_next_tensor = torch.tensor(transitions['ag_next'], dtype=torch.float32)
if self.image:
img_tensor = torch.tensor(transitions['image'], dtype=torch.float32)
img_next_tensor = torch.tensor(transitions['image_next'], dtype=torch.float32)
if self.args.cuda:
inputs_norm_tensor = inputs_norm_tensor.cuda()
inputs_next_norm_tensor = inputs_next_norm_tensor.cuda()
actions_tensor = actions_tensor.cuda()
r_tensor = r_tensor.cuda()
box_tensor = box_tensor.cuda()
box_next_tensor = box_next_tensor.cuda()
input_tensor = input_tensor.cuda()
input_next_tensor = input_next_tensor.cuda()
counter = counter.cuda()
if self.image:
img_tensor = img_tensor.cuda()
img_next_tensor = img_next_tensor.cuda()
# calculate the target Q value function
with torch.no_grad():
# do the normalization
# concatenate the stuffs
# if self.image:
# actions_next = self.actor_target_network(inputs_next_norm_tensor, img_next_tensor)
# else:
# actions_next = self.actor_target_network(inputs_next_norm_tensor)
q_next_value = next_q_estimator(input_next_tensor, box_next_tensor)
q_next_value = q_next_value.detach()
target_q_value = r_tensor + self.args.gamma * q_next_value * counter
# print("expected q value {}".format(target_q_value.mean().item()))
# print(r_tensor, q_next_value, counter)
target_q_value = target_q_value.detach()
# print(torch.masked_select(target_q_value, mask), torch.masked_select(r_tensor, mask))
# clip the q value
clip_return = 1 / (1 - self.args.gamma)
target_q_value = torch.clamp(target_q_value, -clip_return, clip_return)
# the q loss
if self.image:
real_q_value = self.critic_network(inputs_norm_tensor, img_tensor, actions_tensor)
else:
real_q_value = self.critic_network(inputs_norm_tensor, actions_tensor)
# print(target_q_value, real_q_value, input_tensor[:, :3], actions_tensor[:, :3], box_tensor)
critic_loss = (target_q_value - real_q_value).pow(2).mean()
self.critic_optim.zero_grad()
critic_loss.backward()
# sync_grads(self.critic_network)
self.critic_optim.step()
critic_loss_value = critic_loss.detach().item()
# the actor loss
if self.image:
actions_real = self.actor_network(inputs_norm_tensor, img_tensor)
actor_loss = -self.critic_network(inputs_norm_tensor, img_tensor, actions_real).mean()
else:
actions_real = self.actor_network(inputs_norm_tensor)
actor_loss = -self.critic_network(inputs_norm_tensor, actions_real).mean()
actor_loss += self.args.action_l2 * (actions_real / self.env_params['action_max']).pow(2).mean()
# start to update the network
self.actor_optim.zero_grad()
actor_loss.backward()
# sync_grads(self.actor_network)
self.actor_optim.step()
actor_loss_value = actor_loss.detach().item()
if self.args.cuda:
torch.cuda.empty_cache()
return actor_loss_value, critic_loss_value
# do the evaluation
def _eval_agent(self):
total_success_rate = []
for _ in range(self.args.n_test_rollouts):
e = self.env()
observation = e.reset()
obs = observation['observation']
g = observation['desired_goal']
if self.image:
img_tensor = torch.tensor(observation['image'], dtype=torch.float32).unsqueeze(0)
if self.args.cuda:
img_tensor = img_tensor.cuda()
for _ in range(self.env_params['max_timesteps']):
with torch.no_grad():
input_tensor = self._preproc_inputs(obs)
if self.image:
pi = self.actor_network(input_tensor, img_tensor)
else:
pi = self.actor_network(input_tensor)
# convert the actions
actions = pi.detach().cpu().numpy().squeeze()
observation, _, _, info = e.step(actions)
obs = observation['observation']
g = observation['desired_goal']
if self.image:
img_tensor = torch.tensor(observation['image'], dtype=torch.float32).unsqueeze(0)
if self.args.cuda:
img_tensor = img_tensor.cuda()
total_success_rate.append(info['is_success'])
total_success_rate = np.array(total_success_rate)
local_success_rate = np.mean(total_success_rate)
return local_success_rate
```
#### File: Jekyll1021/hindsight-experience-replay/train.py
```python
import numpy as np
import gym
import os, sys
from arguments import get_args
# from mpi4py import MPI
# from subprocess import CalledProcessError
from ddpg_agent import ddpg_agent
from actor_agent import actor_agent
from open_loop_agent import open_loop_agent
"""
train the agent, the MPI part code is copy from openai baselines(https://github.com/openai/baselines/blob/master/baselines/her)
"""
def get_env_params(env):
obs = env.reset()
# close the environment
params = {'obs': obs['observation'].shape[0],
'goal': obs['desired_goal'].shape[0],
'action': env.action_space.shape[0],
'action_max': env.action_space.high[0],
'depth': env.env.depth,
'two_cam': env.env.two_cam
}
params['max_timesteps'] = env._max_episode_steps
return params
def launch(args):
# create the ddpg_agent
env = lambda: gym.make(args.env_name, reward_type='sparse', goal_type='random', cam_type='fixed', gripper_init_type='fixed', act_noise=False, obs_noise=False)
# get the environment parameters
env_params = get_env_params(env())
# create the ddpg agent to interact with the environment
ddpg_trainer = ddpg_agent(args, env, env_params, image=True)
# ddpg_trainer = actor_agent(args, env, env_params, image=True)
ddpg_trainer.learn()
if __name__ == '__main__':
# take the configuration for the HER
# os.environ['OMP_NUM_THREADS'] = '1'
# os.environ['MKL_NUM_THREADS'] = '1'
# os.environ['IN_MPI'] = '1'
# get the params
args = get_args()
# if MPI.COMM_WORLD.Get_rank() == 0:
if not os.path.exists(args.save_dir):
os.mkdir(args.save_dir)
# path to save the model
model_path = os.path.join(args.save_dir, args.env_name)
if not os.path.exists(model_path):
os.mkdir(model_path)
launch(args)
```
|
{
"source": "JekyllAndHyde8999/Cauldron",
"score": 2
}
|
#### File: Cauldron/main/views.py
```python
from django.shortcuts import render, redirect
from django.conf import settings
from django.contrib import messages
from .utils import nlp
import re
import time
# Create your views here.
def home(request):
return render(request, "main/home.html", {})
def about(request):
return render(request, "main/about.html", {})
def generate(request):
context = {}
if request.method == "POST":
passage = re.sub('\[\w+\]', '', request.POST.get('passage'))
# start = time.time()
questions = nlp(passage)[:3]
# end = time.time()
context = {
'passage': passage,
'questions': questions,
# 'time': round(end - start, 2),
'num_questions': len(questions)
}
return render(request, "main/generate.html", context)
```
|
{
"source": "JekyllAndHyde8999/LetsNote",
"score": 2
}
|
#### File: LetsNote/users/serializers.py
```python
from rest_framework import serializers, validators
from django.contrib.auth.models import User
from .models import Profile
class UserSerializer(serializers.ModelSerializer):
# notes = serializers.StringRelatedField(many=True)
email = serializers.EmailField(
validators=[
validators.UniqueValidator(queryset=User.objects.all())
]
)
def create(self, validated_data):
return User.objects.create_user(**validated_data)
def update(self, instance, validated_data):
instance.username = validated_data.get('username', instance.username)
instance.email = validated_data.get('email', instance.email)
instance.save()
return instance
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password')
# class ProfileSerializer(serializers.ModelSerializer):
# user = serializers.StringRelatedField(many=False)
# class Meta:
# model = Profile
# fields = ('profile_pic',)
```
#### File: LetsNote/users/signals.py
```python
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
```
|
{
"source": "jelaip/Raspi-Malette-D",
"score": 3
}
|
#### File: jelaip/Raspi-Malette-D/matriceBt.py
```python
from guizero import Box, PushButton
from buttonClass import *
class matriceBt:
def __init__(self,app,grid,ligne,colone,waffle):
self.grid = grid
self.ligne = ligne
self.colone = colone
self.app = app
self.matrix = waffle
self.createMat()
def createMat(self):
box = Box(self.app,layout="grid", grid=self.grid)
for x in range(self.ligne):
for y in range(self.colone):
b = buttonClass(box,self.matrix,x,y,self.ligne,self.colone)
```
#### File: jelaip/Raspi-Malette-D/moduleDTH11.py
```python
from guizero import *
import Adafruit_DHT
""" install moduleDTH11
sudo apt update
sudo apt install build-essential python-dev
git clone http://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT"""
class moduleDTH11:
def __init__(self,app, pin,grid):
self.grid = grid
self.temp = 0
self.humi = 0
self.app = app
self.sensor = Adafruit_DHT.DHT11
self.DHT11_pin = pin
self.createUI()
def createUI(self):
txt = Text(self.app,text = "DTH11\n"+"temp: "+str(self.temp)+"\n"+
"humi: "+str(self.humi)+"\n",grid=self.grid,align="left")
def update(self):
humidity, temperature = Adafruit_DHT.read_retry(self.sensor,self.DHT11_pin)
if humidity is not None and temperature is not None:
self.humi = humidity
self.temp = temperature
txt.value = "DTH11\n"+"temp: "+str(self.temp)+"\n"+"humi: "+str(self.humi)+"\n"
else:
info("error", "Failed to get reading from the sensor")
```
|
{
"source": "JELambert/sswebdata",
"score": 3
}
|
#### File: sswebdata/sswebdata/GetData.py
```python
import numpy as np
import pandas as pd
import requests
import json
from bs4 import BeautifulSoup
import urllib.request as urllib2
class Data:
def get_ucdp(ucdp):
"""
Version = 18.1
Options for ucdp:
"nonstate" = Nonstate conflict dataset
"dyadic" = Dyadic conflict dataset
"ucdp" = Full UCDP data set
"onesided" = Onesided conflict data sets
"battledeaths" = Battedeaths data set
"gedevents" = The geo-located events data set
"""
if ucdp == "nonstate":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/nonstate/18.1?pagesize=1000&page=0'
elif ucdp == "dyadic":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/dyadic/18.1?pagesize=1000&page=0'
elif ucdp == "ucdp":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/ucdpprioconflict/18.1?pagesize=1000&page=0'
elif ucdp == "onesided":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/onesided/18.1?pagesize=1000&page=0'
elif ucdp == "battledeaths":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/battledeaths/18.1?pagesize=1000&page=0'
elif ucdp == "gedevents":
url_ucdp = 'http://ucdpapi.pcr.uu.se/api/gedevents/18.1?pagesize=1000&page=0'
r = requests.get(url_ucdp).json()
ucdp_df = pd.DataFrame(r['Result'])
while r['NextPageUrl'] != '':
r = requests.get(r['NextPageUrl']).json()
df = pd.DataFrame(r['Result'])
ucdp_df = ucdp_df.append(df)
return ucdp_df
def get_reign(frame):
"""
args :
frame = "monthly" - de-duplicated based on coups
"yearly" - de-duplicated based on coups
"full" - non de-duplicated
notes :
I added a democracy and autocracy variable (foreign occupied and warlordism are in the autocratic cateogry)
"""
url = 'https://oefdatascience.github.io/REIGN.github.io/menu/reign_current.html'
open_url = urllib2.urlopen(url)
soup = BeautifulSoup(open_url, 'html.parser')
p_tags = soup.findAll('p')
href = p_tags[4].find('a')
reign_csv = href.attrs['href']
reign_df = pd.read_csv(reign_csv)
reign_df['democracy'] = np.where((reign_df.government == "Presidential Democracy") | (reign_df.government == "Parliamentary Democracy"), 1, 0)
reign_df['autocracy'] = np.where((reign_df.government == "Personal Dictatorship") | (reign_df.government == "Party-Personal") | (reign_df.government == "Provisional - Military")
| (reign_df.government == "Party-Personal-Military Hyrbrid") | (reign_df.government == "Oligarchy") | (reign_df.government == "Monarchy")
| (reign_df.government == "Military") | (reign_df.government == "Military-Personal") | (reign_df.government == "Provisional - Civilian") | (reign_df.government == "Foreign/Occupied")
| (reign_df.government == "Dominant Party") | (reign_df.government == "Indirect Military") | (reign_df.government == "Warlordism")
| (reign_df.government == "Party-Military"), 1, 0)
if frame == "full":
reign = reign_df
elif frame == "monthly":
reign = reign_df.sort_values('pt_attempt', ascending=False).drop_duplicates(['country', 'year', 'month']).sort_index()
reign['day'] = 1
reign['date']= pd.to_datetime(reign['year']*10000+reign['month']*100+reign['day'],format='%Y%m%d')
elif frame == "yearly":
reign = reign_df.sort_values(by=['ccode', 'year', 'pt_attempt'])
reign = reign.drop_duplicates(subset=['ccode', 'year'], keep='last')
reign['day'] = 1
reign['date']= pd.to_datetime(reign['year']*10000+reign['month']*100+reign['day'],format='%Y%m%d')
return reign
```
|
{
"source": "jelambrar96/muralia",
"score": 3
}
|
#### File: muralia/muralia/utils.py
```python
import numpy as np
import cv2
import matplotlib.pyplot as plt
# ----------------------------------------------------------------------------
def imshow(image, title='', figure=True, cmap=None, figsize=None, show=True,
axis='off'):
if figure:
if figsize == None:
plt.figure()
else:
plt.figure(figsize=figsize)
#
if cmap=='gray':
plt.imshow(image, cmap=cmap)
else:
plt.imshow(image)
#
if title:
plt.title(title)
plt.axis(axis)
if show:
plt.show()
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def imread(filename, cmap='color'):
if cmap=='gray':
return cv2.imread(filename, 0)
else:
return cv2.imread(filename, 1)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def is_square(image):
h,w = image.shape[:2]
if h == w:
return True
return False
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def cvt_square(image):
h,w = image.shape[:2]
if h > w:
dif = int((h - w)/2)
out_image = image[dif:dif + w, :]
return out_image
elif w > h:
dif = int((w - h)/2)
out_image = image[:, dif:dif + h]
return out_image
else:
return image
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def resize_image(image, shape, interpolation='cubic'):
#def resize_image(image, shape):
resolution = shape[:2]
if is_square(image):
image = cvt_square(image)
# -------------------------------------------------------------------------
#
if interpolation=='linear':
inter = cv2.INTER_LINEAR
elif interpolation=='cubic':
inter = cv2.INTER_CUBIC
else:
inter = interpolation
#
# ------------------------------------------------------------------------
rimg = cv2.resize(image, dsize=resolution, interpolation=inter)
#rimg = cv2.resize(image, (590, 590), interpolation=cv2.INTER_CUBIC)
return rimg
#return cv2.resize(image, resolution)
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def resize_format(image, format):
h_out, w_out = format[:2]
h_in, w_in = image.shape[:2]
#
# print(format)
# print(image.shape)
# jk = input()
#
if w_in/h_in > w_out/h_out:
w = w_in * w_out // h_out
image = crop_image(image, (0, h_in), ((w_in - w)//2, (3 * w_in - w)//2))
#print('case 1')
elif w_in/h_in < w_out/h_out:
h = h_in * h_out // w_out
image = crop_image(image, ((h_in - h)//2, (3 * h_in - h)//2), (0, w_in))
#print('case 2')
else:
pass
#print('case 3')
out_image = resize_up_main_image(image, format[::-1])
return out_image
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def crop_image(image, pt1 = (0,0), pt2=None):
h1,w1 = pt1
if pt2==None:
pt2 = image.shape[:2]
h2,w2 = pt2
return image[h1:h2, w1:w2]
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def resize_up_main_image(image, resolution):
resolution = resolution[:2]
print(resolution)
return cv2.resize(image, dsize=resolution, interpolation=cv2.INTER_CUBIC)
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
def imwrite(filename, image):
#print(filename)
return cv2.imwrite(filename, image)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def imgrotate(image, index):
output = np.rot90(np.fliplr(image), index % 4) if (index // 4) else np.rot90(image, index % 4)
return output
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def format_number(i):
return '%04d'%(i)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def format_percent(item):
#fmt_str = '%' + '2.' + str(decimals) + 'f' #+ r'%' + ' '*4
return '%2.2f'%(item)
#return fmt_str%(item)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def square_image(image, minishape):
return resize_image(cvt_square(image), minishape, interpolation='cubic')
```
|
{
"source": "jelambrar96/pyconway",
"score": 3
}
|
#### File: pyconway/pyconway/board.py
```python
from typing import Tuple, overload
# dependences
import numpy as np
# another python files
from .conv import conv2dconway, conv3dconway
class ConwayBoard:
def __init__(self, initial_state, boundary='fill'):
assert(boundary in ['fill', 'wrap'], 'Expected "fill" or "wrap" on boundary argument')
self._boundary = boundary
if not np.ndim(initial_state) == 2:
raise ValueError('Input must both be 2-D arrays')
self.state = initial_state.copy()
# self.state = board.astype(np.uint8)
# set default rules
self._s_rule = np.array([2, 3])
self._b_rule = np.array([3])
def getState(self):
return self.state
def getRules(self):
return self._s_rule, self._b_rule
def __next(self):
conv_result = conv2dconway(self.state, boundary=self._boundary)
temp0 = np.logical_and(self.state == True, np.isin(conv_result, self._s_rule))
temp1 = np.logical_and(self.state == False, np.isin(conv_result, self._b_rule))
self.state = np.logical_or(temp0, temp1)
def next(self, iterations = 1):
for _ in range(iterations):
self.__next()
def setRules(self, s_rule, b_rule):
self._s_rule = np.array(s_rule)
self._b_rule = np.array(b_rule)
class ConwayBoard3C(ConwayBoard):
def __init__(self, board, boundary='fill'):
assert(boundary in ['fill', 'wrap'], 'Expected "fill" or "wrap" on boundary argument')
self._boundary = boundary
if not np.ndim(board) == 3:
raise ValueError('Input must both be 3-D arrays')
self.state = board.copy()
self._s_rule = np.array([2, 3])
self._b_rule = np.array([3])
@overload
def next(self, iterations = 1):
channels = self.state.shape[2]
for i in range(channels):
temp_state = self.state[:,:,i]
for j in range(iterations):
conv_result = conv2dconway(temp_state, boundary=self._boundary)
temp0 = np.logical_and(temp_state == True, np.isin(conv_result, self._s_rule))
temp1 = np.logical_and(temp_state == False, np.isin(conv_result, self._b_rule))
temp_state = np.logical_or(temp0, temp1)
self.state[:,:,i] = temp_state
class ConwayBoard3D(ConwayBoard):
def __init__(self, board, boundary='fill'):
assert(boundary in ['fill', 'wrap'], 'Expected "fill" or "wrap" on boundary argument')
self._boundary = boundary
if not np.ndim(board) == 3:
raise ValueError('Input must both be 3-D arrays')
self.state = board.copy()
self._s_rule = np.array([2, 3])
self._b_rule = np.array([3])
@overload
def __next(self):
conv_result = conv3dconway(self.state, boundary=self._boundary)
temp0 = np.logical_and(self.state == True, np.isin(conv_result, self._s_rule))
temp1 = np.logical_and(self.state == False, np.isin(conv_result, self._b_rule))
self.state = np.logical_or(temp0, temp1)
```
|
{
"source": "Jelaque/Computacion-Bioinspirada",
"score": 3
}
|
#### File: Computacion-Bioinspirada/Evolutive Computing/initFuncTree.py
```python
import numpy as np
import random as rm
def res(x,y): return x - y
def mul(x,y): return x * y
def div(x,y): return x / y
def sum(x,y): return x + y
ops = {'+':sum, '-':res, '*':mul, '/':div}
list_vals = "xyzwvu"
list_ops = "+-*/"
vals = np.zeros(0)
def init_func_tree(size,n_vals,entry):
sign = False
i = 0
while i < len(entry):
if entry[i][0] == 0:
sign = True
i += 1
func_tree = []
i = 0
while i < size:
var = None
if not (i & 1):
if rm.uniform(0,1) > .8:
var = round(rm.uniform(-100,100),2)
else:
var = list_vals[rm.randint(0,n_vals-1)]
if sign and i - 1 > 0 and func_tree[i-1] == '/':
func_tree[i-1] = list_ops[rm.randint(0,len(list_ops)-2)]
else:
var = list_ops[rm.randint(0,len(list_ops)-1)]
func_tree.append(var)
i += 1
return func_tree
```
#### File: Computacion-Bioinspirada/Evolutive Computing/mef.py
```python
import random as rm
import numpy as np
import queue as qu
statery = "ABCDEFGHI"
def evolutionary(total_individuals,n_states,entry,epochs):
population = np.zeros((total_individuals, (n_states*7)+1))
init_states = np.zeros(total_individuals)
pos_fit = n_states*7
i = 0
while i < total_individuals:
population[i], init_states[i] = init_mef_individual(n_states)
i += 1
population = fit_population(population, entry, init_states, total_individuals, pos_fit)
print_population(population)
i = 0
while i < epochs:
new_population = np.copy(population)
new_init_states = np.copy(init_states)
i += 1
j = 0
while j < total_individuals:
rand = rm.uniform(0,1)
if rand <= 0.1:
s = rm.randint(0,n_states-1)
while s == new_init_states[j]:
s = rm.randint(0,n_states-1)
new_population[j][s*7] = 0
elif rand <= 0.3:
s = rm.randint(0,n_states-1)
new_population[j][s*7] = 2
new_population[j][int(new_init_states[j])] = 1
new_init_states[j] = s
elif rand <= 0.5:
s = rm.randint(0,n_states-1)
pos = s*7
temp = new_population[j][pos+1]
new_population[j][pos+1] = new_population[j][pos+2]
new_population[j][pos+2] = temp
elif rand <= 0.7:
s = rm.randint(0,n_states-1)
extra = rm.randint(1,2)
pos = (s * 7) + 2 + extra
val = new_population[j][pos]
new_population[j][pos] = abs(val-1)
elif rand <= 0.9:
s = rm.randint(0,n_states-1)
extra = rm.randint(1,2)
ns = rm.randint(0,n_states-1)
while new_population[j][7*ns] == 0:
ns = rm.randint(0,n_states-1)
new_population[j][(s*7) + 4 + extra] = ns
else:
s = rm.randint(0,n_states-1)
if new_population[j][7*s] == 0:
new_population[j][7*s] = 1
print(j)
j += 1
new_population = fit_population(new_population, \
entry, new_init_states, total_individuals, pos_fit)
new_population = new_population[new_population[:,pos_fit].argsort(axis=0)]
population = population[population[:,pos_fit].argsort(axis=0)]
j = 0
k = int(total_individuals/2)
while j < k:
population[j] = new_population[k+j]
j += 1
print(population)
def print_population(population):
for individual in population:
i = 0
print(i+1,') ',end="")
for s in individual:
if i%5 == 0 or i%6 == 0:
print(statery[int(s)],end="")
else:
print(s,end="")
i += 1
print()
def aptitude(val1,val2,n):
i = 0
c = 0
while i < n:
if val1[i] == val2[i]:
c += 1
i += 1
return float(c/n)
def fit_population(population, entry, init_states, n, n_fit):
i = 0
while i < n:
population[i][n_fit] = fit(population[i],entry,init_states[i])
i += 1
return population
def fit(individual,entry,init_state):
outcome = ""
n = len(entry)
state = int(init_state)
i = 0
while i < n:
symbol = entry[i]
pos = state*7
extra = 3
if individual[pos+2] == int(symbol):
extra = 4
outcome += str(individual[pos+extra])
if individual[int(individual[pos+extra+2])] != 0:
state = int(individual[pos+extra+2])
i += 1
return aptitude(entry,outcome,n)
def init_mef_individual(n):
population = np.zeros((7*n)+1)
active_states = np.zeros(n)
init_state = rm.randint(0,n-1)
qStates = qu.Queue()
"""First case"""
outState1,outState2 = fill_individual(init_state, population, n, 2)
qStates.put(outState1)
qStates.put(outState2)
active_states[init_state] = 1
while not qStates.empty():
state = qStates.get()
if active_states[state] == 0:
outState1, outState2 = fill_individual(state, population, n, 1)
qStates.put(outState1)
qStates.put(outState2)
active_states[state] = 1
i = 0
while i < n:
if active_states[i] == 0:
outState1, outState2 = fill_individual(state, population, n, 0)
i += 1
return population, init_state
def fill_individual(state, individual, n, type_state):
it = 7*state
individual[it] = type_state
symbol_in = rm.randint(0,1)
individual[it+1] = symbol_in
individual[it+2] = abs(symbol_in-1)
symbol_out1 = rm.randint(0,1)
symbol_out2 = rm.randint(0,1)
individual[it+3] = symbol_out1
individual[it+4] = symbol_out2
state_out1 = rm.randint(0,n-1)
state_out2 = rm.randint(0,n-1)
individual[it+5] = state_out1
individual[it+6] = state_out2
return state_out1, state_out2
evolutionary(8,5,"011011011011011",100)
```
#### File: Computacion-Bioinspirada/Evolutive Computing/real.py
```python
import random as rand
import numpy as np
import math
def scale(X, x_min, x_max):
nom = (X-X.min(axis=0))*(x_max-x_min)
denom = int(X.max(axis=0) - X.min(axis=0))
denom[denom==0] = 1
return x_min + nom/denom
def r_genetic(limit,dec,n_genes,N,p_cross,p_mut,func,it,mode):
population = rget_population(dec,n_genes,N,limit)
print('Poblacion inicial')
print_pop_initial(population)
fitness = rdecode(population,func)
print_fitness(population,fitness,N)
i = 1
it = it + 1
while i < it:
print('****Iteracion ',i,'****')
parents = rmating_pool(population, fitness, mode)
population = rselect_parents(population, parents, fitness, p_cross, p_mut)
fitness = rdecode(population,func)
print('Nueva Poblacion')
print_pop_initial(population)
print_fitness(population,fitness,N)
i += 1
def print_pop_initial(population):
i = 1
for row in population:
print(i,')\t\t',row)
i += 1
print()
def print_fitness(population,fitness,n):
i = 1
print('Calcular la Aptitud para cada Individudo')
j = 0
for row in population:
print(i,')\t\t',row,'\t\t',fitness[j])
i += 1
j += 1
print()
def rget_population(dec,n_genes,N,limit):
population = np.random.rand(N,n_genes)
for i in range(0,2):
population[:,i] = np.interp(population[:,i], (min(population[:,i]), max(population[:,i])), (-10,10))
population = np.around(population, decimals = dec)
return population
def rdecode(population, func):
fitness = np.zeros(population.shape[0])
for i in range(0,population.shape[0]):
fitness[i] = func(population[i])
return fitness
def rmating_pool(population, fitness, mode):
n = population.shape[0]
parents = np.zeros(n)
for i in range(0,n):
a = rand.randint(0,n-1)
b = rand.randint(0,n-1)
val = mode(fitness[a], fitness[b])
if val == fitness[a]:
parents[i] = a
else:
parents[i] = b
print(a+1,'\t\t',b+1,'\t\t=>\t\t',int(parents[i])+1,'\t\t=>\t\t',population[int(parents[i])])
print()
return parents
def rselect_parents(population, parents, fitness, p_cross, p_mut):
population = np.around(population,decimals=5)
p_new = population
n = population.shape[0]
for i in range(0,n):
a = rand.randint(0,n-1)
b = rand.randint(0,n-1)
r = population[int(parents[a])]
s = population[int(parents[b])]
pcss = 0
print('Seleccion de Padres')
print(a+1,'\t',b+1,' => ',int(parents[a])+1,' - ',int(parents[b])+1,' => ',r,' - ',s)
if rand.uniform(0,1) >= p_cross:
beta1 = rand.uniform(-0.5,1.5)
beta2 = rand.uniform(-0.5,1.5)
z = r
x = r
y = s
x = [z[0],y[0]]
y = [z[1],y[1]]
H = abs(x[0]-x[1])
lim = H*beta1
v1 = round(rand.uniform(min(x)-lim,max(x)+lim),5)
H = abs(y[0]-y[1])
lim = H*beta2
v2 = round(rand.uniform(min(y)-lim,max(y)+lim),5)
if(v1 > 10 and v1 < -10) or (v2 > 10 and v2 < -10):
if fitness[int(parents[a])] < fitness[int(parents[b])]:
p_new[i] = r
else:
p_new[i] = s
else:
p_new[i] = [v1,v2]
pcss = 1
print('Cruzamiento')
else:
if fitness[int(parents[a])] < fitness[int(parents[b])]:
p_new[i] = r
else:
p_new[i] = s
print('Sin Cruzamiento')
print(p_new[i])
if rand.uniform(0,1) >= p_mut:
d = mutation(p_new[i])
if(d[0] <= 10 and d[0] >= -10) or (d[1] <= 10 and d[1] >= -10):
p_new[i] = d
print('Mutacion')
else:
print('Sin mutacion')
print(p_new[i])
print()
print()
return p_new
def mutation(vec):
for i in range(0,len(vec)):
vec[i] = round(rand.uniform(vec[i]-0.3,vec[i]+0.3),5)
return vec
p_cross = 0.75
p_mut = 0.5
n = 5000
def f(x):
return -math.cos(x[0])*math.cos(x[1])*math.exp(-math.pow(x[0]-math.pi,2)-math.pow(x[1]-math.pi,2))
print(f([8.29,-1.21]))
print('Parametros:')
print('- Cantidad de Individuos: ',16)
print('- Cantidad de Genes por Individuo: ',2)
print('- Selección por torneo (2)')
print('- Probabilidad de Cruzamiento: ',p_cross)
print('- Cruzamiento BLX-Alpha, Alpha = ',0.5)
print('- Probabilidad de Mutación: ',p_mut)
print('- Mutación Uniforme')
print('- Cantidad de Iteraciones: ',n)
r_genetic([[-100,100],[-100,100]],5,2,16,p_cross,p_mut,f,n,min)
```
|
{
"source": "Jelaque/sap-starterkit",
"score": 2
}
|
#### File: sap-toolkit/sap_toolkit/utils.py
```python
from PIL import Image
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import pickle
import os
from tqdm import tqdm
from os.path import join, isfile
FPS = 30
def mkdir2(path):
if not os.path.isdir(path):
os.makedirs(path)
return path
def imread(path, method='PIL'):
return np.array(Image.open(path))
def gen_results(db, opts, filename):
def ltrb2ltwh_(bboxes):
if len(bboxes):
if bboxes.ndim == 1:
bboxes[2:] -= bboxes[:2]
else:
bboxes[:, 2:] -= bboxes[:, :2]
return bboxes
def ltrb2ltwh(bboxes):
bboxes = bboxes.copy()
return ltrb2ltwh_(bboxes)
seqs = db.dataset['sequences']
print('Merging and converting results')
results_ccf = []
miss = 0
for sid, seq in enumerate(tqdm(seqs)):
frame_list = [img for img in db.imgs.values() if img['sid'] == sid]
results = pickle.load(open(join(opts.out_dir, seq + '.pkl'), 'rb'))
results_parsed = results['results_parsed']
timestamps = results['timestamps']
tidx_p1 = 0
for ii, img in enumerate(frame_list):
# pred, gt association by time
t = ii/FPS
while tidx_p1 < len(timestamps) and timestamps[tidx_p1] <= t:
tidx_p1 += 1
if tidx_p1 == 0:
# no output
miss += 1
bboxes, scores, labels = [], [], []
masks, tracks = None, None
else:
tidx = tidx_p1 - 1
result = results_parsed[tidx]
bboxes, scores, labels, masks = result[:4]
if len(result) > 4:
tracks = result[4]
else:
tracks = None
# convert to coco fmt
n = len(bboxes)
if n:
# important: must create a copy, it is used in subsequent frames
bboxes_ltwh = ltrb2ltwh(bboxes)
for i in range(n):
result_dict = {
'image_id': int(img['id']),
'bbox': [float(a) for a in bboxes_ltwh[i]],
'score': float(scores[i]),
'category_id': int(labels[i]),
}
if masks is not None:
result_dict['segmentation'] = masks[i]
results_ccf.append(result_dict)
out_path = join(opts.out_dir, filename)
if opts.overwrite or not isfile(out_path):
json.dump(results_ccf, open(out_path, 'w'))
def evaluate(db, out_dir, filename, overwrite=False):
results_ccf = join(out_dir, filename)
eval_summary = eval_ccf(db, results_ccf)
out_path = join(out_dir, 'eval_summary.pkl')
if overwrite or not isfile(out_path):
pickle.dump(eval_summary, open(out_path, 'wb'))
def eval_ccf(db, results, iou_type='bbox'):
# ccf means CoCo Format
if isinstance(results, str):
if results.endswith('.pkl'):
results = pickle.load(open(results, 'rb'))
else:
results = json.load(open(results, 'r'))
results = db.loadRes(results)
cocoEval = COCOeval(db, results, iou_type)
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()
return {
'eval': cocoEval.eval,
'stats': cocoEval.stats,
}
from multiprocessing import resource_tracker
def remove_shm_from_resource_tracker():
"""Monkey-patch multiprocessing.resource_tracker so SharedMemory won't be tracked
More details at: https://bugs.python.org/issue38119
"""
def fix_register(name, rtype):
if rtype == "shared_memory":
return
return resource_tracker._resource_tracker.register(name, rtype)
resource_tracker.register = fix_register
def fix_unregister(name, rtype):
if rtype == "shared_memory":
return
return resource_tracker._resource_tracker.unregister(name, rtype)
resource_tracker.unregister = fix_unregister
if "shared_memory" in resource_tracker._CLEANUP_FUNCS:
del resource_tracker._CLEANUP_FUNCS["shared_memory"]
```
|
{
"source": "Jelaque/Topics-on-database",
"score": 3
}
|
#### File: Topics-on-database/files/ml100k.py
```python
import codecs
import multiprocessing as mp,os
import math as mt
import pandas as pd
from chunker import Chunker
class recommenderMl100k:
def __init__(self, data, k=1, metric='pearson', n=5, cores=8):
self.k = k
self.n = n
self.username2id = {}
self.userid2name = {}
self.productid2name = {}
self.cores = cores
self.path = '../datasets/ml-100k/'
# for some reason I want to save the name of the metric
self.metric = metric
if self.metric == 'pearson':
self.fn = self.pearson
#
# if data is dictionary set recommender data to it
#
if type(data).__name__ == 'dict':
self.data = data
elif self.metric == 'euclidian':
self.fn = self.euclidian
elif self.metric == 'cosine':
self.fn = self.cosine
elif self.metric == 'manhattan':
self.fn = self.manhattan
def convertProductID2name(self, id):
"""Given product id number return product name"""
if id in self.productid2name:
return self.productid2name[id]
else:
return id
def userRatings(self, id, n):
"""Return n top ratings for user with id"""
print ("Ratings for " + self.userid2name[id])
ratings = self.data[id]
print(len(ratings))
ratings = list(ratings.items())[:n]
ratings = [(self.convertProductID2name(k), v) \
for (k, v) in ratings]
# finally sort and return
ratings.sort(key=lambda artistTuple: artistTuple[1],reverse = True)
for rating in ratings:
print("%s\t%i" % (rating[0], rating[1]))
def showUserTopItems(self, user, n):
""" show top n items for user"""
items = list(self.data[user].items())
items.sort(key=lambda itemTuple: itemTuple[1], reverse=True)
for i in range(n):
print("%s\t%i" % (self.convertProductID2name(items[i][0]),items[i][1]))
def process_data(self,fname,chunkStart, chunkSize):
with open(fname, encoding="ascii", errors="surrogateescape") as f:
f.seek(chunkStart)
lines = f.read(chunkSize).splitlines()
for line in lines:
fields = line.split('\t')
user = fields[0]
movie = fields[1]
rating = int(fields[2].strip().strip('"'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[movie] = rating
self.data[user] = currentRatings
def process_item(self,fname,chunkStart, chunkSize):
with open(fname, encoding="ISO-8859-1") as f:
f.seek(chunkStart)
lines = f.read(chunkSize).splitlines()
for line in lines:
fields = line.split('|')
mid = fields[0].strip()
title = fields[1].strip()
self.productid2name[mid] = title
def loadBookDB(self, path=''):
"""loads the BX book dataset. Path is where the BX files are
located"""
self.data = {}
i = 0
#
# First load book ratings into self.data
#
f = codecs.open(path + "BX-Book-Ratings.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
user = fields[0].strip('"')
book = fields[1].strip('"')
rating = int(fields[2].strip().strip('"'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[book] = rating
self.data[user] = currentRatings
f.close()
#
# Now load books into self.productid2name
# Books contains isbn, title, and author among other fields
#
f = codecs.open(path + "BX-Books.csv", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
isbn = fields[0].strip('"')
title = fields[1].strip('"')
author = fields[2].strip().strip('"')
title = title + ' by ' + author
self.productid2name[isbn] = title
f.close()
#
# Now load user info into both self.userid2name and
# self.username2id
#
f = codecs.open(path + "BX-Users.csv", 'r', 'utf8')
for line in f:
i += 1
#print(line)
#separate line into fields
fields = line.split(';')
userid = fields[0].strip('"')
location = fields[1].strip('"')
if len(fields) > 3:
age = fields[2].strip().strip('"')
else:
age = 'NULL'
if age != 'NULL':
value = location + ' (age: ' + age + ')'
else:
value = location
self.userid2name[userid] = value
self.username2id[location] = userid
f.close()
def process_users(self,fname,chunkStart, chunkSize):
with open(fname, encoding="UTF-8") as f:
f.seek(chunkStart)
lines = f.read(chunkSize).splitlines()
for line in lines:
fields = line.split('|')
userid = fields[0].strip('"')
self.userid2name[userid] = line
self.username2id[line] = userid
def loadMovieLensParallel(self):
self.data = {}
#init objects
pool = mp.Pool(self.cores)
jobs = []
#create jobs
fname = self.path+"u.data"
for chunkStart,chunkSize in Chunker.chunkify(fname):
jobs.append( pool.apply_async(self.process_data,(fname,chunkStart,chunkSize)) )
#wait for all jobs to finish
for job in jobs:
job.get()
#clean up
pool.close()
#init objects
pool = mp.Pool(self.cores)
jobs = []
fname = self.path+"u.item"
for chunkStart,chunkSize in Chunker.chunkify(fname):
jobs.append( pool.apply_async(self.process_item,(fname,chunkStart,chunkSize)) )
#wait for all jobs to finish
for job in jobs:
job.get()
#clean up
pool.close()
#init objects
pool = mp.Pool(self.cores)
jobs = []
fname = self.path+"u.user"
for chunkStart,chunkSize in Chunker.chunkify(fname):
jobs.append( pool.apply_async(self.process_users,(fname,chunkStart,chunkSize)) )
#wait for all jobs to finish
for job in jobs:
job.get()
#clean up
pool.close()
def loadMovieLens(self, path=''):
self.data = {}
# first load movie ratings
i = 0
# First load book ratings into self.data
#f = codecs.open(path + "u.data", 'r', 'utf8')
f = codecs.open(path + "u.data", 'r', 'ascii')
# f = open(path + "u.data")
for line in f:
i += 1
#separate line into fields
fields = line.split('\t')
user = fields[0]
movie = fields[1]
rating = int(fields[2].strip().strip('"'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[movie] = rating
self.data[user] = currentRatings
f.close()
#
# Now load movie into self.productid2name
# the file u.item contains movie id, title, release date among
# other fields
#
#f = codecs.open(path + "u.item", 'r', 'utf8')
f = codecs.open(path + "u.item", 'r', 'iso8859-1', 'ignore')
#f = open(path + "u.item")
for line in f:
i += 1
#separate line into fields
fields = line.split('|')
mid = fields[0].strip()
title = fields[1].strip()
self.productid2name[mid] = title
f.close()
#
# Now load user info into both self.userid2name
# and self.username2id
#
#f = codecs.open(path + "u.user", 'r', 'utf8')
f = open(path + "u.user")
for line in f:
i += 1
fields = line.split('|')
userid = fields[0].strip('"')
self.userid2name[userid] = line
self.username2id[line] = userid
f.close()
def manhattan(self, rating1, rating2):
"""Simplest distance operation using only sums"""
distance = 0
for key in rating1:
if key in rating2:
distance += abs(rating1[key] - rating2[key])
return distance
def euclidian(self, rating1, rating2):
"""Usual triangular distance"""
distance = 0
for key in rating1:
if key in rating2:
distance += pow(rating1[key] - rating2[key],2)
return mt.sqrt(distance)
def minkowski(self, rating1, rating2, p):
"""Generalization of manhattan and euclidian distances"""
distance = 0
for key in rating1:
if key in rating2:
distance += pow(abs(rating1[key] - rating2[key]),p)
if distance != 0:
return pow(distance, 1/p)
return 0
def cosine(self, rating1, rating2):
"""Similarity for sparse ratings"""
prod_xy = 0
len_vx = 0
len_vy = 0
for key in rating1:
if key in rating2:
prod_xy += rating1[key] * rating2[key]
len_vx += rating1[key] * rating1[key]
len_vy += rating2[key] * rating2[key]
dem = mt.sqrt(len_vx) * mt.sqrt(len_vy)
if dem != 0:
return prod_xy / dem
return -1
def pearson(self, rating1, rating2):
"""Similarity between two users"""
sum_xy = 0
sum_x = 0
sum_y = 0
sum_x2 = 0
sum_y2 = 0
n = 0
for key in rating1:
if key in rating2:
n += 1
x = rating1[key]
y = rating2[key]
sum_xy += x * y
sum_x += x
sum_y += y
sum_x2 += pow(x, 2)
sum_y2 += pow(y, 2)
if n == 0:
return 0
# now compute denominator
denominator = mt.sqrt(sum_x2 - pow(sum_x, 2) / n) * \
mt.sqrt(sum_y2 - pow(sum_y, 2) / n)
if denominator == 0:
return 0
else:
return (sum_xy - (sum_x * sum_y) / n) / denominator
def computeNearestNeighbor(self, username):
"""creates a sorted list of users based on their distance
to username"""
distances = []
for instance in self.data:
if instance != username:
distance = self.fn(self.data[username],
self.data[instance])
distances.append((instance, distance))
# sort based on distance -- closest first
distances.sort(key=lambda artistTuple: artistTuple[1],
reverse=True)
return distances
def recommend(self, user):
"""Give list of recommendations"""
recommendations = {}
# first get list of users ordered by nearness
nearest = self.computeNearestNeighbor(user)
#
# now get the ratings for the user
#
userRatings = self.data[user]
#
# determine the total distance
totalDistance = 0.0
for i in range(self.k):
totalDistance += nearest[i][1]
# now iterate through the k nearest neighbors
# accumulating their ratings
for i in range(self.k):
# compute slice of pie
weight = nearest[i][1] / totalDistance
# get the name of the person
name = nearest[i][0]
# get the ratings for this person
neighborRatings = self.data[name]
# get the name of the person
# now find bands neighbor rated that user didn't
for artist in neighborRatings:
if not artist in userRatings:
if artist not in recommendations:
recommendations[artist] = neighborRatings[artist] * \
weight
else:
recommendations[artist] = recommendations[artist] + \
neighborRatings[artist] * \
weight
# now make list from dictionary and only get the first n items
recommendations = list(recommendations.items())[:self.n]
recommendations = [(self.convertProductID2name(k), v)
for (k, v) in recommendations]
# finally sort and return
recommendations.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
return recommendations[:self.n]
def ProjectedRanting(self, user, key):
# first get list of users ordered by nearness
nearest = self.computeNearestNeighbor(user)
projtRating = 0
#
# determine the total distance
totalDistance = 0.0
for i in range(self.k):
totalDistance += nearest[i][1]
# now iterate through the k nearest neighbors
# accumulating their ratings
for i in range(self.k):
# compute slice of pie
weight = nearest[i][1] / totalDistance
name = nearest[i][0]
projtRating += weight * self.data[name][key]
return projtRating
def jaccard(self, rating1, rating2):
"""Similarity of number of coincidences between ratings"""
"""returning similarity and distance"""
union = set()
for i in rating1.keys():
union.add(i)
for i in rating2.keys():
union.add(i)
dif = 0
same = len(union)
for key in union:
if (key in rating1) and (key in rating2):
dif += 1
simil = dif/same
dist = 1-simil
return simil,dist
```
|
{
"source": "jelaredulla/anneReThesis",
"score": 3
}
|
#### File: anneReThesis/PythonClient/camera.py
```python
from PythonClient import *
import cv2
import time
import sys
def printUsage():
print("Usage: python camera.py [depth|segmentation|scene]")
cameraType = "depth"
for arg in sys.argv[1:]:
cameraType = arg.lower()
cameraTypeMap = {
"depth": AirSimImageType.Depth,
"segmentation": AirSimImageType.Segmentation,
"seg": AirSimImageType.Segmentation,
"scene": AirSimImageType.Scene,
}
if (not cameraType in cameraTypeMap):
printUsage()
sys.exit(0)
print cameraTypeMap[cameraType]
client = AirSimClient('127.0.0.1')
help = False
fontFace = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
thickness = 2
textSize, baseline = cv2.getTextSize("FPS", fontFace, fontScale, thickness)
print (textSize)
textOrg = (10, 10 + textSize[1])
frameCount = 0
startTime=time.clock()
fps = 0
while True:
# because this method returns std::vector<uint8>, msgpack decides to encode it as a string unfortunately.
rawImage = client.simGetImage(0, cameraTypeMap[cameraType])
if (rawImage == None):
print("Camera is not returning image, please check airsim for error messages")
sys.exit(0)
else:
png = cv2.imdecode(rawImage, cv2.IMREAD_UNCHANGED)
cv2.putText(png,'FPS ' + str(fps),textOrg, fontFace, fontScale,(255,0,255),thickness)
cv2.imshow("Depth", png)
frameCount = frameCount + 1
endTime=time.clock()
diff = endTime - startTime
if (diff > 1):
fps = frameCount
frameCount = 0
startTime = endTime
key = cv2.waitKey(1) & 0xFF;
if (key == 27 or key == ord('q') or key == ord('x')):
break;
```
|
{
"source": "jelaredulla/thesis",
"score": 3
}
|
#### File: thesis/PythonClient/dronePlayer.py
```python
from AirSimClient import *
import sys
import time
import msgpackrpc
import math
import threading
import numpy as np
import Tkinter as tk
TIME_STEP = 0.01
def generate_planar_evader_path(speed, duration, f, start_x, start_y, start_z):
t = 0
path = []
x = start_x
y = start_y
path.append((x, y, start_z))
while t < duration:
angle = f(t)
x_dot = speed * math.sin(angle)
y_dot = speed * math.cos(angle)
x += x_dot * TIME_STEP
y += y_dot * TIME_STEP
path.append((x, y, start_z))
t += TIME_STEP
return path
class DronePlayer(MultirotorClient):
CAMERA_VIEWS = {"first person": AirSimImageType.Scene,\
"depth": AirSimImageType.DepthPerspective,\
"segmentation": AirSimImageType.Segmentation}
TAKEOFF_MAX_TIME = 3 # maximum time for drone to reach
# takeoff altitude, in seconds
def __init__(self, ip = "127.0.0.1", port = 41451):
""" Initialises a player
Parameters:
* ip (str): the IP address of the AirSim client,
default value of home
"""
super(DronePlayer, self).__init__(ip, port)
self._path = []
def run(self):
self.confirmConnection()
self.enableApiControl(True)
#self.set_views()
arm_result = self.loop_arm()
if (arm_result < 0):
print("Could not arm the drone. Exiting.")
return
takeoff_result = self.loop_takeoff()
if (takeoff_result < 0):
print("Could not take off successfully. Exiting.")
return
while True:
self.fly_box(-7, 1, 10)
pos = self.getPosition()
print(pos)
refly = raw_input("Fly box again? [y]/n: ")
if refly.strip().lower() == 'n':
break
print("Hovering...")
self.hover()
def _get_GPS_location(self):
""" Waits for GPS location to be set by AirSim server
"""
print("Waiting for home GPS location to be set..."),
home = self.getHomePoint()
while ((home[0] == 0 and home[1] == 0 and home[2] == 0) or
math.isnan(home[0]) or math.isnan(home[1]) or \
math.isnan(home[2])):
print("..."),
time.sleep(1)
home = self.getHomePoint()
self._home = home
print("\nHome is:\n\tlatitude: {0:2f}, longitude: {1:2f}, altitude (m): {2:2f}"\
.format(*tuple(home)))
def set_views(self):
""" Sets the camera views. If the user does not enter 'y', the view
is off by default.
"""
for name, cam_view in DronePlayer.CAMERA_VIEWS.iteritems():
view_setting = raw_input("Would you like to turn the '{0}' view on? "\
"y/[n]: ".format(name))
if view_setting.strip().lower() == 'y':
self.simGetImage(0, cam_view)
def loop_arm(self):
""" Attempts to arm the drone until successful, or until the user gives
up by entering 'n'.
"""
while True:
print("Attempting to arm the drone...")
if (not self.armDisarm(True)):
retry= raw_input("Failed to arm the drone. Retry? [y]/n: ")
if retry.strip().lower() == 'n':
return -1
else:
break
return 0
def loop_takeoff(self):
""" Attempts to take off until successful, or until the user gives up by
entering 'n'.
"""
if (self.getLandedState() == LandedState.Landed):
print("Taking off...")
while True:
try:
self.takeoff(DronePlayer.TAKEOFF_MAX_TIME)
print("Should now be flying...")
break
except:
retry = raw_input("Failed to reach takeoff altitude after \
{0} seconds. Retry? [y]/n: "\
.format(DronePlayer.TAKEOFF_MAX_TIME))
if retry.strip().lower() == 'n':
return -1
else:
print("It appears the drone is already flying")
return 0
def fly_box(self, height, speed, side_length):
""" Makes the drone fly in a box at the specified height and speed.
Hovers once the box has been flown
Parameters:
* height (float): height above the original launch point, in m
Note: AirSim uses NED coordinates
so negative axis is up.
* speed (float): speed to fly at, in m/s
* side_length (float): side length of box, in m
"""
direction_vectors = [(1, 0), (0, 1), (-1, 0), (0, -1)]
duration = float(side_length) / speed
delay = duration * speed
for x_dir, y_dir in direction_vectors:
x_velocity = x_dir * speed
y_velocity = y_dir * speed
yaw_angle = math.degrees(math.atan2(y_dir, x_dir))
print("Yaw = "+str(yaw_angle))
self.rotateToYaw(yaw_angle)
self.moveByVelocityZ(x_velocity, y_velocity, height, duration)
## ,\
## DrivetrainType.MaxDegreeOfFreedom, YawMode(False, yaw_angle))
for i in range(10):
pos = self.getPosition()
self._path.append((pos.x_val, pos.y_val, pos.z_val))
time.sleep(delay/10)
self.hover()
class PlayerModel(object):
""" Attributes of a player
"""
PLAYER_COLOURS = ["blue", "red", "green", "yellow"]
colour_index = 0
def __init__(self, speed, start_pos = (0, 0, 0)):
""" Initialises player attributes
Parameters:
* start_pos (tup<float, float>): start position in Cartesian coords
(x, y, z), in m
"""
self._start_pos = start_pos
self._x, self._y, self._z = self._start_pos
self._position_log = [self._start_pos]
self._speed = speed
self._colour = PlayerModel.PLAYER_COLOURS[PlayerModel.colour_index]
PlayerModel.colour_index = (PlayerModel.colour_index + 1) % len(PlayerModel.PLAYER_COLOURS)
def get_speed(self):
return self._speed
def get_colour(self):
return self._colour
def record_current_pos(self):
""" Records current position in position log
"""
self._position_log.append((self._x, self._y, self._z))
def reset_position_log(self):
""" Resets position log
"""
self._position_log = [self._start_pos]
def get_position_log(self):
return self._position_log[:]
## def get_next_pos(self):
## self._pos_index += 1
##
## if self._pos_index == len(self._position_log):
## return None
##
## return self._position_log[self._pos_index]
def move(self, pos):
self._x, self._y, self._z = pos
self.record_current_pos()
def get_current_pos(self):
return self._position_log[-1]
def get_most_recent_segment(self):
if len(self._position_log) < 2:
return
return (self._position_log[-2], self._position_log[-1])
class Evader(PlayerModel):
def __init__(self, speed, start_pos = (0, 5, 0)):
PlayerModel.__init__(self, speed, start_pos)
self._path = []
def set_path(self, path):
self._path = path
self._path_index = -1
def pre_determined_move(self):
self._path_index += 1
if (self._path_index == len(self._path)):
return True
self.move(self._path[self._path_index])
class Pursuer(PlayerModel):
def __init__(self, speed, min_turn_r, start_pos = (0, 0, 0)):
PlayerModel.__init__(self, speed, start_pos)
self._R = min_turn_r
self._capture_r = None
self._prey = None
self._angle = 0
def set_prey(self, evader, capture_radius):
self._prey = evader
self._capture_r = capture_radius
def chase(self):
if self._prey == None:
return True
target_pos = self._prey.get_current_pos()
current_pos = self.get_current_pos()
x = (target_pos[0] - current_pos[0]) * math.cos(self._angle) \
- (target_pos[1] - current_pos[1]) * math.sin(self._angle)
y = (target_pos[0] - current_pos[0]) * math.sin(self._angle) \
+ (target_pos[1] - current_pos[1]) * math.cos(self._angle)
d = math.sqrt(x**2 + y**2)
if d < self._capture_r:
return True
if (x == 0):
if (y < 0):
phi = 1
else:
phi = 0
else:
phi = np.sign(x)
angle_dot = float( self._speed * phi ) / self._R
self._angle += angle_dot * TIME_STEP
p_x_dot = self._speed * math.sin(self._angle)
p_y_dot = self._speed * math.cos(self._angle)
p_x = current_pos[0] + p_x_dot * TIME_STEP
p_y = current_pos[1] + p_y_dot * TIME_STEP
self.move((p_x, p_y, current_pos[2]))
return False
class PositionPlotter(tk.Canvas):
PLAYER_COLOURS = ["blue", "red", "green", "yellow"]
WIDTH = 500
HEIGHT = 1000
MAX_X = 10
MIN_X = -10
MAX_Y = 10
MIN_Y = -10
def __init__(self, parent):
tk.Canvas.__init__(self, parent, bg = "grey", width=PositionPlotter.WIDTH, height=PositionPlotter.HEIGHT)
self.pack(expand = True, fill = tk.BOTH)
self._m_x = float(PositionPlotter.WIDTH) / (PositionPlotter.MAX_X - PositionPlotter.MIN_X)
self._c_x = -self._m_x * PositionPlotter.MIN_X
self._m_y = float(PositionPlotter.HEIGHT) / (PositionPlotter.MAX_Y - PositionPlotter.MIN_Y)
self._c_y = -self._m_y * PositionPlotter.MIN_Y
self._col_index = 0
def scale_x(self, x):
return round(self._m_x * x + self._c_x)
def scale_y(self, y):
return round(self._m_y * y + self._c_y)
def planar_scale(self, x, y):
return ( self.scale_x(x), self.scale_y(y) )
def plot_path(self, points):
planar_points = []
for x, y, z in points:
planar_points.append(self.planar_scale(x, y))
for i in range(len(planar_points[:-1])):
self.create_line(planar_points[i], planar_points[i+1],\
fill = PositionPlotter.PLAYER_COLOURS[self._col_index])
self._col_index += 1
def update_plot(self, player):
path_segment = player.get_most_recent_segment()
col = player.get_colour()
if path_segment:
start, end = path_segment
scaled_start = self.planar_scale(*start[:-1])
scaled_end = self.planar_scale(*end[:-1])
self.create_line(scaled_start, scaled_end, fill = col)
## if not next_pos:
## return
##
## x, y, z = next_pos
## scaled = self.planar_scale(x, y)
##
## if self._last_pos:
## self.create_line(self._last_pos, scaled)
##
## self._last_pos = scaled
## def demo(self, e):
## p = PlayerModel()
## p.planar_sinusoidal_swerve(2, 2*math.pi, 3)
##
## coords = p.get_position_log()
## print(coords[:10])
##
## print("Swerved")
##
##
## self.plot_path(coords)
class PEGameApp(object):
def __init__(self, master):
self._master = master
self._master.title("Position plotter application")
self._plotter = PositionPlotter(self._master)
self._evader = Evader(0.5)
self._pursuer = Pursuer(1, 1)
self._pursuer.set_prey(self._evader, 0.01)
evader_start_pos = self._evader.get_current_pos()
evader_speed = self._evader.get_speed()
swerve_path = generate_planar_evader_path(evader_speed, 60, lambda x: math.cos(x), *evader_start_pos)
self._evader.set_path(swerve_path)
self.chase()
def chase(self):
path_finished = self._evader.pre_determined_move()
caught = self._pursuer.chase()
self._plotter.update_plot(self._evader)
self._plotter.update_plot(self._pursuer)
if (path_finished):
return
if (caught):
return
self._master.after(1, self.chase)
class GameSim(object):
def __init__(self):
self._p = DronePlayer("", 41451)
self._e = DronePlayer("", 41452)
self._pAngle = 0
self._speed = 0.5
self._R = 0.1
self._p.confirmConnection()
self._p.enableApiControl(True)
self._p.loop_arm()
self._e.confirmConnection()
self._e.enableApiControl(True)
self._e.loop_arm()
self.both_takeoff()
self.chase()
self.plot_paths()
def both_takeoff(self):
self._e.loop_takeoff()
self._e.moveToPosition(8, 0, -2.5, 10)
self._p.loop_takeoff()
def chase(self):
self._e.rotateToYaw(90, 3)
self._e.moveByVelocityZ(0, -0.4, -2.5, 50)
while True:
p_pos = self._p.getPosition()
x_p, y_p, z_p = (p_pos.x_val, p_pos.y_val, p_pos.z_val)
e_pos = self._e.getPosition()
x_e, y_e, z_e = (e_pos.x_val, e_pos.y_val, e_pos.z_val)
self._e._path.append((x_e, y_e, z_e))
self._p._path.append((x_p, y_p, z_p))
## print("Pursuer at {}".format((p_pos.x_val, p_pos.y_val, p_pos.z_val)))
## print("Evader at {}".format((e_pos.x_val, e_pos.y_val, e_pos.z_val)))
x = (x_e - x_p) * math.cos(self._pAngle) \
- (y_e - y_p) * math.sin(self._pAngle)
y = (x_e- x_p) * math.sin(self._pAngle) \
+ (y_e - y_p) * math.cos(self._pAngle)
d = math.sqrt(x**2 + y**2)
if d < 2:
return True
if (x == 0):
if (y < 0):
phi = 1
else:
phi = 0
else:
phi = np.sign(x)
angle_dot = float( self._speed * phi ) / self._R
yaw_change = angle_dot * TIME_STEP
self._pAngle += yaw_change
## self._p.moveByAngle(0, 0, -2.5, -math.degrees(yaw_change), 1)
p_x_dot = self._speed * math.sin(self._pAngle)
p_y_dot = self._speed * math.cos(self._pAngle)
## self._p.rotateToYaw(math.degrees(yaw_change), 0.5)
self._p.moveByVelocityZ(p_x_dot, p_y_dot, -2.5, 1,\
DrivetrainType.ForwardOnly, YawMode(False, math.degrees(self._pAngle)))
time.sleep(TIME_STEP)
def plot_paths(self):
root = tk.Tk()
app = PositionPlotter(root)
app.plot_path(self._e._path)
app.plot_path(self._p._path)
root.mainloop()
if __name__ == "__main__":
orig = YawMode(True, 0.456674)
print orig.to_msgpack()
together = len(sys.argv) == 1
if together:
GameSim()
else:
dronePort = int(sys.argv[1])
drone = DronePlayer("", dronePort)
drone.run()
root = tk.Tk()
app = PositionPlotter(root)
app.plot_path(drone._path)
root.mainloop()
## root = tk.Tk()
## app = PEGameApp(root)
## root.mainloop()
```
|
{
"source": "JELAshford/OxHack-2020",
"score": 3
}
|
#### File: OxHack-2020/TCARS/TCARS_interface.py
```python
import pyglet
from pyglet import font
from pyglet.window import mouse
from pyglet.window import key
from dataclasses import dataclass
from backend_generation import generate_plots
@dataclass
class Region:
bottom_left_x: int
bottom_left_y: int
height: int
width: int
def in_region(self, x, y):
if x > self.bottom_left_x and x < self.bottom_left_x+self.width and y > self.bottom_left_y and y < self.bottom_left_y+self.height:
return True
else:
return False
global ACTIVE_WORD, VIEW_DICT, VIEW_MODE, main_display
INTERFACE_PATH = "/Users/jamesashford/Documents/Projects/Hackathons/Oxford Hack 2020/OxHack-2020/TCARS"
RSC_PATH = f"{INTERFACE_PATH}/rsc"
OUTPUT_PATH = f"{INTERFACE_PATH}/output"
WIDTH, HEIGHT = 1440, 898
ACTIVE_WORD = "ENTER QUERY"
VIEW_MODE = 1
VIEW_DICT = {1: "wordcloud",
2: "coocgraph",
3: "psplot"}
# Load in font
font.add_file(f'{RSC_PATH}/swiss_911_ultra_compressed_bt.ttf')
font.load(f'{RSC_PATH}/swiss_911_ultra_compressed_bt.ttf', 16)
# Generate window for app
window = pyglet.window.Window(WIDTH, HEIGHT, "Twitter Analysis")
# Title and Search Labels
title = pyglet.text.Label("TCARS",
font_name='Swiss911 UCm BT',
font_size=90,
x=150, y=800, width=250, height=100,
anchor_x='left', anchor_y='bottom')
subtitle = pyglet.text.Label("Twitter Content Access/Retrieval System",
font_name='Swiss911 UCm BT',
font_size=30,
x=150, y=670, width=250, height=100,
anchor_x='left', anchor_y='bottom')
search_word = pyglet.text.Label(ACTIVE_WORD,
font_name='Swiss911 UCm BT',
font_size=40,
x=860, y=620, width=580, height=270,
anchor_x='left', anchor_y='bottom')
# Button Regions
generate_button = Region(1190, 740, 75, 210)
wordcloud_buttom = Region(1280, 603, 35, 40)
coocgraph_buttom = Region(1280, 368, 35, 40)
psplot_buttom = Region(1280, 153, 35, 40)
# Button Labels
wordcloud_label = pyglet.image.load(f"{RSC_PATH}/button_word_cloud.png")
wordcloud_label.anchor_x = 0; wordcloud_label.anchor_y = 0
coocgraph_label = pyglet.image.load(f"{RSC_PATH}/button_cooc_graph.png")
coocgraph_label.anchor_x = 0; coocgraph_label.anchor_y = 0
psplot_label = pyglet.image.load(f"{RSC_PATH}/button_polsub_graph.png")
psplot_label.anchor_x = 0; psplot_label.anchor_y = 0
# Main Images
background = pyglet.image.load(f"{RSC_PATH}/oxhack2020_background.png")
main_display = pyglet.image.load(f"{RSC_PATH}/standby.png")
main_display.anchor_x = 0; main_display.anchor_y = 0
# Twitter Logo (for fun!)
twitter_logo = pyglet.image.load(f"{RSC_PATH}/twitter_logo.png")
twitter_logo.anchor_x = 0; twitter_logo.anchor_y = 0
@window.event
def on_draw():
window.clear()
background.blit(0, 0)
twitter_logo.blit(400, 800)
wordcloud_label.blit(1230, 560)
coocgraph_label.blit(1230, 330)
psplot_label.blit(1230, 100)
title.draw()
subtitle.draw()
main_display.blit(200, 100)
search_word.draw()
@window.event
def on_mouse_press(x, y, button, modifiers):
global ACTIVE_WORD, VIEW_DICT, VIEW_MODE, main_display
SCREEN_UPDATE = True
if button == mouse.LEFT:
print(f'The left mouse button was pressed at x:{x}, y:{y}')
# Test if generate_button pressed
if generate_button.in_region(x, y):
print(f'Generate a Twitter Profile for "{ACTIVE_WORD}"')
generate_plots(ACTIVE_WORD)
# Test if wordcloud_buttom pressed
elif wordcloud_buttom.in_region(x, y):
print('Pressed wordcloud button. Setting plot type to wordcloud')
VIEW_MODE = 1
elif coocgraph_buttom.in_region(x, y):
print('Pressed coocgraph button. Setting plot type to coocgraph')
VIEW_MODE = 2
elif psplot_buttom.in_region(x, y):
print('Pressed psplot button. Setting plot type to psplot')
VIEW_MODE = 3
else:
SCREEN_UPDATE = False
if SCREEN_UPDATE:
# Update main plot with the
main_display = pyglet.image.load(f"{OUTPUT_PATH}/{ACTIVE_WORD}_{VIEW_DICT[VIEW_MODE]}.png")
main_display.anchor_x = 0; main_display.anchor_y = 0
@window.event
def on_key_press(symbol, modifiers):
global ACTIVE_WORD
# If "/" is pressed, reset the active word
if symbol == 47:
ACTIVE_WORD = ""
# Enable backspacing
if symbol == key.BACKSPACE:
if len(ACTIVE_WORD) > 0:
ACTIVE_WORD = ACTIVE_WORD[:-1]
# Enable spaces
elif symbol == key.SPACE:
ACTIVE_WORD += " "
# Allow letter key presses
else:
new_button = str(key.symbol_string(symbol))
if new_button in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_0_1_2_3_4_5_6_7_8_9':
# Remove _ from numbers
new_button = new_button.strip("_")
ACTIVE_WORD += new_button
# Update label text
search_word.text = ACTIVE_WORD
# Run the app
pyglet.app.run()
```
|
{
"source": "JELAshford/PiBorg",
"score": 3
}
|
#### File: PiBorg/mqtt_testing/sub.py
```python
import paho.mqtt.client as mqtt
import json
broker_url = ""
broker_port = 1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code " + str(rc))
def on_message(client, userdata, message):
decoded_message = json.loads(message.payload.decode())
print(decoded_message)
def wheel_cam_callback(client, userdata, message):
decoded_message = json.loads(message.payload.decode())
print("Data from Wheel Cam: ")
print(decoded_message)
def hq_cam_callback(client, userdata, message):
decoded_message = json.loads(message.payload.decode())
print("Data from HQ Cam: ")
print(decoded_message)
def lidar_callback(client, userdata, message):
decoded_message = json.loads(message.payload.decode())
print("Data from Lidar: ")
print(decoded_message)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, broker_port)
client.subscribe("wheel_cam", qos=0)
client.subscribe("hq_cam", qos=0)
client.subscribe("lidar", qos=0)
client.message_callback_add("wheel_cam", wheel_cam_callback)
client.message_callback_add("hq_cam", hq_cam_callback)
client.message_callback_add("lidar", lidar_callback)
client.loop_forever()
```
|
{
"source": "jelauria/cybersecurity-churros",
"score": 4
}
|
#### File: cybersecurity-churros/test/loopsncondit.py
```python
x = True
y = False
if x is True:
print("hello")
if (x):
print("hello")
if y:
print("false")
elif x is not y:
print("whoops")
else:
print("dang")
if x or y:
print("boom")
print("lmao")
# note: false-y variables in python are 0, None, False, {} and []
# note: you can put parentheses wherever you want it
x = "hello" # scoped within the whole script
def new_func(x, y="", z="bazz"): # x is scoped local to the function
print(x)
print(y)
print(z)
def lol_write():
# clunky way of witing to a file
file = open("file_path", 'w')
file.write("hewwo woowrld")
file.close()
# non-clunky way
with open("file_path", 'w') as file:
file.write("hewwo wowwrld")
new_func("meow")
new_func("meow", z="woof")
def sec_func(x, y = "world"):
return x + "hello", y + "world"
print(sec_func("womp "))
print(type(sec_func("womp"))) #returns a tuple
# String things
thing = "whaddup! my dude!!"
print(len(thing))
print(thing.startswith("wha"), thing.startswith("Wha"))
print(thing.find("dude"), thing.find("puddy"), thing.find("d"))
thing2 = "hello {name} my name is {animal}".format(animal = "dog", name = "reed")
print(thing2)
n = thing[0]
q = thing[2:10:2]
print(n, q)
z = thing.split(" ")
print(z, type(z))
g = " ".join(z)
print(g)
g = g.strip("!") # removes trailing !
print(g)
# bytes stuff
biite = b'thingy'
print(biite, type(biite))
now_str = biite.decode('utf-8')
print(now_str)
print(now_str.encode('utf-16'))
```
#### File: cybersecurity-churros/test/main.py
```python
import math
from enum import Enum, auto
class WORK_LANG(Enum):
ORDER = auto()
CANDOR = auto()
def main():
x = [1, 2, 3]
for i in x:
print(i)
y = 1
while y < 5:
y = y + 1
if y is 7:
break
elif 7 is 10:
continue
print(y)
try:
x.append("boop")
if len(x) > 3:
raise ValueError("the rent is too dang high")
except TypeError as e:
print("whoopo: " + str(e))
finally: # runs regardless of whether or not there was an error
print("zoop")
print(math.pi)
# if statement so main() runs by default from command line
if __name__=="__main__":
main()
```
|
{
"source": "jelauria/network-analysis",
"score": 3
}
|
#### File: jelauria/network-analysis/geoIP.py
```python
import dpkt
import geoip2.database
import socket
import pandas as pd
from shapely.geometry import Point
import geopandas as gpd
from geopandas import GeoDataFrame
import matplotlib.pyplot as plt
def ip_geo_info_(target):
with geoip2.database.Reader('GeoLite2/GeoLite2-City.mmdb') as reader:
try:
resp = reader.city(target)
except:
return ["Unknown", "Unknown", "Unknown", "Unknown", "Unknown"]
city = resp.city.name
region = resp.subdivisions.most_specific.name
iso = resp.country.iso_code
lat = resp.location.latitude
long = resp.location.longitude
data = [city, region, iso, float(lat), float(long)]
for i in range(len(data)):
if data[i] is None:
data[i] = "Unknown"
return data
def loc_array_pcap(pcap):
result = []
for ts, buf in pcap:
try:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
src = socket.inet_ntoa(ip.src)
dst = socket.inet_ntoa(ip.dst)
src_info = ip_geo_info_(src)
dst_info = ip_geo_info_(dst)
full_info = [src]
full_info.extend(src_info)
full_info.append(dst)
full_info.extend(dst_info)
result.append(full_info)
except:
pass
return result
def to_map(df):
srcs = [Point(xy) for xy in zip(df['S Long'], df['S Lat'])]
# dsts = [Point(xy) for xy in zip(df['D Long'], df['D Lat'])]
sdf = GeoDataFrame(df[['S Lat', 'S Long']], geometry=srcs)
# ddf = GeoDataFrame(df['D Lat', 'D Long'], geometry=dsts)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
sdf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='red', markersize=10)
# ddf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='yellow', markersize=10)
plt.show()
def main():
f = open('pcaps/2020-08-21-traffic-analysis-exercise.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
loc_data = loc_array_pcap(pcap)
df = pd.DataFrame(loc_data, columns=['Source IP', 'S City', 'S Region', 'S Country', 'S Lat', 'S Long',
'Destination IP', 'D City', 'D Region', 'D Country', 'D Lat', 'D Long'])
df2 = df[df['S Long'] != 'Unknown']
# df2 = df2[df2['D Long'] != 'Unknown']
to_map(df2)
# df.to_csv('out/finished.csv')
# print(ip_geo_info_('172.16.17.32'))
# print(ip_geo_info_('192.168.0.0'))
if __name__=="__main__":
main()
```
|
{
"source": "jelber2/sesp_radseq",
"score": 2
}
|
#### File: jelber2/sesp_radseq/01b-process_radtags.py
```python
Usage = """
01b-process_radtags.py - version 1.0
Command:
1.Processes sample barcodes
~/bin/stacks-1.44/process_radtags \
-i gzfastq \
-1 Read1 \
-2 Read2 \
-b barcodes \
-q -c --filter_illumina -r -t 140 \
--inline_inline --renz_1 xbaI --renz_2 ecoRI --retain_header \
-o OutDir
mv OutDir/process_radtags.log OutDir/logname
Directory info:
InDir = /work/jelber2/radseq/platefastq
Input Files = Plate.1.fq.gz, Plate.2.fq.gz
OutDir = /work/jelber2/radseq/samplefastq
Important Output Files = Sample.1.fq.gz, Sample.2.fq.gz
Usage (execute following code in InDir):
python ~/scripts/sesp_radseq/01b-process_radtags.py --Read1 R1.fq.gz --Read2 R2.fq.gz --barcodes barcodes.txt --logname process-radtags-plate1.log --OutDir OutDir
"""
###############################################################################
import os, sys, subprocess, re , argparse
class FullPaths(argparse.Action):
"""Expand user- and relative-paths"""
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values)))
def is_dir(dirname):
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""\nRuns Stacks process_radtags on each sample in the barcodes file""")
parser.add_argument(
"--Read1",
required=True,
action=FullPaths,
help="""Path to Read1 file"""
)
parser.add_argument(
"--Read2",
required=True,
action=FullPaths,
help="""Path to Read2 file"""
)
parser.add_argument(
"--barcodes",
required=True,
action=FullPaths,
help="""barcodes file in form Barcode1tabBarcode2tabSample"""
)
parser.add_argument(
"--logname",
required=True,
help="""name of log file"""
)
parser.add_argument(
"--OutDir",
required=True,
action=FullPaths,
help="""Path to output directory, ex: /work/jelber2/samplefastq/"""
)
return parser.parse_args()
def main():
args = get_args()
Read1 = args.Read1
Read2 = args.Read2
barcodes = args.barcodes
logname = args.logname
InDir = os.getcwd()
OutDir = args.OutDir
os.chdir(InDir)
if not os.path.exists(OutDir):
os.mkdir(OutDir) # if OutDir does not exist, then make it
# Customize your options here
Queue = "single"
Allocation = "hpc_sesp"
Processors = "nodes=1:ppn=1"
WallTime = "72:00:00"
LogOut = OutDir
LogMerge = "oe"
JobName = "pradtags-plate-samples"
Command = """
~/bin/stacks-1.44/process_radtags \
-i gzfastq \
-1 %s \
-2 %s \
-b %s \
-q -c --filter_illumina -r -t 140 \
--inline_inline --renz_1 xbaI --renz_2 ecoRI --retain_header \
-o %s
mv %s/process_radtags.log %s/%s""" % \
(Read1, Read2, barcodes, OutDir, OutDir, OutDir, logname)
JobString = """
#!/bin/bash
#PBS -q %s
#PBS -A %s
#PBS -l %s
#PBS -l walltime=%s
#PBS -o %s
#PBS -j %s
#PBS -N %s
cd %s
%s\n""" % (Queue, Allocation, Processors, WallTime, LogOut, LogMerge, JobName, InDir, Command)
#Create pipe to qsub
proc = subprocess.Popen(['qsub'], shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
(child_stdout, child_stdin) = (proc.stdout, proc.stdin)
#Print JobString
jobname = proc.communicate(JobString)[0]
print JobString
print jobname
if __name__ == '__main__':
main()
```
|
{
"source": "jelbrek/DyldExtractor",
"score": 2
}
|
#### File: DyldExtractor/converter/stub_fixer.py
```python
import dataclasses
import enum
import struct
from typing import Iterator, List, Tuple, Dict
from DyldExtractor.extraction_context import ExtractionContext
from DyldExtractor.file_context import FileContext
from DyldExtractor.converter import slide_info
from DyldExtractor import leb128
from DyldExtractor.dyld import dyld_trie
from DyldExtractor.macho.macho_context import MachOContext
from DyldExtractor.macho.macho_constants import *
from DyldExtractor.macho.macho_structs import (
LoadCommands,
dyld_info_command,
dylib_command,
dysymtab_command,
linkedit_data_command,
nlist_64,
section_64,
symtab_command
)
@dataclasses.dataclass
class _DependencyInfo(object):
dylibPath: bytes
imageAddress: int
context: MachOContext
class _Symbolizer(object):
def __init__(self, extractionCtx: ExtractionContext) -> None:
"""Used to symbolize function in the cache.
This will walk down the tree of dependencies and
cache exports and function names. It will also cache
any symbols in the MachO file.
"""
super().__init__()
self._dyldCtx = extractionCtx.dyldCtx
self._machoCtx = extractionCtx.machoCtx
self._statusBar = extractionCtx.statusBar
self._logger = extractionCtx.logger
# Stores and address and the possible symbols at the address
self._symbolCache: dict[int, list[bytes]] = {}
# create a map of image paths and their addresses
self._images: dict[bytes, int] = {}
for image in self._dyldCtx.images:
imagePath = self._dyldCtx.fileCtx.readString(image.pathFileOffset)
self._images[imagePath] = image.address
pass
self._enumerateExports()
self._enumerateSymbols()
pass
def symbolizeAddr(self, addr: int) -> List[bytes]:
"""Get the name of a function at the address.
Args:
addr: The address of the function.
Returns:
A set of potential name of the function.
or None if it could not be found.
"""
if addr in self._symbolCache:
return self._symbolCache[addr]
else:
return None
def _enumerateExports(self) -> None:
# process the dependencies iteratively,
# skipping ones already processed
depsQueue: List[_DependencyInfo] = []
depsProcessed: List[bytes] = []
# load commands for all dependencies
DEP_LCS = (
LoadCommands.LC_LOAD_DYLIB,
LoadCommands.LC_PREBOUND_DYLIB,
LoadCommands.LC_LOAD_WEAK_DYLIB,
LoadCommands.LC_REEXPORT_DYLIB,
LoadCommands.LC_LAZY_LOAD_DYLIB,
LoadCommands.LC_LOAD_UPWARD_DYLIB
)
# These exports sometimes change the name of an existing
# export symbol. We have to process them last.
reExports: list[dyld_trie.ExportInfo] = []
# get an initial list of dependencies
if dylibs := self._machoCtx.getLoadCommand(DEP_LCS, multiple=True):
for dylib in dylibs:
if depInfo := self._getDepInfo(dylib, self._machoCtx):
depsQueue.append(depInfo)
pass
while len(depsQueue):
self._statusBar.update()
depInfo = depsQueue.pop()
# check if we already processed it
if next(
(name for name in depsProcessed if name == depInfo.dylibPath),
None
):
continue
depExports = self._readDepExports(depInfo)
self._cacheDepExports(depInfo, depExports)
depsProcessed.append(depInfo.dylibPath)
# check for any ReExports dylibs
if dylibs := depInfo.context.getLoadCommand(DEP_LCS, multiple=True):
for dylib in dylibs:
if dylib.cmd == LoadCommands.LC_REEXPORT_DYLIB:
if info := self._getDepInfo(dylib, depInfo.context):
depsQueue.append(info)
pass
# check for any ReExport exports
reExportOrdinals = set()
for export in depExports:
if export.flags & EXPORT_SYMBOL_FLAGS_REEXPORT:
reExportOrdinals.add(export.other)
reExports.append(export)
pass
for ordinal in reExportOrdinals:
dylib = dylibs[ordinal - 1]
if info := self._getDepInfo(dylib, depInfo.context):
depsQueue.append(info)
pass
pass
# process and add ReExport exports
for reExport in reExports:
if reExport.importName == b"\x00":
continue
found = False
name = reExport.importName
for export in self._symbolCache.values():
if name in export:
# ReExport names should get priority
export.insert(0, bytes(reExport.name))
found = True
break
if not found:
self._logger.warning(f"No root export for ReExport with symbol {name}")
pass
def _getDepInfo(
self,
dylib: dylib_command,
context: MachOContext
) -> _DependencyInfo:
"""Given a dylib command, get dependency info.
"""
dylibPathOff = dylib._fileOff_ + dylib.dylib.name.offset
dylibPath = context.fileCtx.readString(dylibPathOff)
if dylibPath not in self._images:
self._logger.warning(f"Unable to find dependency: {dylibPath}")
return None
imageAddr = self._images[dylibPath]
imageOff, dyldCtx = self._dyldCtx.convertAddr(imageAddr)
# Since we're not editing the dependencies, this should be fine.
context = MachOContext(dyldCtx.fileCtx, imageOff)
return _DependencyInfo(dylibPath, imageAddr, context)
def _readDepExports(
self,
depInfo: _DependencyInfo
) -> List[dyld_trie.ExportInfo]:
exportOff = None
exportSize = None
dyldInfo: dyld_info_command = depInfo.context.getLoadCommand(
(LoadCommands.LC_DYLD_INFO, LoadCommands.LC_DYLD_INFO_ONLY)
)
exportTrie: linkedit_data_command = depInfo.context.getLoadCommand(
(LoadCommands.LC_DYLD_EXPORTS_TRIE,)
)
if dyldInfo and dyldInfo.export_size:
exportOff = dyldInfo.export_off
exportSize = dyldInfo.export_size
elif exportTrie and exportTrie.datasize:
exportOff = exportTrie.dataoff
exportSize = exportTrie.datasize
if exportOff is None:
# Some images like UIKit don't have exports
return []
linkeditFile = self._dyldCtx.convertAddr(
depInfo.context.segments[b"__LINKEDIT"].seg.vmaddr
)[1].fileCtx.file
try:
depExports = dyld_trie.ReadExports(
linkeditFile,
exportOff,
exportSize,
)
return depExports
except dyld_trie.ExportReaderError as e:
self._logger.warning(f"Unable to read exports of {depInfo.dylibPath}, reason: {e}") # noqa
return []
def _cacheDepExports(
self,
depInfo: _DependencyInfo,
exports: List[dyld_trie.ExportInfo]
) -> None:
for export in exports:
if not export.address:
continue
exportAddr = depInfo.imageAddress + export.address
if exportAddr in self._symbolCache:
self._symbolCache[exportAddr].append(bytes(export.name))
else:
self._symbolCache[exportAddr] = [bytes(export.name)]
if export.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER:
# The address points to the stub, while "other" points
# to the function itself. Add the function as well.
functionAddr = depInfo.imageAddress + export.other
if functionAddr in self._symbolCache:
self._symbolCache[functionAddr].append(bytes(export.name))
else:
self._symbolCache[functionAddr] = [bytes(export.name)]
pass
def _enumerateSymbols(self) -> None:
"""Cache potential symbols in the symbol table.
"""
symtab: symtab_command = self._machoCtx.getLoadCommand(
(LoadCommands.LC_SYMTAB,)
)
if not symtab:
self._logger.warning("Unable to find LC_SYMTAB.")
return
linkeditFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__LINKEDIT"].seg.vmaddr
)
for i in range(symtab.nsyms):
self._statusBar.update()
# Get the symbol and its address
entryOff = symtab.symoff + (i * nlist_64.SIZE)
symbolEntry = nlist_64(linkeditFile.file, entryOff)
symbolAddr = symbolEntry.n_value
symbol = linkeditFile.readString(symtab.stroff + symbolEntry.n_strx)
if symbolAddr == 0:
continue
if not self._machoCtx.containsAddr(symbolAddr):
self._logger.warning(f"Invalid address: {symbolAddr}, for symbol entry: {symbol}.") # noqa
continue
# save it to the cache
if symbolAddr in self._symbolCache:
self._symbolCache[symbolAddr].append(bytes(symbol))
else:
self._symbolCache[symbolAddr] = [bytes(symbol)]
pass
pass
pass
class _StubFormat(enum.Enum):
# Non optimized stub with a symbol pointer
# and a stub helper.
StubNormal = 1
# Optimized stub with a symbol pointer
# and a stub helper.
StubOptimized = 2
# Non optimized auth stub with a symbol pointer.
AuthStubNormal = 3
# Optimized auth stub with a branch to a function.
AuthStubOptimized = 4
# Non optimized auth stub with a symbol pointer
# and a resolver.
AuthStubResolver = 5
# A special stub helper with a branch to a function.
Resolver = 6
pass
class Arm64Utilities(object):
def __init__(self, extractionCtx: ExtractionContext) -> None:
super().__init__()
self._dyldCtx = extractionCtx.dyldCtx
self._slider = slide_info.PointerSlider(extractionCtx)
def getResolverTarget(address):
if resolverData := self.getResolverData(address):
# Don't need the size of the resolver
return resolverData[0]
else:
return None
self._stubResolvers = (
(self._getStubNormalTarget, _StubFormat.StubNormal),
(self._getStubOptimizedTarget, _StubFormat.StubOptimized),
(self._getAuthStubNormalTarget, _StubFormat.AuthStubNormal),
(self._getAuthStubOptimizedTarget, _StubFormat.AuthStubOptimized),
(self._getAuthStubResolverTarget, _StubFormat.AuthStubResolver),
(getResolverTarget, _StubFormat.Resolver)
)
# A cache of resolved stub chains
self._resolveCache: Dict[int, int] = {}
pass
def generateStubNormal(self, stubAddress: int, ldrAddress: int) -> bytes:
"""Create a normal stub.
Args:
stubAddress: The address of the stub to generate.
ldrAddress: The address of the pointer targeted by the ldr instruction.
Returns:
The bytes of the generated stub.
"""
# ADRP X16, lp@page
adrpDelta = (ldrAddress & -4096) - (stubAddress & -4096)
immhi = (adrpDelta >> 9) & (0x00FFFFE0)
immlo = (adrpDelta << 17) & (0x60000000)
newAdrp = (0x90000010) | immlo | immhi
# LDR X16, [X16, lp@pageoff]
ldrOffset = ldrAddress - (ldrAddress & -4096)
imm12 = (ldrOffset << 7) & 0x3FFC00
newLdr = 0xF9400210 | imm12
# BR X16
newBr = 0xD61F0200
return struct.pack("<III", newAdrp, newLdr, newBr)
def generateAuthStubNormal(self, stubAddress: int, ldrAddress: int) -> bytes:
"""Create a normal auth stub.
Args:
stubAddress: The address of the stub to generate.
ldrAddress: The address of the pointer targeted by the ldr instruction.
Returns:
The bytes of the generated stub.
"""
"""
91 59 11 90 adrp x17,0x1e27e5000
31 22 0d 91 add x17,x17,#0x348
30 02 40 f9 ldr x16,[x17]=>->__auth_stubs::_CCRandomCopyBytes = 1bfcb5d50
11 0a 1f d7 braa x16=>__auth_stubs::_CCRandomCopyBytes,x17
"""
# ADRP X17, sp@page
adrpDelta = (ldrAddress & -4096) - (stubAddress & -4096)
immhi = (adrpDelta >> 9) & (0x00FFFFE0)
immlo = (adrpDelta << 17) & (0x60000000)
newAdrp = (0x90000011) | immlo | immhi
# ADD X17, [X17, sp@pageoff]
addOffset = ldrAddress - (ldrAddress & -4096)
imm12 = (addOffset << 10) & 0x3FFC00
newAdd = 0x91000231 | imm12
# LDR X16, [X17, 0]
newLdr = 0xF9400230
# BRAA X16
newBraa = 0xD71F0A11
return struct.pack("<IIII", newAdrp, newAdd, newLdr, newBraa)
def resolveStubChain(self, address: int) -> int:
"""Follow a stub to its target function.
Args:
address: The address of the stub.
Returns:
The final target of the stub chain.
"""
if address in self._resolveCache:
return self._resolveCache[address]
target = address
while True:
if stubData := self.resolveStub(target):
target = stubData[0]
else:
break
self._resolveCache[address] = target
return target
def resolveStub(self, address: int) -> Tuple[int, _StubFormat]:
"""Get the stub and its format.
Args:
address: The address of the stub.
Returns:
A tuple containing the target of the branch
and its format, or None if it could not be
determined.
"""
for resolver, stubFormat in self._stubResolvers:
if (result := resolver(address)) is not None:
return (result, stubFormat)
pass
return None
def getStubHelperData(self, address: int) -> int:
"""Get the bind data of a stub helper.
Args:
address: The address of the stub helper.
Returns:
The bind data associated with a stub helper.
If unable to get the bind data, return None.
"""
helperOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if helperOff is None:
return None
ldr, b, data = ctx.fileCtx.readFormat("<III", helperOff)
# verify
if (
(ldr & 0xBF000000) != 0x18000000
or (b & 0xFC000000) != 0x14000000
):
return None
return data
def getResolverData(self, address: int) -> Tuple[int, int]:
"""Get the data of a resolver.
This is a stub helper that branches to a function
that should be within the same MachO file.
Args:
address: The address of the resolver.
Returns:
A tuple containing the target of the resolver
and its size. Or None if it could not be determined.
"""
"""
fd 7b bf a9 stp x29,x30,[sp, #local_10]!
fd 03 00 91 mov x29,sp
e1 03 bf a9 stp x1,x0,[sp, #local_20]!
e3 0b bf a9 stp x3,x2,[sp, #local_30]!
e5 13 bf a9 stp x5,x4,[sp, #local_40]!
e7 1b bf a9 stp x7,x6,[sp, #local_50]!
e1 03 bf 6d stp d1,d0,[sp, #local_60]!
e3 0b bf 6d stp d3,d2,[sp, #local_70]!
e5 13 bf 6d stp d5,d4,[sp, #local_80]!
e7 1b bf 6d stp d7,d6,[sp, #local_90]!
5f d4 fe 97 bl _vDSP_vadd
70 e6 26 90 adrp x16,0x1e38ba000
10 02 0f 91 add x16,x16,#0x3c0
00 02 00 f9 str x0,[x16]
f0 03 00 aa mov x16,x0
e7 1b c1 6c ldp d7,d6,[sp], #0x10
e5 13 c1 6c ldp d5,d4,[sp], #0x10
e3 0b c1 6c ldp d3,d2,[sp], #0x10
e1 03 c1 6c ldp d1,d0,[sp], #0x10
e7 1b c1 a8 ldp x7,x6,[sp], #0x10
e5 13 c1 a8 ldp x5,x4,[sp], #0x10
e3 0b c1 a8 ldp x3,x2,[sp], #0x10
e1 03 c1 a8 ldp x1,x0,[sp], #0x10
fd 7b c1 a8 ldp x29=>local_10,x30,[sp], #0x10
1f 0a 1f d6 braaz x16
Because the format is not the same across iOS versions,
the following conditions are used to verify it.
* Starts with stp and mov
* A branch within an arbitrary threshold
* bl is in the middle
* adrp is directly after bl
* ldp is directly before the branch
"""
SEARCH_LIMIT = 0xC8
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
# test stp and mov
stp, mov = ctx.fileCtx.readFormat("<II", stubOff)
if (
(stp & 0x7FC00000) != 0x29800000
or (mov & 0x7F3FFC00) != 0x11000000
):
return None
# Find the branch instruction
dataSource = ctx.fileCtx.file
branchInstrOff = None
for instrOff in range(stubOff, stubOff + SEARCH_LIMIT, 4):
# (instr & 0xFE9FF000) == 0xD61F0000
if (
dataSource[instrOff + 1] & 0xF0 == 0x00
and dataSource[instrOff + 2] & 0x9F == 0x1F
and dataSource[instrOff + 3] & 0xFE == 0xD6
):
branchInstrOff = instrOff
break
pass
if branchInstrOff is None:
return None
# find the bl instruction
blInstrOff = None
for instrOff in range(stubOff, branchInstrOff, 4):
# (instruction & 0xFC000000) == 0x94000000
if (dataSource[instrOff + 3] & 0xFC) == 0x94:
blInstrOff = instrOff
break
pass
if blInstrOff is None:
return None
# Test if there is a stp before the bl and a ldp before the braaz
adrp = ctx.fileCtx.readFormat("<I", blInstrOff + 4)[0]
ldp = ctx.fileCtx.readFormat("<I", branchInstrOff - 4)[0]
if (
(adrp & 0x9F00001F) != 0x90000010
or (ldp & 0x7FC00000) != 0x28C00000
):
return None
# Hopefully it's a resolver...
imm = (ctx.fileCtx.readFormat("<I", blInstrOff)[0] & 0x3FFFFFF) << 2
imm = self.signExtend(imm, 28)
blResult = address + (blInstrOff - stubOff) + imm
resolverSize = branchInstrOff - stubOff + 4
return (blResult, resolverSize)
def getStubLdrAddr(self, address: int) -> int:
"""Get the ldr address of a normal stub.
Args:
address: The address of the stub.
Returns:
The address of the ldr, or None if it can't
be determined.
"""
if (ldrAddr := self._getStubNormalLdrAddr(address)) is not None:
return ldrAddr
elif (ldrAddr := self._getAuthStubNormalLdrAddr(address)) is not None:
return ldrAddr
else:
return None
@staticmethod
def signExtend(value: int, size: int) -> int:
if value & (1 << (size - 1)):
return value - (1 << size)
return value
def _getStubNormalLdrAddr(self, address: int) -> int:
"""Get the ldr address of a normal stub.
Args:
address: The address of the stub.
Returns:
The address of the ldr, or None if it can't
be determined.
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, ldr, br = ctx.fileCtx.readFormat("<III", stubOff)
# verify
if (
(adrp & 0x9F00001F) != 0x90000010
or (ldr & 0xFFC003FF) != 0xF9400210
or br != 0xD61F0200
):
return None
# adrp
immlo = (adrp & 0x60000000) >> 29
immhi = (adrp & 0xFFFFE0) >> 3
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# ldr
imm12 = (ldr & 0x3FFC00) >> 7
return adrpResult + imm12
def _getAuthStubNormalLdrAddr(self, address: int) -> int:
"""Get the Ldr address of a normal auth stub.
Args:
address: The address of the stub.
Returns:
The Ldr address of the stub or None if it could
not be determined.
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, add, ldr, braa = ctx.fileCtx.readFormat(
"<IIII",
stubOff
)
# verify
if (
(adrp & 0x9F000000) != 0x90000000
or (add & 0xFFC00000) != 0x91000000
or (ldr & 0xFFC00000) != 0xF9400000
or (braa & 0xFEFFF800) != 0xD61F0800
):
return None
# adrp
immhi = (adrp & 0xFFFFE0) >> 3
immlo = (adrp & 0x60000000) >> 29
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# add
imm = (add & 0x3FFC00) >> 10
addResult = adrpResult + imm
# ldr
imm = (ldr & 0x3FFC00) >> 7
return addResult + imm
def _getStubNormalTarget(self, address: int) -> int:
"""
ADRP x16, page
LDR x16, [x16, pageoff]
BR x16
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, ldr, br = ctx.fileCtx.readFormat("<III", stubOff)
# verify
if (
(adrp & 0x9F00001F) != 0x90000010
or (ldr & 0xFFC003FF) != 0xF9400210
or br != 0xD61F0200
):
return None
# adrp
immlo = (adrp & 0x60000000) >> 29
immhi = (adrp & 0xFFFFE0) >> 3
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# ldr
offset = (ldr & 0x3FFC00) >> 7
ldrTarget = adrpResult + offset
return self._slider.slideAddress(ldrTarget)
def _getStubOptimizedTarget(self, address: int) -> int:
"""
ADRP x16, page
ADD x16, x16, offset
BR x16
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, add, br = ctx.fileCtx.readFormat("<III", stubOff)
# verify
if (
(adrp & 0x9F00001F) != 0x90000010
or (add & 0xFFC003FF) != 0x91000210
or br != 0xD61F0200
):
return None
# adrp
immlo = (adrp & 0x60000000) >> 29
immhi = (adrp & 0xFFFFE0) >> 3
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# add
imm12 = (add & 0x3FFC00) >> 10
return adrpResult + imm12
def _getAuthStubNormalTarget(self, address: int) -> int:
"""
91 59 11 90 adrp x17,0x1e27e5000
31 22 0d 91 add x17,x17,#0x348
30 02 40 f9 ldr x16,[x17]=>->__auth_stubs::_CCRandomCopyBytes
11 0a 1f d7 braa x16=>__auth_stubs::_CCRandomCopyBytes,x17
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, add, ldr, braa = ctx.fileCtx.readFormat("<IIII", stubOff)
# verify
if (
(adrp & 0x9F000000) != 0x90000000
or (add & 0xFFC00000) != 0x91000000
or (ldr & 0xFFC00000) != 0xF9400000
or (braa & 0xFEFFF800) != 0xD61F0800
):
return None
# adrp
immhi = (adrp & 0xFFFFE0) >> 3
immlo = (adrp & 0x60000000) >> 29
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# add
imm = (add & 0x3FFC00) >> 10
addResult = adrpResult + imm
# ldr
imm = (ldr & 0x3FFC00) >> 7
ldrTarget = addResult + imm
return self._slider.slideAddress(ldrTarget)
pass
def _getAuthStubOptimizedTarget(self, address: int) -> int:
"""
1bfcb5d20 30 47 e2 90 adrp x16,0x184599000
1bfcb5d24 10 62 30 91 add x16,x16,#0xc18
1bfcb5d28 00 02 1f d6 br x16=>LAB_184599c18
1bfcb5d2c 20 00 20 d4 trap
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, add, br, trap = ctx.fileCtx.readFormat("<IIII", stubOff)
# verify
if (
(adrp & 0x9F000000) != 0x90000000
or (add & 0xFFC00000) != 0x91000000
or br != 0xD61F0200
or trap != 0xD4200020
):
return None
# adrp
immhi = (adrp & 0xFFFFE0) >> 3
immlo = (adrp & 0x60000000) >> 29
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# add
imm = (add & 0x3FFC00) >> 10
return adrpResult + imm
def _getAuthStubResolverTarget(self, address: int) -> int:
"""
70 e6 26 b0 adrp x16,0x1e38ba000
10 e6 41 f9 ldr x16,[x16, #0x3c8]
1f 0a 1f d6 braaz x16=>FUN_195bee070
"""
stubOff, ctx = self._dyldCtx.convertAddr(address) or (None, None)
if stubOff is None:
return None
adrp, ldr, braaz = ctx.fileCtx.readFormat("<III", stubOff)
# verify
if (
(adrp & 0x9F000000) != 0x90000000
or (ldr & 0xFFC00000) != 0xF9400000
or (braaz & 0xFEFFF800) != 0xD61F0800
):
return None
# adrp
immhi = (adrp & 0xFFFFE0) >> 3
immlo = (adrp & 0x60000000) >> 29
imm = (immhi | immlo) << 12
imm = self.signExtend(imm, 33)
adrpResult = (address & ~0xFFF) + imm
# ldr
imm = (ldr & 0x3FFC00) >> 7
ldrTarget = adrpResult + imm
return self._slider.slideAddress(ldrTarget)
pass
@dataclasses.dataclass
class _BindRecord(object):
ordinal: int = None
flags: int = None
symbol: bytes = None
symbolType: int = None
addend: int = None
segment: int = None
offset: int = None
pass
def _bindReader(
fileCtx: FileContext,
bindOff: int,
bindSize: int
) -> Iterator[_BindRecord]:
"""Read all the bind records
Args:
fileCtx: The source file to read from.
bindOff: The offset in the fileCtx to read from.
bindSize: The total size of the bind data.
Returns:
A list of bind records.
Raises:
KeyError: If the reader encounters an unknown bind opcode.
"""
file = fileCtx.file
currentRecord = _BindRecord()
bindDataEnd = bindOff + bindSize
while bindOff < bindDataEnd:
bindOpcodeImm = file[bindOff]
opcode = bindOpcodeImm & BIND_OPCODE_MASK
imm = bindOpcodeImm & BIND_IMMEDIATE_MASK
bindOff += 1
if opcode == BIND_OPCODE_DONE:
# Only resets the record apparently
currentRecord = _BindRecord()
pass
elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
currentRecord.ordinal = imm
pass
elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
currentRecord.ordinal, bindOff = leb128.decodeUleb128(file, bindOff)
pass
elif opcode == BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
if imm == 0:
currentRecord.ordinal = BIND_SPECIAL_DYLIB_SELF
else:
if imm == 1:
currentRecord.ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
elif imm == 2:
currentRecord.ordinal = BIND_SPECIAL_DYLIB_FLAT_LOOKUP
elif imm == 3:
currentRecord.ordinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP
else:
raise KeyError(f"Unknown special ordinal: {imm}")
pass
elif opcode == BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
currentRecord.flags = imm
currentRecord.symbol = fileCtx.readString(bindOff)
bindOff += len(currentRecord.symbol)
pass
elif opcode == BIND_OPCODE_SET_TYPE_IMM:
currentRecord.symbolType = imm
pass
elif opcode == BIND_OPCODE_SET_ADDEND_SLEB:
currentRecord.addend, bindOff = leb128.decodeSleb128(file, bindOff)
pass
elif opcode == BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
currentRecord.segment = imm
currentRecord.offset, bindOff = leb128.decodeUleb128(file, bindOff)
pass
elif opcode == BIND_OPCODE_ADD_ADDR_ULEB:
add, bindOff = leb128.decodeUleb128(file, bindOff)
add = Arm64Utilities.signExtend(add, 64)
currentRecord.offset += add
pass
elif opcode == BIND_OPCODE_DO_BIND:
yield dataclasses.replace(currentRecord)
currentRecord.offset += 8
pass
elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
yield dataclasses.replace(currentRecord)
add, bindOff = leb128.decodeUleb128(file, bindOff)
add = Arm64Utilities.signExtend(add, 64)
currentRecord.offset += add + 8
pass
elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
yield dataclasses.replace(currentRecord)
currentRecord.offset += (imm * 8) + 8
pass
elif opcode == BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
count, bindOff = leb128.decodeUleb128(file, bindOff)
skip, bindOff = leb128.decodeUleb128(file, bindOff)
for _ in range(count):
yield dataclasses.replace(currentRecord)
currentRecord.offset += skip + 8
pass
else:
raise KeyError(f"Unknown bind opcode: {opcode}")
pass
pass
class _StubFixerError(Exception):
pass
class _StubFixer(object):
def __init__(self, extractionCtx: ExtractionContext) -> None:
super().__init__()
self._extractionCtx = extractionCtx
self._dyldCtx = extractionCtx.dyldCtx
self._machoCtx = extractionCtx.machoCtx
self._statusBar = extractionCtx.statusBar
self._logger = extractionCtx.logger
pass
def run(self):
self._statusBar.update(status="Caching Symbols")
self._symbolizer = _Symbolizer(self._extractionCtx)
self._arm64Utils = Arm64Utilities(self._extractionCtx)
self._slider = slide_info.PointerSlider(self._extractionCtx)
self._symtab: symtab_command = self._machoCtx.getLoadCommand(
(LoadCommands.LC_SYMTAB,)
)
if not self._symtab:
raise _StubFixerError("Unable to get symtab_command.")
self._dysymtab: dysymtab_command = self._machoCtx.getLoadCommand(
(LoadCommands.LC_DYSYMTAB,)
)
if not self._dysymtab:
raise _StubFixerError("Unable to get dysymtab_command.")
symbolPtrs = self._enumerateSymbolPointers()
self._fixStubHelpers()
stubMap = self._fixStubs(symbolPtrs)
self._fixCallsites(stubMap)
self._fixIndirectSymbols(symbolPtrs, stubMap)
pass
def _enumerateSymbolPointers(self) -> Dict[bytes, Tuple[int]]:
"""Generate a mapping between a pointer's symbol and its address.
"""
# read all the bind records as they're a source of symbolic info
bindRecords: Dict[int, _BindRecord] = {}
dyldInfo: dyld_info_command = self._machoCtx.getLoadCommand(
(LoadCommands.LC_DYLD_INFO, LoadCommands.LC_DYLD_INFO_ONLY)
)
linkeditFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__LINKEDIT"].seg.vmaddr
)
if dyldInfo:
records: List[_BindRecord] = []
try:
if dyldInfo.weak_bind_size:
# usually contains records for c++ symbols like "new"
records.extend(
_bindReader(
linkeditFile,
dyldInfo.weak_bind_off,
dyldInfo.weak_bind_size
)
)
pass
if dyldInfo.lazy_bind_off:
records.extend(
_bindReader(
linkeditFile,
dyldInfo.lazy_bind_off,
dyldInfo.lazy_bind_size
)
)
pass
for record in records:
# check if we have the info needed
if (
record.symbol is None
or record.segment is None
or record.offset is None
):
self._logger.warning(f"Incomplete lazy bind record: {record}")
continue
bindAddr = self._machoCtx.segmentsI[record.segment].seg.vmaddr
bindAddr += record.offset
bindRecords[bindAddr] = record
pass
except KeyError as e:
self._logger.error(f"Unable to read bind records, reasons: {e}")
pass
# enumerate all symbol pointers
symbolPtrs: Dict[bytes, List[int]] = {}
def _addToMap(ptrSymbol: bytes, ptrAddr: int, section: section_64):
if ptrSymbol in symbolPtrs:
# give priority to ptrs in the __auth_got section
if section.sectname == b"__auth_got":
symbolPtrs[ptrSymbol].insert(0, ptrAddr)
else:
symbolPtrs[ptrSymbol].append(ptrAddr)
else:
symbolPtrs[ptrSymbol] = [ptrAddr]
pass
for segment in self._machoCtx.segmentsI:
for sect in segment.sectsI:
sectType = sect.flags & SECTION_TYPE
if (
sectType == S_NON_LAZY_SYMBOL_POINTERS
or sectType == S_LAZY_SYMBOL_POINTERS
):
for i in range(int(sect.size / 8)):
self._statusBar.update(status="Caching Symbol Pointers")
ptrAddr = sect.addr + (i * 8)
# Try to symbolize through bind records
if ptrAddr in bindRecords:
_addToMap(bindRecords[ptrAddr].symbol, ptrAddr, sect)
continue
# Try to symbolize though indirect symbol entries
symbolIndex = linkeditFile.readFormat(
"<I",
self._dysymtab.indirectsymoff + ((sect.reserved1 + i) * 4)
)[0]
if (
symbolIndex != 0
and symbolIndex != INDIRECT_SYMBOL_ABS
and symbolIndex != INDIRECT_SYMBOL_LOCAL
and symbolIndex != (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL)
):
symbolEntry = nlist_64(
linkeditFile.file,
self._symtab.symoff + (symbolIndex * nlist_64.SIZE)
)
symbol = linkeditFile.readString(
self._symtab.stroff + symbolEntry.n_strx
)
_addToMap(symbol, ptrAddr, sect)
continue
# Try to symbolize though the pointers target
ptrTarget = self._slider.slideAddress(ptrAddr)
ptrFunc = self._arm64Utils.resolveStubChain(ptrTarget)
if symbols := self._symbolizer.symbolizeAddr(ptrFunc):
for sym in symbols:
_addToMap(sym, ptrAddr, sect)
continue
# Skip special cases like __csbitmaps in CoreFoundation
if self._machoCtx.containsAddr(ptrTarget):
continue
self._logger.warning(f"Unable to symbolize pointer at {hex(ptrAddr)}, with indirect entry index {hex(sect.reserved1 + i)}, with target function {hex(ptrFunc)}") # noqa
pass
pass
pass
pass
return symbolPtrs
def _fixStubHelpers(self) -> None:
"""Relink symbol pointers to stub helpers.
"""
STUB_BINDER_SIZE = 0x18
REG_HELPER_SIZE = 0xC
try:
helperSect = self._machoCtx.segments[b"__TEXT"].sects[b"__stub_helper"]
except KeyError:
return
dyldInfo: dyld_info_command = self._machoCtx.getLoadCommand(
(LoadCommands.LC_DYLD_INFO, LoadCommands.LC_DYLD_INFO_ONLY)
)
if not dyldInfo:
return
linkeditFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__LINKEDIT"].seg.vmaddr
)
# the stub helper section has the stub binder in
# beginning, skip it.
helperAddr = helperSect.addr + STUB_BINDER_SIZE
helperEnd = helperSect.addr + helperSect.size
while helperAddr < helperEnd:
self._statusBar.update(status="Fixing Lazy symbol Pointers")
if (bindOff := self._arm64Utils.getStubHelperData(helperAddr)) is not None:
record = next(
_bindReader(
linkeditFile,
dyldInfo.lazy_bind_off + bindOff,
dyldInfo.lazy_bind_size,
),
None
)
if (
record is None
or record.symbol is None
or record.segment is None
or record.offset is None
):
self._logger.warning(f"Bind record for stub helper is incomplete: {record}") # noqa
helperAddr += REG_HELPER_SIZE
continue
# repoint the bind pointer to the stub helper
bindPtrAddr = self._machoCtx.segmentsI[record.segment].seg.vmaddr
bindPtrOff = self._dyldCtx.convertAddr(bindPtrAddr)[0] + record.offset
ctx = self._machoCtx.fileForAddr(bindPtrAddr)
newBindPtr = struct.pack("<Q", helperAddr)
ctx.writeBytes(bindPtrOff, newBindPtr)
helperAddr += REG_HELPER_SIZE
continue
# it may be a resolver
if resolverInfo := self._arm64Utils.getResolverData(helperAddr):
# it shouldn't need fixing but check it just in case.
if not self._machoCtx.containsAddr(resolverInfo[0]):
self._logger.warning(f"Unable to fix resolver at {hex(helperAddr)}")
helperAddr += resolverInfo[1] # add by resolver size
continue
self._logger.warning(f"Unknown stub helper format at {hex(helperAddr)}")
helperAddr += REG_HELPER_SIZE
pass
pass
def _fixStubs(
self,
symbolPtrs: Dict[bytes, Tuple[int]]
) -> Dict[bytes, Tuple[int]]:
"""Relink stubs to their symbol pointers
"""
stubMap: Dict[bytes, List[int]] = {}
def _addToMap(stubName: bytes, stubAddr: int):
if stubName in stubMap:
stubMap[stubName].append(stubAddr)
else:
stubMap[stubName] = [stubAddr]
pass
linkeditFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__LINKEDIT"].seg.vmaddr
)
textFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__TEXT"].seg.vmaddr
)
symbolPtrFile = None
for segment in self._machoCtx.segmentsI:
for sect in segment.sectsI:
if sect.flags & SECTION_TYPE == S_SYMBOL_STUBS:
for i in range(int(sect.size / sect.reserved2)):
self._statusBar.update(status="Fixing Stubs")
stubAddr = sect.addr + (i * sect.reserved2)
# First symbolize the stub
stubNames = None
# Try to symbolize though indirect symbol entries
symbolIndex = linkeditFile.readFormat(
"<I",
self._dysymtab.indirectsymoff + ((sect.reserved1 + i) * 4)
)[0]
if (
symbolIndex != 0
and symbolIndex != INDIRECT_SYMBOL_ABS
and symbolIndex != INDIRECT_SYMBOL_LOCAL
and symbolIndex != (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL)
):
symbolEntry = nlist_64(
linkeditFile.file,
self._symtab.symoff + (symbolIndex * nlist_64.SIZE)
)
stubNames = [
linkeditFile.readString(self._symtab.stroff + symbolEntry.n_strx)
]
pass
# If the stub isn't optimized,
# try to symbolize it though its pointer
if not stubNames:
if (ptrAddr := self._arm64Utils.getStubLdrAddr(stubAddr)) is not None:
stubNames = [
sym for sym, ptrs in symbolPtrs.items() if ptrAddr in ptrs
]
pass
pass
# If the stub is optimized,
# try to symbolize it though its target function
if not stubNames:
stubTarget = self._arm64Utils.resolveStubChain(stubAddr)
stubNames = self._symbolizer.symbolizeAddr(stubTarget)
pass
if not stubNames:
self._logger.warning(f"Unable to symbolize stub at {hex(stubAddr)}")
continue
for name in stubNames:
_addToMap(name, stubAddr)
# Try to find a symbol pointer for the stub
symPtrAddr = None
# if the stub is not optimized,
# we can match it though the ldr instruction
symPtrAddr = self._arm64Utils.getStubLdrAddr(stubAddr)
# Try to match a pointer though symbols
if not symPtrAddr:
symPtrAddr = next(
(symbolPtrs[sym][0] for sym in symbolPtrs if sym in stubNames),
None
)
pass
if not symPtrAddr:
self._logger.warning(f"Unable to find a symbol pointer for stub at {hex(stubAddr)}, with names {stubNames}") # noqa
continue
# relink the stub if necessary
if stubData := self._arm64Utils.resolveStub(stubAddr):
stubFormat = stubData[1]
if stubFormat == _StubFormat.StubNormal:
# No fix needed
continue
elif stubFormat == _StubFormat.StubOptimized:
# only need to relink stub
newStub = self._arm64Utils.generateStubNormal(stubAddr, symPtrAddr)
stubOff = self._dyldCtx.convertAddr(stubAddr)[0]
textFile.writeBytes(stubOff, newStub)
continue
elif stubFormat == _StubFormat.AuthStubNormal:
# only need to relink symbol pointer
symPtrOff = self._dyldCtx.convertAddr(symPtrAddr)[0]
if not symbolPtrFile:
symbolPtrFile = self._machoCtx.fileForAddr(symPtrAddr)
pass
symbolPtrFile.writeBytes(symPtrOff, struct.pack("<Q", stubAddr))
continue
elif stubFormat == _StubFormat.AuthStubOptimized:
# need to relink both the stub and the symbol pointer
symPtrOff = self._dyldCtx.convertAddr(symPtrAddr)[0]
if not symbolPtrFile:
symbolPtrFile = self._machoCtx.fileForAddr(symPtrAddr)
pass
symbolPtrFile.writeBytes(symPtrOff, struct.pack("<Q", stubAddr))
newStub = self._arm64Utils.generateAuthStubNormal(stubAddr, symPtrAddr)
stubOff, ctx = self._dyldCtx.convertAddr(stubAddr)
textFile.writeBytes(stubOff, newStub)
continue
elif stubFormat == _StubFormat.AuthStubResolver:
# These shouldn't need fixing but check just in case
if not self._machoCtx.containsAddr(stubData[0]):
self._logger.error(f"Unable to fix auth stub resolver at {hex(stubAddr)}") # noqa
continue
elif stubFormat == _StubFormat.Resolver:
# how did we get here???
self._logger.warning(f"Encountered a resolver at {hex(stubAddr)} while fixing stubs") # noqa
continue
else:
self._logger.error(f"Unknown stub format: {stubFormat}, at {hex(stubAddr)}") # noqa
continue
else:
self._logger.warning(f"Unknown stub format at {hex(stubAddr)}")
continue
pass
pass
pass
return stubMap
def _fixCallsites(self, stubMap: Dict[bytes, Tuple[int]]) -> None:
if (
b"__TEXT" not in self._machoCtx.segments
or b"__text" not in self._machoCtx.segments[b"__TEXT"].sects
):
raise _StubFixerError("Unable to get __text section.")
textSect = self._machoCtx.segments[b"__TEXT"].sects[b"__text"]
textAddr = textSect.addr
# Section offsets by section_64.offset are sometimes
# inaccurate, like in libcrypto.dylib
textOff = self._dyldCtx.convertAddr(textAddr)[0]
textFile = self._machoCtx.fileForAddr(textAddr)
for sectOff in range(0, textSect.size, 4):
# We are only looking for bl and b instructions only.
# Theses instructions are only identical by their top
# most byte. By only looking at the top byte, we can
# save a lot of time.
instrOff = textOff + sectOff
instrTop = textFile.file[instrOff + 3] & 0xFC
if (
instrTop != 0x94 # bl
and instrTop != 0x14 # b
):
continue
# get the target of the branch
brInstr = textFile.readFormat("<I", instrOff)[0]
imm26 = brInstr & 0x3FFFFFF
brOff = self._arm64Utils.signExtend(imm26 << 2, 28)
brAddr = textAddr + sectOff
brTarget = brAddr + brOff
# check if it needs fixing
if self._machoCtx.containsAddr(brTarget):
continue
# find the matching stub for the branch
brTargetFunc = self._arm64Utils.resolveStubChain(brTarget)
if not (funcSymbols := self._symbolizer.symbolizeAddr(brTargetFunc)):
# Sometimes there are bytes of data in the text section
# that match the bl and b filter, these seem to follow a
# BR or other branch, skip these.
lastInstTop = textFile.file[instrOff + 3] & 0xFC
if (
lastInstTop == 0x94 # bl
or lastInstTop == 0x14 # b
or lastInstTop == 0xD6 # br
):
continue
self._logger.warning(f"Unable to symbolize branch at {hex(brAddr)}, targeting {hex(brTargetFunc)}") # noqa
continue
stubSymbol = next((sym for sym in funcSymbols if sym in stubMap), None)
if not stubSymbol:
# Same as above
lastInstTop = textFile.file[instrOff + 3] & 0xFC
if (
lastInstTop == 0x94 # bl
or lastInstTop == 0x14 # b
or lastInstTop == 0xD6 # br
):
continue
self._logger.warning(f"Unable to find a stub for branch at {hex(brAddr)}, potential symbols: {funcSymbols}") # noqa
continue
# repoint the branch to the stub
stubAddr = stubMap[stubSymbol][0]
imm26 = (stubAddr - brAddr) >> 2
brInstr = (brInstr & 0xFC000000) | imm26
struct.pack_into("<I", textFile.file, instrOff, brInstr)
self._statusBar.update(status="Fixing Callsites")
pass
pass
def _fixIndirectSymbols(
self,
symbolPtrs: Dict[bytes, Tuple[int]],
stubMap: Dict[bytes, Tuple[int]]
) -> None:
"""Fix indirect symbols.
Some files have indirect symbols that are redacted,
These are then pointed to the "redacted" symbol entry.
But disassemblers like Ghidra use these to symbolize
stubs and other pointers.
"""
if not self._extractionCtx.hasRedactedIndirect:
return
self._statusBar.update(status="Fixing Indirect Symbols")
linkeditFile = self._machoCtx.fileForAddr(
self._machoCtx.segments[b"__LINKEDIT"].seg.vmaddr
)
currentSymbolIndex = self._dysymtab.iundefsym + self._dysymtab.nundefsym
currentStringIndex = self._symtab.strsize
newSymbols = bytearray()
newStrings = bytearray()
for seg in self._machoCtx.segmentsI:
for sect in seg.sectsI:
sectType = sect.flags & SECTION_TYPE
if sectType == S_SYMBOL_STUBS:
indirectStart = sect.reserved1
indirectEnd = sect.reserved1 + int(sect.size / sect.reserved2)
for i in range(indirectStart, indirectEnd):
self._statusBar.update()
entryOffset = self._dysymtab.indirectsymoff + (i * 4)
entry = linkeditFile.readFormat("<I", entryOffset)[0]
if entry != 0:
continue
stubAddr = sect.addr + ((i - indirectStart) * sect.reserved2)
stubSymbol = next(
(sym for (sym, ptrs) in stubMap.items() if stubAddr in ptrs),
None
)
if not stubSymbol:
self._logger.warning(f"Unable to symbolize indirect stub symbol at {hex(stubAddr)}, indirect symbol index {i}") # noqa
continue
# create the entry and add the string
newSymbolEntry = nlist_64()
newSymbolEntry.n_type = 1
newSymbolEntry.n_strx = currentStringIndex
newStrings.extend(stubSymbol)
currentStringIndex += len(stubSymbol)
# update the indirect entry and add it
linkeditFile.writeBytes(
entryOffset,
struct.pack("<I", currentSymbolIndex)
)
newSymbols.extend(newSymbolEntry)
currentSymbolIndex += 1
pass
pass
elif (
sectType == S_NON_LAZY_SYMBOL_POINTERS
or sectType == S_LAZY_SYMBOL_POINTERS
):
indirectStart = sect.reserved1
indirectEnd = sect.reserved1 + int(sect.size / 8)
for i in range(indirectStart, indirectEnd):
self._statusBar.update()
entryOffset = self._dysymtab.indirectsymoff + (i * 4)
entry = linkeditFile.readFormat("<I", entryOffset)[0]
if entry != 0:
continue
ptrAddr = sect.addr + ((i - indirectStart) * 8)
ptrSymbol = next(
(sym for (sym, ptrs) in symbolPtrs.items() if ptrAddr in ptrs),
None
)
if not ptrSymbol:
self._logger.warning(f"Unable to symbolize pointer at {hex(ptrAddr)}, indirect entry index {i}") # noqa
continue
# create the entry and add the string
newSymbolEntry = nlist_64()
newSymbolEntry.n_type = 1
newSymbolEntry.n_strx = currentStringIndex
newStrings.extend(ptrSymbol)
currentStringIndex += len(ptrSymbol)
# update the indirect entry and add it
linkeditFile.writeBytes(
entryOffset,
struct.pack("<I", currentSymbolIndex)
)
newSymbols.extend(newSymbolEntry)
currentSymbolIndex += 1
pass
pass
elif (
sectType == S_MOD_INIT_FUNC_POINTERS
or sectType == S_MOD_TERM_FUNC_POINTERS
):
indirectStart = sect.reserved1
indirectEnd = sect.reserved1 + int(sect.size / 8)
for i in range(indirectStart, indirectEnd):
self._statusBar.update()
entryOffset = self._dysymtab.indirectsymoff + (i * 4)
entry = linkeditFile.readFormat("<I", entryOffset)[0]
if entry != 0:
continue
raise NotImplementedError
pass
elif sectType == S_16BYTE_LITERALS:
indirectStart = sect.reserved1
indirectEnd = sect.reserved1 + int(sect.size / 16)
for i in range(indirectStart, indirectEnd):
self._statusBar.update()
entryOffset = self._dysymtab.indirectsymoff + (i * 4)
entry = linkeditFile.readFormat("<I", entryOffset)[0]
if entry != 0:
continue
raise NotImplementedError
pass
elif sectType == S_DTRACE_DOF:
continue
elif (
sectType == S_LAZY_DYLIB_SYMBOL_POINTERS
or sectType == S_COALESCED
or sectType == S_GB_ZEROFILL
or sectType == S_INTERPOSING
):
raise NotImplementedError
pass
pass
self._statusBar.update()
# add the new data and update the load commands
linkeditFile.writeBytes(
self._symtab.symoff + (self._symtab.nsyms * nlist_64.SIZE),
newSymbols
)
linkeditFile.writeBytes(
self._symtab.stroff + self._symtab.strsize,
newStrings
)
newSymbolsCount = int(len(newSymbols) / nlist_64.SIZE)
newStringSize = len(newStrings)
self._symtab.nsyms += newSymbolsCount
self._symtab.strsize += newStringSize
self._dysymtab.nundefsym += newSymbolsCount
linkedit = self._machoCtx.segments[b"__LINKEDIT"].seg
linkedit.vmsize += newStringSize
linkedit.filesize += newStringSize
self._statusBar.update()
pass
pass
def fixStubs(extractionCtx: ExtractionContext) -> None:
extractionCtx.statusBar.update(unit="Stub Fixer")
try:
_StubFixer(extractionCtx).run()
except _StubFixerError as e:
extractionCtx.logger.error(f"Unable to fix stubs, reason: {e}")
pass
```
#### File: DyldExtractor/dyld/dyld_trie.py
```python
import dataclasses
from mmap import mmap
from DyldExtractor import leb128
from typing import Tuple, List
from DyldExtractor.macho.macho_constants import *
def _readString(file: mmap, readHead: int) -> Tuple[bytes, int]:
"""Read a null terminated string.
Returns:
The string including the new read head.
"""
nullIndex = file.find(b"\x00", readHead)
if nullIndex == -1:
return None
string = file[readHead:nullIndex + 1]
readHead += len(string)
return (string, readHead)
@dataclasses.dataclass
class ExportInfo(object):
address: int = 0
flags: int = 0
other: int = 0
name: bytes = None
importName: bytes = None
def loadData(self, file: mmap, offset: int) -> int:
self.flags, offset = leb128.decodeUleb128(file, offset)
if self.flags & EXPORT_SYMBOL_FLAGS_REEXPORT:
# dylib ordinal
self.other, offset = leb128.decodeUleb128(file, offset)
self.importName, offset = _readString(file, offset)
else:
self.address, offset = leb128.decodeUleb128(file, offset)
if self.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER:
self.other, offset = leb128.decodeUleb128(file, offset)
return offset
class ExportReaderError(Exception):
pass
class _ExportTrieReader(object):
exports: List[ExportInfo]
def __init__(
self,
file: mmap,
exportOff: int,
exportSize: int
) -> None:
super().__init__()
self.file = file
self.start = exportOff
self.end = exportOff + exportSize
self.exports = []
self.cumulativeString = bytearray()
self._processNode(self.start, 0)
pass
def _getCurrentString(self) -> bytes:
nullTermIndex = self.cumulativeString.index(b"\x00")
return self.cumulativeString[0:nullTermIndex + 1]
def _processNode(
self,
offset: int,
curStrOff: int
) -> None:
if offset >= self.end:
raise ExportReaderError("Node Offset extends beyond export end.")
terminalSize, offset = leb128.decodeUleb128(self.file, offset)
childrenOff = offset + terminalSize
if childrenOff >= self.end:
raise ExportReaderError("Children offset extend beyond export end.")
if terminalSize:
exportInfo = ExportInfo()
exportInfo.name = self._getCurrentString()
offset = exportInfo.loadData(self.file, offset)
self.exports.append(exportInfo)
# process the child nodes
childrenCount = self.file[childrenOff]
childrenOff += 1
for _ in range(childrenCount):
edgeString, childrenOff = _readString(self.file, childrenOff)
edgeStrLen = len(edgeString) - 1
self.cumulativeString[curStrOff:curStrOff + edgeStrLen] = edgeString
childNodeOff, childrenOff = leb128.decodeUleb128(self.file, childrenOff)
childNodeOff += self.start
self._processNode(childNodeOff, curStrOff + edgeStrLen)
pass
def ReadExports(
file: mmap,
exportOff: int,
exportSize: int
) -> List[ExportInfo]:
"""Read an export trie.
Args:
file: The source file to read from.
exportOff: The offset into the file to the export trie.
exportSize: The total size of the export trie.
Returns:
A list of ExportInfo
Raises:
ExportReaderError: If there was an error reading the export trie.
"""
reader = _ExportTrieReader(file, exportOff, exportSize)
return reader.exports
```
#### File: src/DyldExtractor/file_context.py
```python
import struct
import mmap
from typing import Any, BinaryIO
class FileContext:
def __init__(
self,
fileObject: BinaryIO,
copyMode: bool = False
) -> None:
self.fileObject = fileObject
self.file = mmap.mmap(
fileObject.fileno(),
0,
access=mmap.ACCESS_COPY if copyMode else mmap.ACCESS_READ
)
pass
def readString(self, offset: int) -> bytes:
"""Read a null terminated c-string.
Args:
offset: the file offset to the start of the string.
Returns:
The string in bytes, including the null terminater.
"""
nullIndex = self.file.find(b"\x00", offset)
if nullIndex == -1:
return None
return self.file[offset:nullIndex + 1]
def readFormat(self, format: str, offset: int) -> Any:
"""Read a formatted value at the offset.
Args:
offset: the file offset to read from.
format: the struct format to pass to struct.unpack.
Return:
The formated value.
"""
size = struct.calcsize(format)
return struct.unpack(format, self.file[offset:offset + size])
def getBytes(self, offset: int, length: int) -> bytes:
"""Retrieve data from the datasource.
Args:
offset: The location to start at.
length: How many bytes to read.
Return:
The data requested.
"""
return self.file[offset:offset + length]
def writeBytes(self, offset: int, data: bytes) -> None:
"""Writes the data at the offset.
Args:
offset: the file offset.
data: the data to write
"""
self.file.seek(offset)
self.file.write(data)
pass
def makeCopy(self, copyMode: bool = False) -> "FileContext":
return type(self)(self.fileObject, copyMode=copyMode)
```
#### File: DyldExtractor/tests/run_all_images_multiprocess.py
```python
import multiprocessing as mp
import signal
import logging
import io
import progressbar
import argparse
import pathlib
from typing import (
Tuple,
List,
BinaryIO
)
from DyldExtractor.file_context import FileContext
from DyldExtractor.macho.macho_context import MachOContext
from DyldExtractor.dyld.dyld_context import DyldContext
from DyldExtractor.extraction_context import ExtractionContext
from DyldExtractor.converter import (
linkedit_optimizer,
stub_fixer,
objc_fixer,
slide_info,
macho_offset
)
class _DyldExtractorArgs(argparse.Namespace):
dyld_path: pathlib.Path
jobs: int
pass
class _DummyProgressBar(object):
def update(*args, **kwargs):
pass
def _openSubCaches(
mainCachePath: str,
numSubCaches: int
) -> Tuple[List[FileContext], List[BinaryIO]]:
"""Create FileContext objects for each sub cache.
Assumes that each sub cache has the same base name as the
main cache, and that the suffixes are preserved.
Also opens the symbols cache, and adds it to the end of
the list.
Returns:
A list of subcaches, and their file objects, which must be closed!
"""
subCaches = []
subCachesFiles = []
subCacheSuffixes = [i for i in range(1, numSubCaches + 1)]
subCacheSuffixes.append("symbols")
for cacheSuffix in subCacheSuffixes:
subCachePath = f"{mainCachePath}.{cacheSuffix}"
cacheFileObject = open(subCachePath, mode="rb")
cacheFileCtx = FileContext(cacheFileObject)
subCaches.append(cacheFileCtx)
subCachesFiles.append(cacheFileObject)
pass
return subCaches, subCachesFiles
def _imageRunner(dyldPath: str, imageIndex: int) -> None:
level = logging.DEBUG
loggingStream = io.StringIO()
# setup logging
logger = logging.getLogger(f"Worker: {imageIndex}")
handler = logging.StreamHandler(loggingStream)
formatter = logging.Formatter(
fmt="{asctime}:{msecs:03.0f} [{levelname:^9}] {filename}:{lineno:d} : {message}", # noqa
datefmt="%H:%M:%S",
style="{",
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
# process the image
with open(dyldPath, "rb") as f:
dyldFileCtx = FileContext(f)
dyldCtx = DyldContext(dyldFileCtx)
subCacheFiles: List[BinaryIO] = []
try:
# add sub caches if there are any
if dyldCtx.hasSubCaches():
subCacheFileCtxs, subCacheFiles = _openSubCaches(
dyldPath,
dyldCtx.header.numSubCaches
)
dyldCtx.addSubCaches(subCacheFileCtxs)
pass
machoOffset, context = dyldCtx.convertAddr(
dyldCtx.images[imageIndex].address
)
machoCtx = MachOContext(
context.fileCtx.makeCopy(copyMode=True),
machoOffset
)
# Add sub caches if necessary
if dyldCtx.hasSubCaches():
mappings = dyldCtx.mappings
mainFileMap = next(
(mapping[0] for mapping in mappings if mapping[1] == context)
)
machoCtx.addSubfiles(
mainFileMap,
((m, ctx.fileCtx.makeCopy(copyMode=True)) for m, ctx in mappings)
)
pass
extractionCtx = ExtractionContext(
dyldCtx,
machoCtx,
_DummyProgressBar(),
logger
)
# TODO: implement a way to select convertors
slide_info.processSlideInfo(extractionCtx)
linkedit_optimizer.optimizeLinkedit(extractionCtx)
stub_fixer.fixStubs(extractionCtx)
objc_fixer.fixObjC(extractionCtx)
macho_offset.optimizeOffsets(extractionCtx)
except Exception as e:
logger.exception(e)
pass
finally:
for file in subCacheFiles:
file.close()
pass
pass
pass
# cleanup
handler.close()
return loggingStream.getvalue()
def _workerInitializer():
# ignore KeyboardInterrupt in workers
signal.signal(signal.SIGINT, signal.SIG_IGN)
pass
if "__main__" == __name__:
# Get arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"dyld_path",
type=pathlib.Path,
help="A path to the target DYLD cache."
)
parser.add_argument(
"-j", "--jobs", type=int, default=mp.cpu_count(),
help="Number of jobs to run simultaneously." # noqa
)
args = parser.parse_args(namespace=_DyldExtractorArgs)
# create a list of images
images: list[str] = []
with open(args.dyld_path, "rb") as f:
dyldFileCtx = FileContext(f)
dyldCtx = DyldContext(dyldFileCtx)
for index, image in enumerate(dyldCtx.images):
imagePath = dyldCtx.fileCtx.readString(image.pathFileOffset)[0:-1]
imagePath = imagePath.decode("utf-8")
imageName = imagePath.split("/")[-1]
images.append(imageName)
pass
summary = ""
with mp.Pool(args.jobs, initializer=_workerInitializer) as pool:
# create jobs for each image
jobs: list[tuple[str, mp.pool.AsyncResult]] = []
for index, imageName in enumerate(images):
jobs.append(
(imageName, pool.apply_async(_imageRunner, (args.dyld_path, index)))
)
pass
total = len(jobs)
jobsComplete = 0
# setup progress bar
statusBar = progressbar.ProgressBar(
max_value=total,
redirect_stdout=True
)
# wait for all the jobs to complete
while True:
if len(jobs) == 0:
break
for i in reversed(range(len(jobs))):
imageName, job = jobs[i]
if job.ready():
jobs.pop(i)
# update the status
jobsComplete += 1
statusBar.update(jobsComplete)
print(f"processed: {imageName}")
# print the result if any
result = job.get()
if len(result):
result = f"----- {imageName} -----\n{result}--------------------\n"
summary += result
print(result)
pass
# close the pool and cleanup
pool.close()
pool.join()
statusBar.update(jobsComplete)
pass
print("\n\n----- Summary -----")
print(summary)
print("-------------------\n\n")
pass
```
|
{
"source": "jelbrek/ghidra_kernelcache",
"score": 2
}
|
#### File: jelbrek/ghidra_kernelcache/load_structs.py
```python
from ghidra.app.services import DataTypeManagerService
from ghidra.program.model.data import StructureDataType,PointerDataType
from ghidra.app.services import ProgramManager
"""
- Get all structures from source program and copy them into destination program
- It avoids taking "_vtable" structures because fix_kernelcache will handle it
- If struct is already there, just skip it
"""
src_prog_string = "<source program>"
dst_prog_string = "<destination program>"
def isThere(name,programDT):
if "MetaClass" in name:
return True
if "_vtable" in name:
return True
dataType = programDT.getDataType(name)
if dataType :
return True
return False
if __name__ == "__main__":
tool = state.getTool()
service = tool.getService(DataTypeManagerService)
dataTypeManagers = service.getDataTypeManagers();
programManager = state.getTool().getService(ProgramManager)
progs =programManager.getAllOpenPrograms()
if len(progs) < 2 :
popup ("You must open at least two programs")
exit(1)
src = dst = None
for prog in progs:
if src_prog_string == prog.getName():
src = prog
elif dst_prog_string == prog.getName():
dst = prog
if src == None or dst == None:
popup("Could not get src/dst program")
exit(0)
print src,dst
src_dtm = src.getDataTypeManager()
dst_dtm = dst.getDataTypeManager()
structs = src_dtm.getAllStructures()
for s in structs:
name = s.getName()
res = isThere('/'+name,dst_dtm)
if res == True:
continue
res = isThere('/Demangler/'+name,dst_dtm)
if res == True:
continue
struct = StructureDataType(name,0)
dst_dtm.addDataType(struct,None)
dst_dtm.addDataType(PointerDataType(struct),None)
```
|
{
"source": "Jelby-John/HatalogicoWeatherStation",
"score": 3
}
|
#### File: Jelby-John/HatalogicoWeatherStation/main.py
```python
from Adafruit_PWM_Servo_Driver import PWM
from Adafruit_ADS1x15 import ADS1x15
import time, os, sys
import Adafruit_DHT
# HOW MANY CYCLES TO BE PERFORMED BEFORE SHOWING THE HIGH AND LOW SEQUENCE
# SET TO 0 FOR OFF
intervalHighLow = 60
# HOW LONG TO REST BETWEEN CYCLES - ZERO IS FINE
intervalSleep = 1
# HOW LONG TO DISPLAY THE HIGH AND LOW DISPLAYS
intervalDisplay = 5
# INTERVAL COUNTER/TRACKER. ALWAYS START AT 1
intervalCounter = 1
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHTsensor = Adafruit_DHT.DHT22
DHTpin = '22'
# SETUP THE PWMS
pwm = PWM(0x70)
pwm.setPWMFreq(100)
# SETUP THE ADCS
ADS1015 = 0x00
gain = 6144
sps = 100
adc = ADS1x15(address=0x49, ic=ADS1015)
# SET LEFT AND RIGHT POSITION FOR SERVOS
servoMin = 380
servoMax = 1150
# DEFINE SERVO PINS ON HATALOGICO PWMS
servoLight = 8
servoHumid = 10
servoTemp = 12
# DEFINE MAX AND MIN VALUES
tempMin = 40
tempMax = 15
humidMin = 100
humidMax = 0
lightMin = 1
lightMax = 2800
# DECLARE DEFAULT VALUES FOR HIGH AND LOW TRACKERS
tempHigh = 0
tempLow = 100
humidHigh = 0
humidLow = 100
lightHigh = 0
lightLow = 100
# LED PIN CONFIG ON HATALOGICO PWMS
brightRed = 3
brightGreen = 5
humidRed = 7
humidGreen = 9
tempRed = 11
tempGreen = 13
def showHighs():
# SCALE READINGS INTO OUTPUT VALUES
tempPercent = (tempHigh - tempMin) / (tempMax - tempMin)
tempOutput = int(tempPercent * (servoMax - servoMin) + servoMin)
lightPercent = (lightHigh - lightMin) / (lightMax - lightMin)
lightOutput = int(lightPercent * (servoMax - servoMin) + servoMin)
humidPercent = (humidHigh - humidMin) / (humidMax - humidMin)
humidOutput = int(humidPercent * (servoMax - servoMin) + servoMin)
pwm.setPWM(brightGreen, 0, 4095)
pwm.setPWM(brightRed, 0, 0)
pwm.setPWM(humidGreen, 0, 4095)
pwm.setPWM(humidRed, 0, 0)
pwm.setPWM(tempGreen, 0, 4095)
pwm.setPWM(tempRed, 0, 0)
pwm.setPWM(servoTemp, 0, tempOutput)
pwm.setPWM(servoHumid, 0, humidOutput)
pwm.setPWM(servoLight, 0, lightOutput)
time.sleep(intervalDisplay)
def showLows():
# SCALE READINGS INTO OUTPUT VALUES
tempPercent = (tempLow - tempMin) / (tempMax - tempMin)
tempOutput = int(tempPercent * (servoMax - servoMin) + servoMin)
lightPercent = (lightLow - lightMin) / (lightMax - lightMin)
lightOutput = int(lightPercent * (servoMax - servoMin) + servoMin)
humidPercent = (humidLow - humidMin) / (humidMax - humidMin)
humidOutput = int(humidPercent * (servoMax - servoMin) + servoMin)
pwm.setPWM(brightGreen, 0, 0)
pwm.setPWM(brightRed, 0, 4095)
pwm.setPWM(humidGreen, 0, 0)
pwm.setPWM(humidRed, 0, 4095)
pwm.setPWM(tempGreen, 0, 0)
pwm.setPWM(tempRed, 0, 4095)
pwm.setPWM(servoTemp, 0, tempOutput)
pwm.setPWM(servoHumid, 0, humidOutput)
pwm.setPWM(servoLight, 0, lightOutput)
time.sleep(intervalDisplay)
def lightsOff():
pwm.setPWM(brightRed, 0, 4095)
pwm.setPWM(humidRed, 0, 4095)
pwm.setPWM(tempRed, 0, 4095)
pwm.setPWM(brightGreen, 0, 4095)
pwm.setPWM(humidGreen, 0, 4095)
pwm.setPWM(tempGreen, 0, 4095)
def startup():
lightsOff()
# TURN ON RED LEDS FOR SERVO START-UP PROCEDURE
pwm.setPWM(brightRed, 0, 0)
pwm.setPWM(humidRed, 0, 0)
pwm.setPWM(tempRed, 0, 0)
time.sleep(3)
lightsOff()
pwm.setPWM(brightGreen, 0, 0)
pwm.setPWM(humidGreen, 0, 0)
pwm.setPWM(tempGreen, 0, 0)
time.sleep(5)
lightsOff()
startup()
while (True):
if(intervalCounter == intervalHighLow):
showHighs()
showLows()
lightsOff()
intervalCounter = 1
elif(intervalCounter < intervalHighLow):
intervalCounter += 1
# GET HUMIDITY AND TEMPERATURE READINGS FROM DHT22
humidity, temperature = Adafruit_DHT.read_retry(DHTsensor, DHTpin)
ldrValue = adc.readADCSingleEnded(0, gain, sps)
lightValue = (ldrValue - lightMin) / (lightMax - lightMin) * 100
# SCALE READINGS INTO OUTPUT VALUES
tempPercent = (temperature - tempMin) / (tempMax - tempMin)
tempOutput = int(tempPercent * (servoMax - servoMin) + servoMin)
humidPercent = (humidity - humidMin) / (humidMax - humidMin)
humidOutput = int(humidPercent * (servoMax - servoMin) + servoMin)
lightPercent = lightValue / 100
lightOutput = int(lightPercent * (servoMax - servoMin) + servoMin)
# CHECK FOR HIGH AND LOW VALUES
# HUMIDITY
if(humidity > humidHigh):
humidHigh = humidity
if(humidity < humidLow):
humidLow = humidity
# TEMPERATURE
if(temperature > tempHigh):
tempHigh = temperature
if(temperature < tempLow):
tempLow = temperature
# BRIGHTNESS
if(lightValue > lightHigh):
lightHigh = lightValue
if(lightValue < lightLow):
lightLow = lightValue
os.system('clear')
print "----- INPUTS ------"
print "Temperature: %d" % temperature
print "Humidity: %d" % humidity
print "Brightness: %d" % lightValue
print "----- OUTPUTS -----"
print "Temperature: %d" % tempOutput
print "Humidity: %d" % humidOutput
print "Brightness: %d" % lightOutput
print "----- HISTORY -----"
print " | Temperature | Humidity | Brightness "
print "High: | %.1f" % tempHigh + " degC | %.1f" % humidHigh + " %% | %.1f" % lightHigh + " %"
print "Low: | %.1f" % tempLow + " degC | %.1f" % humidLow + " %% | %.1f" % lightLow + " %"
print "------------------------------"
pwm.setPWM(servoTemp, 0, tempOutput)
pwm.setPWM(servoHumid, 0, humidOutput)
pwm.setPWM(servoLight, 0, lightOutput)
time.sleep(intervalSleep)
```
|
{
"source": "jeleandro/PANAA2018",
"score": 2
}
|
#### File: PANAA2018/Article2019/sklearnExtensions.py
```python
import numpy as np;
from sklearn.base import BaseEstimator, TransformerMixin
from scipy.sparse import issparse
class SumarizeTransformer(BaseEstimator):
def __init__(self, agg = None):
self.agg = agg
def transform(self, X, y=None):
if self.agg == 'min':
return X.min(axis=1,keepdims=True);
if self.agg == 'max':
return X.max(axis=1,keepdims=True);
if self.agg == 'mean':
return X.mean(axis=1,keepdims=True);
if self.agg is not None:
return self.agg(X);
return X;
def fit(self, X, y=None):
return self
def fit_transform(self, X, y=None):
return self.transform(X=X, y=y)
def fit_predict(self,X,y=None):
return self.transform(X=X, y=y);
def predict(self,X,y=None):
return self.transform(X=X, y=y)
from sklearn.base import ClusterMixin, BaseEstimator
from sklearn.utils.validation import check_random_state
class DistanceNoveltyClassifier(BaseEstimator,ClusterMixin):
def __init__(self,classes, clip=(1,99), random_state=None):
self.random_state = random_state;
self.classes = classes;
self.clip =clip
def _buildProfile(self,X,y):
#building the profile matrix
profiles_ = np.zeros((len(self.classes), X.shape[1]),dtype=np.float32);
for i,p in enumerate(self.classes):
profiles_[i,] += np.array(X[y==p,].sum(axis=0)).flatten();
self.profiles_ = profiles_;
def fit(self,X,y):
y = np.array(y)
self._buildProfile(X,y);
#building the distance matrix
self.metrics_ = ['cosine',fuzzyyulef];
distances =np.hstack([
pairwise_distances(X,self.profiles_,metric=d).min(axis=1).reshape(-1,1)
for d in self.metrics_
])
inSet = np.array([1 if yi in self.classes else 0 for yi in y]);
#downsampling because the out of classes is larger
distances,inSet = upsampling(distances,inSet);
self.clf_ = Pipeline([
('clip' ,ClipTransformer(a_min=self.clip[0],a_max=self.clip[1])),
('transf',preprocessing.MaxAbsScaler()),
('clf' ,linear_model.LogisticRegression(C=1,random_state=self.random_state,class_weight='balanced'))
]);
self.clf_.fit(distances,inSet);
return self;
def predict(self,X):
distances =np.hstack([
pairwise_distances(X,self.profiles_,metric=d).min(axis=1).reshape(-1,1)
for d in self.metrics_
])
return self.clf_.predict(distances);
def predict_proba(self,X):
distances =np.hstack([
pairwise_distances(X,self.profiles_,metric=d).min(axis=1).reshape(-1,1)
for d in self.metrics_
])
return self.clf_.predict_proba(distances);
def fit_predict(self,X,y):
self.fit(X,y);
return self.predict(X);
from sklearn.base import ClusterMixin, BaseEstimator
from sklearn.utils.validation import check_random_state
class OneClassClassifier(BaseEstimator):
def __init__(self,n_estimators=10,noise_proportion=0.1, random_state=None):
self.n_estimators=n_estimators;
self.noise_proportion=noise_proportion;
self.random_state = random_state;
def fit(self,X,y=None):
random_state = check_random_state(self.random_state);
self.estimators = [];
l = X.shape[0] or len(X);
y = np.ones(int(l*self.noise_proportion));
y = np.hstack([y,np.zeros(l-len(y))]);
for _ in range(self.n_estimators):
est = linear_model.LogisticRegression(C=0.01,random_state=self.random_state);
random_state.shuffle(y);
est.fit(X,y);
self.estimators.append(est);
return self;
def predict(self,X):
pred = np.vstack([
p.predict(X)[:,1] for p in self.estimators
]);
return pred.sum(axis=0);
def predict_proba(self,X):
pred = np.vstack([
p.predict_proba(X)[:,1] for p in self.estimators
]);
return pred.sum(axis=0);
def fit_predict(self,X):
self.fit(X);
return self.predict(X);
class ClipTransformer(BaseEstimator):
def __init__(self, a_min=1,a_max=99):
self.a_min = a_min
self.a_max = a_max
self.axis=1
def transform(self, X, y=None):
X = X.copy();
for i in range(X.shape[self.axis]):
X[:,i] = np.clip(X[:,i],self.min_[i],self.max_[i]);
return X;
def fit(self, X, y=None):
self.min_ = np.zeros(X.shape[self.axis]);
self.max_ = np.zeros(X.shape[self.axis]);
for i in range(X.shape[self.axis]):
self.min_[i], self.max_[i] = np.percentile(X[:,i],q=(self.a_min, self.a_max))
return self
def fit_transform(self, X, y=None):
self.fit(X);
return self.transform(X=X, y=y)
class DenseTransformer(BaseEstimator):
"""Convert a sparse array into a dense array."""
def __init__(self, return_copy=True):
self.return_copy = return_copy
self.is_fitted = False
def transform(self, X, y=None):
""" Return a dense version of the input array.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] (default: None)
Returns
---------
X_dense : dense version of the input X array.
"""
if issparse(X):
return X.toarray()
elif self.return_copy:
return X.copy()
else:
return X
def fit(self, X, y=None):
self.is_fitted = True
return self
def fit_transform(self, X, y=None):
""" Return a dense version of the input array.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] (default: None)
Returns
---------
X_dense : dense version of the input X array.
"""
return self.transform(X=X, y=y)
```
|
{
"source": "JelenaBanjac/microbiome-toolbox",
"score": 2
}
|
#### File: pages/home/home_data.py
```python
import dill
# @cache.memoize()
def get_dataset(dataset_path):
with open(dataset_path, "rb") as f:
dataset = dill.load(f)
return dataset
def set_dataset(dataset, path):
# path_dir = pathlib.Path(UPLOAD_FOLDER_ROOT) / session_id
# path_dir.mkdir(parents=True, exist_ok=True)
# path = path_dir / f"{button_id}-dataset.pickle"
with open(path, "wb") as f:
dill.dump(dataset, f)
return path
# @cache.memoize()
def get_trajectory(trajectory_path):
with open(trajectory_path, "rb") as f:
dataset = dill.load(f)
return dataset
def set_trajectory(trajectory, path):
# path_dir = pathlib.Path(UPLOAD_FOLDER_ROOT) / session_id
# path_dir.mkdir(parents=True, exist_ok=True)
# path = path_dir / f"{button_id}-trajectory.pickle"
with open(path, "wb") as f:
dill.dump(trajectory, f)
return path
```
#### File: pages/page1/page1_callbacks.py
```python
from dash_extensions.enrich import Output, Input
from app import app
from pages.home.home_data import get_dataset
from dash import dcc
from dash import html as dhc
import dash_bootstrap_components as dbc
import traceback
@app.callback(
Output("page-1-display-value-1", "children"),
Input("microbiome-dataset-location", "data"),
Input("button-refresh-reference-statistics", "n_clicks"),
)
def display_value(dataset_path, n_clicks):
results = []
if dataset_path:
try:
dataset = get_dataset(dataset_path)
if dataset.reference_group_plot is None:
results = [
dcc.Markdown("Reference groups have not been defined yet."),
]
else:
img_src = dataset.reference_group_img_src
acccuracy = dataset.reference_group_accuracy
f1score = dataset.reference_group_f1score
img_src.update_layout(height=400, width=400)
confusion_matrix = dcc.Graph(figure=img_src)
results = [
dcc.Graph(
figure=dataset.reference_group_plot,
config=dataset.reference_group_config,
),
dhc.Br(),
dbc.Container(
dbc.Row(
[
dbc.Col(
[
dhc.Br(),
dhc.Br(),
dcc.Markdown(
f"Reference groups differentiation can be seen below."
),
dcc.Markdown(
"The ideal separation between two groups (reference vs. non-reference) will have 100% of values detected on the second diagonal. This would mean that the two groups can be easily separated knowing their taxa abundamces and metadata information."
),
dcc.Markdown(f"Accuracy: {acccuracy*100:.2f}"),
dcc.Markdown(f"F1-score: {f1score:.2f}"),
]
),
dbc.Col(confusion_matrix),
]
)
),
dhc.Br(),
]
except Exception as e:
results = dbc.Alert(
children=[
dcc.Markdown("Microbiome trajectory error: " + str(e)),
dcc.Markdown(traceback.format_exc()),
dcc.Markdown("Open an [issue on GitHub](https://github.com/JelenaBanjac/microbiome-toolbox/issues) or send an [email](<EMAIL>)."),
],
color="danger",
)
return results
```
#### File: microbiome-toolbox/webapp/routes.py
```python
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
# from dash import html as dhc
from dash import html as dhc
from app import app
from utils.constants import (
home_location,
page1_location,
page2_location,
page3_location,
page4_location,
page5_location,
page6_location,
)
@app.callback(
Output("home-layout", "hidden"),
Output("page-1-layout", "hidden"),
Output("page-2-layout", "hidden"),
Output("page-3-layout", "hidden"),
Output("page-4-layout", "hidden"),
Output("page-5-layout", "hidden"),
Output("page-6-layout", "hidden"),
Output("page-not-found", "children"),
[Input("url", "pathname")],
)
def render_page_content(pathname):
print(pathname)
if pathname == home_location:
return False, True, True, True, True, True, True, ""
elif pathname == page1_location:
return True, False, True, True, True, True, True, ""
elif pathname == page2_location:
return True, True, False, True, True, True, True, ""
elif pathname == page3_location:
return True, True, True, False, True, True, True, ""
elif pathname == page4_location:
return True, True, True, True, False, True, True, ""
elif pathname == page5_location:
return True, True, True, True, True, False, True, ""
elif pathname == page6_location:
return True, True, True, True, True, True, False, ""
# If the user tries to reach a different page, return a 404 message
return (
True,
True,
True,
True,
True,
True,
True,
dbc.Jumbotron(
[
dhc.H1("404: Not found", className="text-danger"),
dhc.Hr(),
dhc.P(f"The pathname {pathname} was not recognized..."),
]
),
)
```
|
{
"source": "JelenaBanjac/PyLSR",
"score": 2
}
|
#### File: PyLSR/tests/test_main.py
```python
from __future__ import annotations
import sys
from pathlib import Path
from imgcompare import imgcompare
from PIL import Image
THISDIR = str(Path(__file__).resolve().parent)
sys.path.insert(0, str(Path(THISDIR).parent))
THISDIR = str(Path(__file__).resolve().parent)
sys.path.insert(0, str(Path(THISDIR).parent))
import pylsr
def test_1():
pylsr.write(f"{THISDIR}/data/test1copy.lsr", pylsr.read(f"{THISDIR}/data/test1.lsr"))
output = f"{THISDIR}/data/test1.png"
expected = f"{THISDIR}/data/test1_expected.png"
pylsr.read(f"{THISDIR}/data/test1.lsr").flatten().save(output)
assert imgcompare.is_equal(
output,
expected,
tolerance=0.2,
)
output = f"{THISDIR}/data/test1copy.png"
pylsr.read(f"{THISDIR}/data/test1copy.lsr").flatten().save(output)
assert imgcompare.is_equal(
output,
expected,
tolerance=0.2,
)
# Copy an image
def test_3():
pylsr.write(f"{THISDIR}/data/test3copy.lsr", pylsr.read(f"{THISDIR}/data/test3.lsr"))
output = f"{THISDIR}/data/test3.png"
expected = f"{THISDIR}/data/test3_expected.png"
pylsr.read(f"{THISDIR}/data/test3.lsr").flatten().save(output)
assert imgcompare.is_equal(
output,
expected,
tolerance=0.2,
)
output = f"{THISDIR}/data/test3copy.png"
pylsr.read(f"{THISDIR}/data/test3copy.lsr").flatten().save(output)
assert imgcompare.is_equal(
output,
expected,
tolerance=0.2,
)
if __name__ == "__main__":
test_1()
test_3()
```
|
{
"source": "jelena-markovic/botorch",
"score": 2
}
|
#### File: test/models/test_pairwise_gp.py
```python
import itertools
import warnings
import torch
from botorch import fit_gpytorch_model
from botorch.exceptions.warnings import OptimizationWarning
from botorch.models.pairwise_gp import PairwiseGP, PairwiseLaplaceMarginalLogLikelihood
from botorch.posteriors import GPyTorchPosterior
from botorch.sampling.pairwise_samplers import PairwiseSobolQMCNormalSampler
from botorch.utils.testing import BotorchTestCase
from gpytorch.kernels import RBFKernel, ScaleKernel
from gpytorch.kernels.linear_kernel import LinearKernel
from gpytorch.means import ConstantMean
from gpytorch.priors import GammaPrior, SmoothedBoxPrior
class TestPairwiseGP(BotorchTestCase):
def _make_rand_mini_data(self, batch_shape, X_dim=2, **tkwargs):
train_X = torch.rand(*batch_shape, 2, X_dim, **tkwargs)
train_Y = train_X.sum(dim=-1, keepdim=True)
train_comp = torch.topk(train_Y, k=2, dim=-2).indices.transpose(-1, -2)
return train_X, train_Y, train_comp
def _get_model_and_data(self, batch_shape, X_dim=2, **tkwargs):
train_X, train_Y, train_comp = self._make_rand_mini_data(
batch_shape=batch_shape, X_dim=X_dim, **tkwargs
)
model_kwargs = {"datapoints": train_X, "comparisons": train_comp}
model = PairwiseGP(**model_kwargs)
return model, model_kwargs
def test_pairwise_gp(self):
for batch_shape, dtype in itertools.product(
(torch.Size(), torch.Size([2])), (torch.float, torch.double)
):
tkwargs = {"device": self.device, "dtype": dtype}
X_dim = 2
model, model_kwargs = self._get_model_and_data(
batch_shape=batch_shape, X_dim=X_dim, **tkwargs
)
train_X = model_kwargs["datapoints"]
train_comp = model_kwargs["comparisons"]
# test training
# regular training
mll = PairwiseLaplaceMarginalLogLikelihood(model).to(**tkwargs)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=OptimizationWarning)
fit_gpytorch_model(mll, options={"maxiter": 2}, max_retries=1)
# prior training
prior_m = PairwiseGP(None, None)
with self.assertRaises(RuntimeError):
prior_m(train_X)
# forward in training mode with non-training data
custom_m = PairwiseGP(**model_kwargs)
other_X = torch.rand(batch_shape + torch.Size([3, X_dim]), **tkwargs)
other_comp = train_comp.clone()
with self.assertRaises(RuntimeError):
custom_m(other_X)
custom_mll = PairwiseLaplaceMarginalLogLikelihood(custom_m).to(**tkwargs)
post = custom_m(train_X)
with self.assertRaises(RuntimeError):
custom_mll(post, other_comp)
# setting jitter = 0 with a singular covar will raise error
sing_train_X = torch.ones(batch_shape + torch.Size([10, X_dim]), **tkwargs)
with self.assertRaises(RuntimeError):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RuntimeWarning)
custom_m = PairwiseGP(sing_train_X, train_comp, jitter=0)
custom_m.posterior(sing_train_X)
# test init
self.assertIsInstance(model.mean_module, ConstantMean)
self.assertIsInstance(model.covar_module, ScaleKernel)
self.assertIsInstance(model.covar_module.base_kernel, RBFKernel)
self.assertIsInstance(
model.covar_module.base_kernel.lengthscale_prior, GammaPrior
)
self.assertIsInstance(
model.covar_module.outputscale_prior, SmoothedBoxPrior
)
self.assertEqual(model.num_outputs, 1)
# test custom models
custom_m = PairwiseGP(**model_kwargs, covar_module=LinearKernel())
self.assertIsInstance(custom_m.covar_module, LinearKernel)
# prior prediction
prior_m = PairwiseGP(None, None)
prior_m.eval()
post = prior_m.posterior(train_X)
self.assertIsInstance(post, GPyTorchPosterior)
# test trying adding jitter
pd_mat = torch.eye(2, 2)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RuntimeWarning)
jittered_pd_mat = model._add_jitter(pd_mat)
diag_diff = (jittered_pd_mat - pd_mat).diagonal(dim1=-2, dim2=-1)
self.assertTrue(
torch.allclose(
diag_diff,
torch.full_like(diag_diff, model._jitter),
atol=model._jitter / 10,
)
)
# test initial utility val
util_comp = torch.topk(model.utility, k=2, dim=-1).indices.unsqueeze(-2)
self.assertTrue(torch.all(util_comp == train_comp))
# test posterior
# test non batch evaluation
X = torch.rand(batch_shape + torch.Size([3, X_dim]), **tkwargs)
expected_shape = batch_shape + torch.Size([3, 1])
posterior = model.posterior(X)
self.assertIsInstance(posterior, GPyTorchPosterior)
self.assertEqual(posterior.mean.shape, expected_shape)
self.assertEqual(posterior.variance.shape, expected_shape)
# expect to raise error when output_indices is not None
with self.assertRaises(RuntimeError):
model.posterior(X, output_indices=[0])
# test re-evaluating utility when it's None
model.utility = None
posterior = model.posterior(X)
self.assertIsInstance(posterior, GPyTorchPosterior)
# test batch evaluation
X = torch.rand(2, *batch_shape, 3, X_dim, **tkwargs)
expected_shape = torch.Size([2]) + batch_shape + torch.Size([3, 1])
posterior = model.posterior(X)
self.assertIsInstance(posterior, GPyTorchPosterior)
self.assertEqual(posterior.mean.shape, expected_shape)
def test_condition_on_observations(self):
for batch_shape, dtype in itertools.product(
(torch.Size(), torch.Size([2])), (torch.float, torch.double)
):
tkwargs = {"device": self.device, "dtype": dtype}
X_dim = 2
model, model_kwargs = self._get_model_and_data(
batch_shape=batch_shape, X_dim=X_dim, **tkwargs
)
train_X = model_kwargs["datapoints"]
train_comp = model_kwargs["comparisons"]
# evaluate model
model.posterior(torch.rand(torch.Size([4, X_dim]), **tkwargs))
# test condition_on_observations
# test condition_on_observations with prior mode
prior_m = PairwiseGP(None, None)
cond_m = prior_m.condition_on_observations(train_X, train_comp)
self.assertTrue(cond_m.datapoints is train_X)
self.assertTrue(cond_m.comparisons is train_comp)
# fantasize at different input points
fant_shape = torch.Size([2])
X_fant, Y_fant, comp_fant = self._make_rand_mini_data(
batch_shape=fant_shape + batch_shape, X_dim=X_dim, **tkwargs
)
# cannot condition on non-pairwise Ys
with self.assertRaises(RuntimeError):
model.condition_on_observations(X_fant, comp_fant[..., 0])
cm = model.condition_on_observations(X_fant, comp_fant)
# make sure it's a deep copy
self.assertTrue(model is not cm)
# fantasize at same input points (check proper broadcasting)
cm_same_inputs = model.condition_on_observations(X_fant[0], comp_fant)
test_Xs = [
# test broadcasting single input across fantasy and model batches
torch.rand(4, X_dim, **tkwargs),
# separate input for each model batch and broadcast across
# fantasy batches
torch.rand(batch_shape + torch.Size([4, X_dim]), **tkwargs),
# separate input for each model and fantasy batch
torch.rand(
fant_shape + batch_shape + torch.Size([4, X_dim]), **tkwargs
),
]
for test_X in test_Xs:
posterior = cm.posterior(test_X)
self.assertEqual(
posterior.mean.shape, fant_shape + batch_shape + torch.Size([4, 1])
)
posterior_same_inputs = cm_same_inputs.posterior(test_X)
self.assertEqual(
posterior_same_inputs.mean.shape,
fant_shape + batch_shape + torch.Size([4, 1]),
)
# check that fantasies of batched model are correct
if len(batch_shape) > 0 and test_X.dim() == 2:
state_dict_non_batch = {
key: (val[0] if val.numel() > 1 else val)
for key, val in model.state_dict().items()
}
model_kwargs_non_batch = {
"datapoints": model_kwargs["datapoints"][0],
"comparisons": model_kwargs["comparisons"][0],
}
model_non_batch = model.__class__(**model_kwargs_non_batch)
model_non_batch.load_state_dict(state_dict_non_batch)
model_non_batch.eval()
model_non_batch.posterior(
torch.rand(torch.Size([4, X_dim]), **tkwargs)
)
cm_non_batch = model_non_batch.condition_on_observations(
X_fant[0][0], comp_fant[:, 0, :]
)
non_batch_posterior = cm_non_batch.posterior(test_X)
self.assertTrue(
torch.allclose(
posterior_same_inputs.mean[:, 0, ...],
non_batch_posterior.mean,
atol=1e-3,
)
)
self.assertTrue(
torch.allclose(
posterior_same_inputs.mvn.covariance_matrix[:, 0, :, :],
non_batch_posterior.mvn.covariance_matrix,
atol=1e-3,
)
)
def test_fantasize(self):
for batch_shape, dtype in itertools.product(
(torch.Size(), torch.Size([2])), (torch.float, torch.double)
):
tkwargs = {"device": self.device, "dtype": dtype}
X_dim = 2
model, model_kwargs = self._get_model_and_data(
batch_shape=batch_shape, X_dim=X_dim, **tkwargs
)
# fantasize
X_f = torch.rand(
torch.Size(batch_shape + torch.Size([4, X_dim])), **tkwargs
)
sampler = PairwiseSobolQMCNormalSampler(num_samples=3)
fm = model.fantasize(X=X_f, sampler=sampler)
self.assertIsInstance(fm, model.__class__)
fm = model.fantasize(X=X_f, sampler=sampler, observation_noise=False)
self.assertIsInstance(fm, model.__class__)
```
|
{
"source": "jelena-markovic/compare-selection",
"score": 2
}
|
#### File: jelena-markovic/compare-selection/gaussian_methods.py
```python
import tempfile, os, glob
from scipy.stats import norm as ndist
from traitlets import (HasTraits,
Integer,
Unicode,
Float,
Integer,
Instance,
Dict,
Bool,
default)
import numpy as np
import regreg.api as rr
from selection.algorithms.lasso import lasso, lasso_full, lasso_full_modelQ
from selection.algorithms.sqrt_lasso import choose_lambda
from selection.truncated.gaussian import truncated_gaussian_old as TG
from selection.randomized.lasso import lasso as random_lasso_method, form_targets
from selection.randomized.modelQ import modelQ as randomized_modelQ
from utils import BHfilter
from selection.randomized.base import restricted_estimator
# Rpy
import rpy2.robjects as rpy
from rpy2.robjects import numpy2ri
methods = {}
class generic_method(HasTraits):
need_CV = False
selectiveR_method = False
wide_ok = True # ok for p>= n?
# Traits
q = Float(0.2)
method_name = Unicode('Generic method')
model_target = Unicode()
@classmethod
def setup(cls, feature_cov):
cls.feature_cov = feature_cov
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
(self.X,
self.Y,
self.l_theory,
self.l_min,
self.l_1se,
self.sigma_reid) = (X,
Y,
l_theory,
l_min,
l_1se,
sigma_reid)
def select(self):
raise NotImplementedError('abstract method')
@classmethod
def register(cls):
methods[cls.__name__] = cls
def selected_target(self, active, beta):
C = self.feature_cov[active]
Q = C[:,active]
return np.linalg.inv(Q).dot(C.dot(beta))
def full_target(self, active, beta):
return beta[active]
def get_target(self, active, beta):
if self.model_target not in ['selected', 'full']:
raise ValueError('Gaussian methods only have selected or full targets')
if self.model_target == 'full':
return self.full_target(active, beta)
else:
return self.selected_target(active, beta)
# Knockoff selection
class knockoffs_mf(generic_method):
method_name = Unicode('Knockoffs')
knockoff_method = Unicode('Second order')
model_target = Unicode("full")
def select(self):
try:
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('Y', self.Y)
rpy.r.assign('q', self.q)
rpy.r('V=knockoff.filter(X, Y, fdr=q)$selected')
rpy.r('if (length(V) > 0) {V = V-1}')
V = rpy.r('V')
numpy2ri.deactivate()
return np.asarray(V, np.int), np.asarray(V, np.int)
except:
return [], []
knockoffs_mf.register()
class knockoffs_sigma(generic_method):
factor_method = 'asdp'
method_name = Unicode('Knockoffs')
knockoff_method = Unicode("ModelX (asdp)")
model_target = Unicode("full")
@classmethod
def setup(cls, feature_cov):
cls.feature_cov = feature_cov
numpy2ri.activate()
# see if we've factored this before
have_factorization = False
if not os.path.exists('.knockoff_factorizations'):
os.mkdir('.knockoff_factorizations')
factors = glob.glob('.knockoff_factorizations/*npz')
for factor_file in factors:
factor = np.load(factor_file)
feature_cov_f = factor['feature_cov']
if ((feature_cov_f.shape == feature_cov.shape) and
(factor['method'] == cls.factor_method) and
np.allclose(feature_cov_f, feature_cov)):
have_factorization = True
print('found factorization: %s' % factor_file)
cls.knockoff_chol = factor['knockoff_chol']
if not have_factorization:
print('doing factorization')
cls.knockoff_chol = factor_knockoffs(feature_cov, cls.factor_method)
numpy2ri.deactivate()
def select(self):
numpy2ri.activate()
rpy.r.assign('chol_k', self.knockoff_chol)
rpy.r('''
knockoffs = function(X) {
mu = rep(0, ncol(X))
mu_k = X # sweep(X, 2, mu, "-") %*% SigmaInv_s
X_k = mu_k + matrix(rnorm(ncol(X) * nrow(X)), nrow(X)) %*%
chol_k
return(X_k)
}
''')
numpy2ri.deactivate()
try:
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('Y', self.Y)
rpy.r.assign('q', self.q)
rpy.r('V=knockoff.filter(X, Y, fdr=q, knockoffs=knockoffs)$selected')
rpy.r('if (length(V) > 0) {V = V-1}')
V = rpy.r('V')
numpy2ri.deactivate()
return np.asarray(V, np.int), np.asarray(V, np.int)
except:
return [], []
knockoffs_sigma.register()
def factor_knockoffs(feature_cov, method='asdp'):
numpy2ri.activate()
rpy.r.assign('Sigma', feature_cov)
rpy.r.assign('method', method)
rpy.r('''
# Compute the Cholesky -- from create.gaussian
diag_s = diag(switch(method, equi = create.solve_equi(Sigma),
sdp = create.solve_sdp(Sigma), asdp = create.solve_asdp(Sigma)))
if (is.null(dim(diag_s))) {
diag_s = diag(diag_s, length(diag_s))
}
SigmaInv_s = solve(Sigma, diag_s)
Sigma_k = 2 * diag_s - diag_s %*% SigmaInv_s
chol_k = chol(Sigma_k)
''')
knockoff_chol = np.asarray(rpy.r('chol_k'))
SigmaInv_s = np.asarray(rpy.r('SigmaInv_s'))
diag_s = np.asarray(rpy.r('diag_s'))
np.savez('.knockoff_factorizations/%s.npz' % (os.path.split(tempfile.mkstemp()[1])[1],),
method=method,
feature_cov=feature_cov,
knockoff_chol=knockoff_chol)
return knockoff_chol
class knockoffs_sigma_equi(knockoffs_sigma):
knockoff_method = Unicode('ModelX (equi)')
factor_method = 'equi'
knockoffs_sigma_equi.register()
class knockoffs_orig(generic_method):
wide_OK = False # requires at least n>p
method_name = Unicode("Knockoffs")
knockoff_method = Unicode('Candes & Barber')
model_target = Unicode('full')
def select(self):
try:
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('Y', self.Y)
rpy.r.assign('q', self.q)
rpy.r('V=knockoff.filter(X, Y, statistic=stat.glmnet_lambdadiff, fdr=q, knockoffs=create.fixed)$selected')
rpy.r('if (length(V) > 0) {V = V-1}')
V = rpy.r('V')
numpy2ri.deactivate()
V = np.asarray(V, np.int)
return V, V
except:
return [], []
knockoffs_orig.register()
class knockoffs_fixed(generic_method):
wide_OK = False # requires at least n>p
method_name = Unicode("Knockoffs")
knockoff_method = Unicode('Fixed')
model_target = Unicode('full')
def select(self):
try:
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('Y', self.Y)
rpy.r.assign('q', self.q)
rpy.r('V=knockoff.filter(X, Y, fdr=q, knockoffs=create.fixed)$selected')
rpy.r('if (length(V) > 0) {V = V-1}')
V = rpy.r('V')
numpy2ri.deactivate()
return np.asarray(V, np.int), np.asarray(V, np.int)
except:
return [], []
knockoffs_fixed.register()
# Liu, Markovic, Tibs selection
class parametric_method(generic_method):
confidence = Float(0.95)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
generic_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self._fit = False
def select(self):
if not self._fit:
self.method_instance.fit()
self._fit = True
active_set, pvalues = self.generate_pvalues()
if len(pvalues) > 0:
selected = [active_set[i] for i in BHfilter(pvalues, q=self.q)]
return selected, active_set
else:
return [], active_set
class liu_theory(parametric_method):
sigma_estimator = Unicode('relaxed')
method_name = Unicode("Liu")
lambda_choice = Unicode("theory")
model_target = Unicode("full")
dispersion = Float(0.)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
parametric_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
n, p = X.shape
if n < p:
self.method_name = 'ROSI'
self.lagrange = l_theory * np.ones(X.shape[1])
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso_full.gaussian(self.X, self.Y, self.lagrange * np.sqrt(n))
return self._method_instance
def generate_summary(self, compute_intervals=False):
if not self._fit:
self.method_instance.fit()
self._fit = True
X, Y, lagrange, L = self.X, self.Y, self.lagrange, self.method_instance
n, p = X.shape
if len(L.active) > 0:
if self.sigma_estimator == 'reid' and n < p:
dispersion = self.sigma_reid**2
elif self.dispersion != 0:
dispersion = self.dispersion
else:
dispersion = None
S = L.summary(compute_intervals=compute_intervals, dispersion=dispersion)
return S
def generate_pvalues(self):
S = self.generate_summary(compute_intervals=False)
if S is not None:
active_set = np.array(S['variable'])
pvalues = np.asarray(S['pval'])
return active_set, pvalues
else:
return [], []
def generate_intervals(self):
S = self.generate_summary(compute_intervals=True)
if S is not None:
active_set = np.array(S['variable'])
lower, upper = np.asarray(S['lower_confidence']), np.asarray(S['upper_confidence'])
return active_set, lower, upper
else:
return [], [], []
liu_theory.register()
class liu_aggressive(liu_theory):
lambda_choice = Unicode("aggressive")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
liu_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
liu_aggressive.register()
class liu_modelQ_pop_aggressive(liu_aggressive):
method_name = Unicode("Liu (ModelQ population)")
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso_full_modelQ(self.feature_cov * n, self.X, self.Y, self.lagrange * np.sqrt(n))
return self._method_instance
liu_modelQ_pop_aggressive.register()
class liu_modelQ_semi_aggressive(liu_aggressive):
method_name = Unicode("Liu (ModelQ semi-supervised)")
B = 10000 # how many samples to use to estimate E[XX^T]
@classmethod
def setup(cls, feature_cov):
cls.feature_cov = feature_cov
cls._chol = np.linalg.cholesky(feature_cov)
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
# draw sample of X for semi-supervised method
_chol = self._chol
p = _chol.shape[0]
Q = 0
batch_size = int(self.B/10)
for _ in range(10):
X_semi = np.random.standard_normal((batch_size, p)).dot(_chol.T)
Q += X_semi.T.dot(X_semi)
Q += self.X.T.dot(self.X)
Q /= (10 * batch_size + self.X.shape[0])
n, p = self.X.shape
self._method_instance = lasso_full_modelQ(Q * self.X.shape[0], self.X, self.Y, self.lagrange * np.sqrt(n))
return self._method_instance
liu_modelQ_semi_aggressive.register()
class liu_sparseinv_aggressive(liu_aggressive):
method_name = Unicode("ROSI")
"""
Force the use of the debiasing matrix.
"""
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso_full.gaussian(self.X, self.Y, self.lagrange * np.sqrt(n))
self._method_instance.sparse_inverse = True
return self._method_instance
liu_sparseinv_aggressive.register()
class liu_aggressive_reid(liu_aggressive):
sigma_estimator = Unicode('Reid')
pass
liu_aggressive_reid.register()
class liu_CV(liu_theory):
need_CV = True
lambda_choice = Unicode("CV")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
liu_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_min * np.ones(X.shape[1])
liu_CV.register()
class liu_1se(liu_theory):
need_CV = True
lambda_choice = Unicode("1se")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
liu_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_1se * np.ones(X.shape[1])
liu_1se.register()
class liu_sparseinv_1se(liu_1se):
method_name = Unicode("ROSI")
"""
Force the use of the debiasing matrix.
"""
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso_full.gaussian(self.X, self.Y, self.lagrange * np.sqrt(n))
self._method_instance.sparse_inverse = True
return self._method_instance
liu_sparseinv_1se.register()
class liu_sparseinv_1se_known(liu_1se):
method_name = Unicode("ROSI - known")
dispersion = Float(1.)
"""
Force the use of the debiasing matrix.
"""
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso_full.gaussian(self.X, self.Y, self.lagrange * np.sqrt(n))
self._method_instance.sparse_inverse = True
return self._method_instance
liu_sparseinv_1se_known.register()
class liu_R_theory(liu_theory):
selectiveR_method = True
method_name = Unicode("Liu (R code)")
def generate_pvalues(self):
try:
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('y', self.Y)
rpy.r.assign('sigma_reid', self.sigma_reid)
rpy.r('y = as.numeric(y)')
rpy.r.assign('lam', self.lagrange[0])
rpy.r('''
p = ncol(X);
n = nrow(X);
sigma_est = 1.
if (p >= n) {
sigma_est = sigma_reid
} else {
sigma_est = sigma(lm(y ~ X - 1))
}
penalty_factor = rep(1, p);
lam = lam / sqrt(n); # lambdas are passed a sqrt(n) free from python code
soln = selectiveInference:::solve_problem_glmnet(X, y, lam, penalty_factor=penalty_factor, loss="ls")
PVS = selectiveInference:::inference_group_lasso(X, y,
soln, groups=1:ncol(X),
lambda=lam, penalty_factor=penalty_factor,
sigma_est, loss="ls", algo="Q",
construct_ci=FALSE)
active_vars=PVS$active_vars - 1 # for 0-based
pvalues = PVS$pvalues
''')
pvalues = np.asarray(rpy.r('pvalues'))
active_set = np.asarray(rpy.r('active_vars'))
numpy2ri.deactivate()
if len(active_set) > 0:
return active_set, pvalues
else:
return [], []
except:
return [np.nan], [np.nan] # some R failure occurred
liu_R_theory.register()
class liu_R_aggressive(liu_R_theory):
lambda_choice = Unicode('aggressive')
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
liu_R_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
liu_R_aggressive.register()
class lee_full_R_theory(liu_theory):
wide_OK = False # requires at least n>p
method_name = Unicode("Lee (R code)")
selectiveR_method = True
def generate_pvalues(self):
numpy2ri.activate()
rpy.r.assign('x', self.X)
rpy.r.assign('y', self.Y)
rpy.r('y = as.numeric(y)')
rpy.r.assign('sigma_reid', self.sigma_reid)
rpy.r.assign('lam', self.lagrange[0])
rpy.r('''
sigma_est=sigma_reid
n = nrow(x);
gfit = glmnet(x, y, standardize=FALSE, intercept=FALSE)
lam = lam / sqrt(n); # lambdas are passed a sqrt(n) free from python code
if (lam < max(abs(t(x) %*% y) / n)) {
beta = coef(gfit, x=x, y=y, s=lam, exact=TRUE)[-1]
out = fixedLassoInf(x, y, beta, lam*n, sigma=sigma_est, type='full', intercept=FALSE)
active_vars=out$vars - 1 # for 0-based
pvalues = out$pv
} else {
pvalues = NULL
active_vars = numeric(0)
}
''')
pvalues = np.asarray(rpy.r('pvalues'))
active_set = np.asarray(rpy.r('active_vars'))
numpy2ri.deactivate()
if len(active_set) > 0:
return active_set, pvalues
else:
return [], []
lee_full_R_theory.register()
class lee_full_R_aggressive(lee_full_R_theory):
lambda_choice = Unicode("aggressive")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
lee_full_R_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
lee_full_R_aggressive.register()
# Unrandomized selected
class lee_theory(parametric_method):
model_target = Unicode("selected")
method_name = Unicode("Lee")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
parametric_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1])
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = lasso.gaussian(self.X, self.Y, self.lagrange * np.sqrt(n))
return self._method_instance
def generate_summary(self, compute_intervals=False):
if not self._fit:
self.method_instance.fit()
self._fit = True
X, Y, lagrange, L = self.X, self.Y, self.lagrange, self.method_instance
if len(L.active) > 0:
S = L.summary(compute_intervals=compute_intervals, alternative='onesided')
return S
def generate_pvalues(self):
S = self.generate_summary(compute_intervals=False)
if S is not None:
active_set = np.array(S['variable'])
pvalues = np.asarray(S['pval'])
return active_set, pvalues
else:
return [], []
def generate_intervals(self):
S = self.generate_summary(compute_intervals=True)
if S is not None:
active_set = np.array(S['variable'])
lower, upper = np.asarray(S['lower_confidence']), np.asarray(S['upper_confidence'])
return active_set, lower, upper
else:
return [], [], []
def point_estimator(self):
X, Y, lagrange, L = self.X, self.Y, self.lagrange, self.method_instance
n, p = X.shape
beta_full = np.zeros(p)
if self.estimator == "LASSO":
beta_full[L.active] = L.soln
else:
beta_full[L.active] = L.onestep_estimator
return L.active, beta_full
lee_theory.register()
class lee_CV(lee_theory):
need_CV = True
lambda_choice = Unicode("CV")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
lee_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_min * np.ones(X.shape[1])
lee_CV.register()
class lee_1se(lee_theory):
need_CV = True
lambda_choice = Unicode("1se")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
lee_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_1se * np.ones(X.shape[1])
lee_1se.register()
class lee_aggressive(lee_theory):
lambda_choice = Unicode("aggressive")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
lee_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = 0.8 * l_theory * np.ones(X.shape[1])
lee_aggressive.register()
class lee_weak(lee_theory):
lambda_choice = Unicode("weak")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
lee_theory.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = 2 * l_theory * np.ones(X.shape[1])
lee_weak.register()
class sqrt_lasso(parametric_method):
method_name = Unicode('SqrtLASSO')
kappa = Float(0.7)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
parametric_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = self.kappa * choose_lambda(X)
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
self._method_instance = lasso.sqrt_lasso(self.X, self.Y, self.lagrange)
return self._method_instance
def generate_summary(self, compute_intervals=False):
X, Y, lagrange, L = self.X, self.Y, self.lagrange, self.method_instance
n, p = X.shape
X = X / np.sqrt(n)
if len(L.active) > 0:
S = L.summary(compute_intervals=compute_intervals, alternative='onesided')
return S
def generate_pvalues(self):
S = self.generate_summary(compute_intervals=False)
if S is not None:
active_set = np.array(S['variable'])
pvalues = np.asarray(S['pval'])
return active_set, pvalues
else:
return [], []
def generate_intervals(self):
S = self.generate_summary(compute_intervals=True)
if S is not None:
active_set = np.array(S['variable'])
lower, upper = np.asarray(S['lower_confidence']), np.asarray(S['upper_confidence'])
return active_set, lower, upper
else:
return [], [], []
sqrt_lasso.register()
# Randomized selected
class randomized_lasso(parametric_method):
method_name = Unicode("Randomized LASSO")
model_target = Unicode("selected")
lambda_choice = Unicode("theory")
randomizer_scale = Float(1)
ndraw = 10000
burnin = 1000
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
parametric_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1])
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
mean_diag = np.mean((self.X ** 2).sum(0))
self._method_instance = random_lasso_method.gaussian(self.X,
self.Y,
feature_weights = self.lagrange * np.sqrt(n),
ridge_term=np.std(self.Y) * np.sqrt(mean_diag) / np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
def generate_summary(self, compute_intervals=False):
X, Y, lagrange, rand_lasso = self.X, self.Y, self.lagrange, self.method_instance
n, p = X.shape
if not self._fit:
signs = self.method_instance.fit()
self._fit = True
signs = rand_lasso.fit()
active_set = np.nonzero(signs)[0]
active = signs != 0
# estimates sigma
# JM: for transparency it's better not to have this digged down in the code
X_active = X[:,active_set]
rpy.r.assign('X_active', X_active)
rpy.r.assign('Y', Y)
rpy.r('X_active=as.matrix(X_active)')
rpy.r('Y=as.numeric(Y)')
rpy.r('sigma_est = sigma(lm(Y~ X_active - 1))')
dispersion = rpy.r('sigma_est')
print("dispersion (sigma est for Python)", dispersion)
(observed_target,
cov_target,
cov_target_score,
alternatives) = form_targets(self.model_target,
rand_lasso.loglike,
rand_lasso._W,
active,
**{'dispersion': dispersion})
if active.sum() > 0:
_, pvalues, intervals = rand_lasso.summary(observed_target,
cov_target,
cov_target_score,
alternatives,
level=0.9,
ndraw=self.ndraw,
burnin=self.burnin,
compute_intervals=compute_intervals)
return active_set, pvalues, intervals
else:
return [], [], []
def generate_pvalues(self, compute_intervals=False):
active_set, pvalues, _ = self.generate_summary(compute_intervals=compute_intervals)
if len(active_set) > 0:
return active_set, pvalues
else:
return [], []
def generate_intervals(self):
active_set, _, intervals = self.generate_summary(compute_intervals=True)
if len(active_set) > 0:
return active_set, intervals[:,0], intervals[:,1]
else:
return [], [], []
class randomized_lasso_CV(randomized_lasso):
need_CV = True
lambda_choice = Unicode("CV")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_min * np.ones(X.shape[1])
class randomized_lasso_1se(randomized_lasso):
need_CV = True
lambda_choice = Unicode("1se")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_1se * np.ones(X.shape[1])
randomized_lasso.register(), randomized_lasso_CV.register(), randomized_lasso_1se.register()
# More aggressive lambda choice
class randomized_lasso_aggressive(randomized_lasso):
lambda_choice = Unicode("aggressive")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
class randomized_lasso_aggressive_half(randomized_lasso):
lambda_choice = Unicode('aggressive')
randomizer_scale = Float(0.5)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
class randomized_lasso_weak_half(randomized_lasso):
lambda_choice = Unicode('weak')
randomizer_scale = Float(0.5)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 2.
randomized_lasso_weak_half.register()
class randomized_lasso_aggressive_quarter(randomized_lasso):
randomizer_scale = Float(0.25)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
randomized_lasso_aggressive.register(), randomized_lasso_aggressive_half.register(), randomized_lasso_aggressive_quarter.register()
# Randomized selected smaller randomization
class randomized_lasso_half(randomized_lasso):
randomizer_scale = Float(0.5)
pass
class randomized_lasso_half_CV(randomized_lasso_CV):
need_CV = True
randomizer_scale = Float(0.5)
pass
class randomized_lasso_half_1se(randomized_lasso_1se):
need_CV = True
randomizer_scale = Float(0.5)
pass
randomized_lasso_half.register(), randomized_lasso_half_CV.register(), randomized_lasso_half_1se.register()
# selective mle
class randomized_lasso_mle(randomized_lasso_aggressive_half):
method_name = Unicode("Randomized MLE")
randomizer_scale = Float(0.5)
model_target = Unicode("selected")
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = randomized_modelQ(self.feature_cov * n,
self.X,
self.Y,
self.lagrange * np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
def generate_pvalues(self):
X, Y, lagrange, rand_lasso = self.X, self.Y, self.lagrange, self.method_instance
n, p = X.shape
if not self._fit:
signs = self.method_instance.fit()
self._fit = True
signs = rand_lasso.fit()
active_set = np.nonzero(signs)[0]
Z, pvalues = rand_lasso.selective_MLE(target=self.model_target,
solve_args={'min_iter':1000, 'tol':1.e-12})[-3:-1]
print(pvalues, 'pvalues')
print(Z, 'Zvalues')
if len(pvalues) > 0:
return active_set, pvalues
else:
return [], []
randomized_lasso_mle.register()
# Using modelQ for randomized
class randomized_lasso_half_pop_1se(randomized_lasso_half_1se):
method_name = Unicode("Randomized ModelQ (pop)")
randomizer_scale = Float(0.5)
nsample = 15000
burnin = 2000
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = randomized_modelQ(self.feature_cov * n,
self.X,
self.Y,
self.lagrange * np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
class randomized_lasso_half_semi_1se(randomized_lasso_half_1se):
method_name = Unicode("Randomized ModelQ (semi-supervised)")
randomizer_scale = Float(0.5)
B = 10000
nsample = 15000
burnin = 2000
@classmethod
def setup(cls, feature_cov):
cls.feature_cov = feature_cov
cls._chol = np.linalg.cholesky(feature_cov)
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
# draw sample of X for semi-supervised method
_chol = self._chol
p = _chol.shape[0]
Q = 0
batch_size = int(self.B/10)
for _ in range(10):
X_semi = np.random.standard_normal((batch_size, p)).dot(_chol.T)
Q += X_semi.T.dot(X_semi)
Q += self.X.T.dot(self.X)
Q /= (10 * batch_size + self.X.shape[0])
n, p = self.X.shape
self._method_instance = randomized_modelQ(Q * n,
self.X,
self.Y,
self.lagrange * np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
randomized_lasso_half_pop_1se.register(), randomized_lasso_half_semi_1se.register()
# Using modelQ for randomized
class randomized_lasso_half_pop_aggressive(randomized_lasso_aggressive_half):
method_name = Unicode("Randomized ModelQ (pop)")
randomizer_scale = Float(0.5)
nsample = 10000
burnin = 2000
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
self._method_instance = randomized_modelQ(self.feature_cov * n,
self.X,
self.Y,
self.lagrange * np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
class randomized_lasso_half_semi_aggressive(randomized_lasso_aggressive_half):
method_name = Unicode("Randomized ModelQ (semi-supervised)")
randomizer_scale = Float(0.25)
B = 10000
nsample = 15000
burnin = 2000
@classmethod
def setup(cls, feature_cov):
cls.feature_cov = feature_cov
cls._chol = np.linalg.cholesky(feature_cov)
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
# draw sample of X for semi-supervised method
_chol = self._chol
p = _chol.shape[0]
Q = 0
batch_size = int(self.B/10)
for _ in range(10):
X_semi = np.random.standard_normal((batch_size, p)).dot(_chol.T)
Q += X_semi.T.dot(X_semi)
Q += self.X.T.dot(self.X)
Q /= (10 * batch_size + self.X.shape[0])
n, p = self.X.shape
self._method_instance = randomized_modelQ(Q * n,
self.X,
self.Y,
self.lagrange * np.sqrt(n),
randomizer_scale=self.randomizer_scale * np.std(self.Y) * np.sqrt(n))
return self._method_instance
randomized_lasso_half_pop_aggressive.register(), randomized_lasso_half_semi_aggressive.register()
# Randomized sqrt selected
class randomized_sqrtlasso(randomized_lasso):
method_name = Unicode("Randomized SqrtLASSO")
model_target = Unicode("selected")
randomizer_scale = Float(1)
kappa = Float(0.7)
@property
def method_instance(self):
if not hasattr(self, "_method_instance"):
n, p = self.X.shape
lagrange = np.ones(p) * choose_lambda(self.X) * self.kappa
self._method_instance = random_lasso_method.gaussian(self.X,
self.Y,
lagrange,
randomizer_scale=self.randomizer_scale * np.std(self.Y))
return self._method_instance
def generate_summary(self, compute_intervals=False):
X, Y, rand_lasso = self.X, self.Y, self.method_instance
n, p = X.shape
X = X / np.sqrt(n)
if not self._fit:
self.method_instance.fit()
self._fit = True
signs = self.method_instance.selection_variable['sign']
active_set = np.nonzero(signs)[0]
active = signs != 0
(observed_target,
cov_target,
cov_target_score,
alternatives) = form_targets(self.model_target,
rand_lasso.loglike,
rand_lasso._W,
active)
_, pvalues, intervals = rand_lasso.summary(observed_target,
cov_target,
cov_target_score,
alternatives,
ndraw=self.ndraw,
burnin=self.burnin,
compute_intervals=compute_intervals)
if len(pvalues) > 0:
return active_set, pvalues, intervals
else:
return [], [], []
class randomized_sqrtlasso_half(randomized_sqrtlasso):
randomizer_scale = Float(0.5)
pass
randomized_sqrtlasso.register(), randomized_sqrtlasso_half.register()
class randomized_sqrtlasso_bigger(randomized_sqrtlasso):
kappa = Float(0.8)
pass
class randomized_sqrtlasso_bigger_half(randomized_sqrtlasso):
kappa = Float(0.8)
randomizer_scale = Float(0.5)
pass
randomized_sqrtlasso_bigger.register(), randomized_sqrtlasso_bigger_half.register()
# Randomized full
class randomized_lasso_full(randomized_lasso):
model_target = Unicode('full')
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1])
class randomized_lasso_full_CV(randomized_lasso_full):
need_CV = True
lambda_choice = Unicode("CV")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso_full.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_min * np.ones(X.shape[1])
class randomized_lasso_full_1se(randomized_lasso_full):
need_CV = True
lambda_choice = Unicode("1se")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso_full.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_1se * np.ones(X.shape[1])
randomized_lasso_full.register(), randomized_lasso_full_CV.register(), randomized_lasso_full_1se.register()
# Randomized full smaller randomization
class randomized_lasso_full_half(randomized_lasso_full):
randomizer_scale = Float(0.5)
pass
class randomized_lasso_full_half_CV(randomized_lasso_full_CV):
randomizer_scale = Float(0.5)
pass
class randomized_lasso_full_half_1se(randomized_lasso_full_1se):
need_CV = True
randomizer_scale = Float(0.5)
pass
randomized_lasso_full_half.register(), randomized_lasso_full_half_CV.register(), randomized_lasso_full_half_1se.register()
# Aggressive choice of lambda
class randomized_lasso_full_aggressive(randomized_lasso_full):
lambda_choice = Unicode("aggressive")
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
randomized_lasso_full.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_theory * np.ones(X.shape[1]) * 0.8
class randomized_lasso_full_aggressive_half(randomized_lasso_full_aggressive):
randomizer_scale = Float(0.5)
pass
randomized_lasso_full_aggressive.register(), randomized_lasso_full_aggressive_half.register()
class randomized_lasso_R_theory(randomized_lasso):
method_name = Unicode("Randomized LASSO (R code)")
selective_Rmethod = True
def generate_summary(self, compute_intervals=False):
numpy2ri.activate()
rpy.r.assign('X', self.X)
rpy.r.assign('y', self.Y)
rpy.r('y = as.numeric(y)')
rpy.r.assign('q', self.q)
rpy.r.assign('lam', self.lagrange[0])
rpy.r.assign("randomizer_scale", self.randomizer_scale)
rpy.r.assign("compute_intervals", compute_intervals)
rpy.r('''
n = nrow(X)
p = ncol(X)
lam = lam * sqrt(n)
mean_diag = mean(apply(X^2, 2, sum))
ridge_term = sqrt(mean_diag) * sd(y) / sqrt(n)
result = randomizedLasso(X, y, lam, ridge_term=ridge_term,
noise_scale = randomizer_scale * sd(y) * sqrt(n), family='gaussian')
active_set = result$active_set
if (length(active_set)==0){
active_set = -1
} else{
sigma_est = sigma(lm(y ~ X[,active_set] - 1))
cat("sigma est for R", sigma_est,"\n")
targets = selectiveInference:::compute_target(result, 'partial', sigma_est = sigma_est,
construct_pvalues=rep(TRUE, length(active_set)),
construct_ci=rep(compute_intervals, length(active_set)))
out = randomizedLassoInf(result,
targets=targets,
sampler = "norejection",
level=0.9,
burnin=1000,
nsample=10000)
active_set=active_set-1
pvalues = out$pvalues
intervals = out$ci
}
''')
active_set = np.asarray(rpy.r('active_set'), np.int)
print(active_set)
if active_set[0]==-1:
numpy2ri.deactivate()
return [], [], []
pvalues = np.asarray(rpy.r('pvalues'))
intervals = np.asarray(rpy.r('intervals'))
numpy2ri.deactivate()
return active_set, pvalues, intervals
randomized_lasso_R_theory.register()
class data_splitting_1se(parametric_method):
method_name = Unicode('Data splitting')
selection_frac = Float(0.5)
def __init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid):
parametric_method.__init__(self, X, Y, l_theory, l_min, l_1se, sigma_reid)
self.lagrange = l_1se * np.ones(X.shape[1])
n, p = self.X.shape
n1 = int(self.selection_frac * n)
X1, X2 = self.X1, self.X2 = self.X[:n1], self.X[n1:]
Y1, Y2 = self.Y1, self.Y2 = self.Y[:n1], self.Y[n1:]
pen = rr.weighted_l1norm(np.sqrt(n1) * self.lagrange, lagrange=1.)
loss = rr.squared_error(X1, Y1)
problem = rr.simple_problem(loss, pen)
soln = problem.solve()
self.active_set = np.nonzero(soln)[0]
self.signs = np.sign(soln)[self.active_set]
self._fit = True
def generate_pvalues(self):
X2, Y2 = self.X2[:,self.active_set], self.Y2
if len(self.active_set) > 0:
s = len(self.active_set)
X2i = np.linalg.inv(X2.T.dot(X2))
beta2 = X2i.dot(X2.T.dot(Y2))
resid2 = Y2 - X2.dot(beta2)
n2 = X2.shape[0]
sigma2 = np.sqrt((resid2**2).sum() / (n2 - s))
Z2 = beta2 / np.sqrt(sigma2**2 * np.diag(X2i))
signed_Z2 = self.signs * Z2
pvalues = 1 - ndist.cdf(signed_Z2)
return self.active_set, pvalues
else:
return [], []
data_splitting_1se.register()
```
|
{
"source": "jelenanemcic/ekspertni",
"score": 3
}
|
#### File: jelenanemcic/ekspertni/board.py
```python
import tkinter as tk
from tkinter import ttk
from random import randrange
import math
from strategy import CSP, SAT
class Field:
# a[row][col]
def __init__(self, i, j, board_dim, is_mine=False):
self.row = i
self.column = j
self.id = int(board_dim * i + j + 1)
self.adjacent_mines = 0
self.covered = True
self.is_mine = is_mine
self.marked_mine = False
def __repr__(self):
return "[{}][{}]: {}".format(self.row, self.column, self.adjacent_mines)
class Minesweeper:
def __init__(self, n, k):
"""
Create board object with dimensions nxn and k mines inside
set at random locations
"""
self.labels = {}
self.board_dim = n
self.num_mines = k
self.marked = []
self.board = [[Field(j, i, self.board_dim) for i in range(n)] for j in range(n)]
self.buttons = []
self.opened = 0
self.strategy = None
self.setup_gui()
def get_field_by_id(self, id):
return self.board[math.floor((id - 1) / self.board_dim)][(id - 1) % self.board_dim]
def _right_click(self, event):
"""
Handle right click on the grid
If the field is marked as mine, we are removing the mark and vice versa.
"""
grid_info = event.widget.grid_info()
column, row = grid_info["column"], grid_info["row"]
if self.board[row][column].marked_mine:
self.mark_field_safe(self.board[row][column])
else:
self.mark_field_dangerous(self.board[row][column])
def _left_click(self, event):
"""
Handle left click on the grid.
If the field we clicked is already opened, do nothing since it makes no sense.
"""
grid_info = event.widget.grid_info()
column, row = grid_info["column"], grid_info["row"]
if self.board[row][column].covered:
self.open_field(self.board[row][column])
def setup_gui(self):
"""
Create and setup objects needed for GUI.
"""
self.root = tk.Tk()
self.root.title("Minesweeper solver")
self.images = {
"covered": tk.PhotoImage(file="images/covered.png").subsample(6, 6),
"marked": tk.PhotoImage(file="images/flagged.png").subsample(6, 6),
"numbers": [tk.PhotoImage(file="images/{}.png".format(i)).subsample(6, 6) for i in range(8+1)],
"bomb": tk.PhotoImage(file="images/bomb.png").subsample(2, 2)
}
# create 2x3 grid for root frame
[self.root.rowconfigure(r, weight=1) for r in range(3)]
[self.root.columnconfigure(c, weight=1) for c in range(3)]
self.labels["mines"] = ttk.Label(self.root, text="Mines: {}".format(self.num_mines))
self.labels["mines"].grid(row=0, column=0)
self.labels["alive"] = ttk.Label(self.root, text="Alive")
self.labels["alive"].grid(row=0, column=1)
self.labels["opened"] = ttk.Label(self.root, text="Opened: 0")
self.labels["opened"].grid(row=0, column=2)
self.strategy_grid = ttk.Frame(self.root, name="strategy_grid")
self.strategy_grid.grid(row=1, column=0, rowspan=1, columnspan=3)
CSP_button = ttk.Button(self.strategy_grid, name="csp_button", text="CSP Strategy")
CSP_button.grid(row=0, column=0)
CSP_button.bind('<ButtonPress-1>', self._run_CSP)
SAT_button = ttk.Button(self.strategy_grid, name="sat_button", text="SAT Strategy")
SAT_button.grid(row=0, column=1)
SAT_button.bind('<ButtonPress-1>', self._run_SAT)
next_step = ttk.Button(self.strategy_grid, name="next_step", text="Next step")
next_step.grid(row=0, column=2)
next_step.bind('<ButtonPress-1>', self._next_step)
next_step.config(state=tk.DISABLED)
# create a frame for minesweeper button grid
self.grid = ttk.Frame(self.root)
self.grid.grid(row=2, column=0, rowspan=1, columnspan=self.board_dim)
for x in range(self.board_dim):
row_buttons = []
for y in range(self.board_dim):
b = ttk.Button(self.grid, width=2, image=self.images["covered"])
b.grid(row=x, column=y)
b.bind('<ButtonPress-1>', self._left_click)
b.bind('<ButtonPress-3>', self._right_click)
b.config(state=tk.DISABLED)
row_buttons.append(b)
self.buttons.append(row_buttons)
def set_mines(self, first_field):
"""
Generate self.num_mines random tuples that represent mine positions
"""
mines = 0
while mines < self.num_mines:
x, y = (randrange(0, self.board_dim), randrange(0, self.board_dim))
if first_field != (x, y):
mines += 1
self.board[x][y].is_mine = True
self._update()
def num_closed(self):
"""
Return number of closed fields on the board
"""
return self.board_dim ** 2 - self.opened
def get_adjacent_fields(self, row_index, col_index):
"""
Get a list of adjacent fields around field specified with row_index and col_index
"""
adjacent_fields = []
for i in range(max(0, row_index - 1), min(self.board_dim, row_index + 2)):
for j in range(max(0, col_index - 1), min(self.board_dim, col_index + 2)):
if i != row_index or j != col_index:
adjacent_fields.append(self.board[i][j])
return adjacent_fields
def get_adjacent_mines(self, row_index, col_index):
"""
Get number of mines in the adjacent fields.
"""
return sum(f.is_mine for f in self.get_adjacent_fields(row_index, col_index))
def _update(self):
"""
For each field that is not marked with is_mine compute number of adjacent mines
"""
for (row_index, row) in enumerate(self.board):
for (col_index, field) in enumerate(row):
field = self.board[row_index][col_index]
if not field.is_mine:
field.adjacent_mines = self.get_adjacent_mines(row_index, col_index)
def mark_field_dangerous(self, field):
"""
Mark field as dangerous and add it to the marked list
"""
if field not in self.marked:
field.marked_mine = True
self.marked.append(field)
print("Mark field {}".format(field))
self.buttons[field.row][field.column].config(image=self.images["marked"])
self.labels["mines"].config(text="Mines: {}".format(self.num_mines - len(self.marked)))
def mark_field_safe(self, field):
"""
Remove mark on the field and remove it from marked list
"""
if field in self.marked:
field.marked_mine = False
self.marked.remove(field)
print("Remove mark on field {}".format(field))
self.buttons[field.row][field.column].config(image=self.images["covered"])
self.labels["mines"].config(text="Mines: {}".format(self.num_mines - len(self.marked)))
def open_field(self, field):
"""
Open field and check if there is a mine.
If there is a bomb this function will create new windows with Game over message.
If opened field has no adjacent mines we will open new all of his covered adjacent
fields.
Returns list of newly opened fields
"""
assert field.covered
self.opened += 1
field.covered = False
print("Opening {}".format(field))
if field.is_mine:
self.buttons[field.row][field.column].config(image=self.images["bomb"])
self.labels["alive"].config(text="Dead")
print("Game over.")
popup = tk.Toplevel(self.root)
popup.wm_title("Lose")
l = tk.Label(popup, text="Game over")
l.grid(row=0, column=0, columnspan=2)
b1 = ttk.Button(popup, text="Exit", command=quit)
b1.grid(row=1, column=0)
b2 = ttk.Button(popup, text="Restart", command=lambda: self.restart())
b2.grid(row=1, column=1)
else:
# if any of these fields are marked as dangerous we should delete now because
# they are obviously not dangerous and mark as safe
self.mark_field_safe(field)
self.labels["opened"].config(text="Opened: {}".format(self.opened))
self.buttons[field.row][field.column].config(image=self.images["numbers"][field.adjacent_mines])
# check if all fields are opened
if self.num_closed() == self.num_mines:
# mark all covered as bombs
for row in self.board:
for field in row:
if field.covered:
self.mark_field_dangerous(field)
print("Game solved.")
popup = tk.Toplevel(self.root)
popup.wm_title("Win")
l = tk.Label(popup, text="Game solved")
l.grid(row=0, column=0, columnspan=2)
b1 = ttk.Button(popup, text="Exit", command=quit)
b1.grid(row=1, column=0)
b2 = ttk.Button(popup, text="Restart", command=lambda: self.restart())
b2.grid(row=1, column=1)
elif field.adjacent_mines == 0:
opened_fields = [field]
for adjacent_field in self.get_adjacent_fields(field.row, field.column):
if adjacent_field.covered:
opened_fields += self.open_field(adjacent_field)
return opened_fields
else:
return [field]
return [field]
def _run_CSP(self, event):
"""
CSP button is clicked, we are solving with CSP strategy.
We will also disable SAT button since we clicked CSP.
"""
SAT_button = event.widget.winfo_toplevel().nametowidget("strategy_grid.sat_button")
SAT_button.config(state=tk.DISABLED)
self.enable_buttons(event)
self.strategy = CSP(self)
first_field = (randrange(0, self.board_dim), randrange(0, self.board_dim))
self.set_mines(first_field)
self.strategy.first_step(first_field=first_field)
def _run_SAT(self, event):
"""
SAT button is clicked, we are solving with SAT strategy.
We will also disable CSP button since we clicked SAT.
"""
CSP_button = event.widget.winfo_toplevel().nametowidget("strategy_grid.csp_button")
CSP_button.config(state=tk.DISABLED)
self.enable_buttons(event)
self.strategy = SAT(self)
first_field = (randrange(0, self.board_dim), randrange(0, self.board_dim))
self.set_mines(first_field)
self.strategy.first_step(first_field=first_field)
def _next_step(self, event):
"""
Run one step of chosen strategy
"""
self.strategy.step()
def enable_buttons(self, event):
"""
Enables Next step button and all field buttons in the board.
"""
next_step = event.widget.winfo_toplevel().nametowidget("strategy_grid.next_step")
next_step.config(state=tk.NORMAL)
for row in self.buttons:
for button in row:
button.config(state=tk.NORMAL)
def restart(self):
"""
Restart the game by reseting all the widgets in the root window.
"""
self.root.destroy()
self.labels = {}
self.marked = []
self.board = [[Field(j, i, self.board_dim) for i in range(self.board_dim)] for j in range(self.board_dim)]
self.buttons = []
self.opened = 0
self.strategy = None
self.setup_gui()
```
|
{
"source": "jelford/activesoup",
"score": 3
}
|
#### File: src/activesoup/driver.py
```python
import functools
from typing import Any, Dict, Optional, Callable
from urllib.parse import urljoin
import requests
import activesoup
import activesoup.html
from activesoup.response import CsvResponse, JsonResponse
class DriverError(RuntimeError):
"""Errors that occur as part of operating the driver
These errors reflect logic errors (such as accessing the ``last_response``
before navigating) or that the ``Driver`` is unable to carry out the
action that was requested (e.g. the server returned a bad redirect)"""
pass
_Resolver = Callable[[requests.Response], activesoup.Response]
class ContentResolver:
def __init__(self):
self._resolvers: Dict[str, _Resolver] = {}
def register(self, content_type: str, resolver: _Resolver) -> None:
self._resolvers[content_type] = resolver
def resolve(self, response: requests.Response) -> activesoup.Response:
content_type = response.headers.get("Content-Type", None)
if content_type is not None:
for k, factory in self._resolvers.items():
if content_type.startswith(k):
return factory(response)
return activesoup.Response(response, content_type)
class Driver:
""":py:class:`Driver` is the main entrypoint into ``activesoup``.
The ``Driver`` provides navigation functions, and keeps track of the
current page. Note that this class is re-exposed via ``activesoup.Driver``.
>>> d = Driver()
>>> page = d.get("https://github.com/jelford/activesoup")
>>> assert d.url == "https://github.com/jelford/activesoup"
- Navigation updates the current page
- Any methods which are not defined directly on ``Driver`` are
forwarded on to the most recent ``Response`` object
A single :py:class:`requests.Session` is held open for the
lifetime of the ``Driver`` - the ``Session`` will accumulate
cookies and open connections. ``Driver`` may be used as a
context manager to automatically close all open connections
when finished:
.. code-block::
with Driver() as d:
d.get("https://github.com/jelford/activesoup")
See :ref:`getting-started` for a full demo of usage.
:param kwargs: optional keyword arguments may be passed, which will be set
as attributes of the :py:class:`requests.Session` which will be used
for the lifetime of this ``Driver``:
>>> d = Driver(headers={"User-Agent": "activesoup script"})
>>> d.session.headers["User-Agent"]
'activesoup script'
"""
def __init__(self, **kwargs) -> None:
self.session = requests.Session()
for k, v in kwargs.items():
setattr(self.session, k, v)
self._last_response: Optional[activesoup.Response] = None
self._raw_response: Optional[requests.Response] = None
self.content_resolver = ContentResolver()
self.content_resolver.register(
"text/html", functools.partial(activesoup.html.resolve, self)
)
self.content_resolver.register("text/csv", CsvResponse)
self.content_resolver.register(
"application/json", JsonResponse
)
def __enter__(self) -> "Driver":
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.session.close()
def _resolve_url(self, possibly_relative_url) -> str:
"""Converts a relative URL into an absolute one if possible.
If there is no current page (because the ``Driver`` has not yet received
a call to :py:meth:`Driver.get`), then the URL is returned unchanged
>>> d = Driver()
>>> d._resolve_url("./something")
'./something'
>>> _ = d.get("https://github.com/jelford/activesoup/")
>>> d._resolve_url("./something")
'https://github.com/jelford/activesoup/something'
:param str possibly_relative_url: A URL which is assumed to be relative
the current page
:returns: A URL that has been resolved relative to the current page, if
there is one.
"""
current_url_str = self.url
if not current_url_str:
return possibly_relative_url
return urljoin(current_url_str, possibly_relative_url)
def get(self, url, **kwargs) -> "Driver":
"""Move the Driver to a new page.
This is the primary means of navigating the ``Driver`` to the page of interest.
:param str url: the new URL for the Driver to navigate to (e.g. `https://www.example.com`)
:param kwargs: additional keyword arguments are passed in to the
constructor of the :py:class:`requests.Request` used to fetch the
page.
:returns: the ``Driver`` object itself
:rtype: Driver
"""
return self._do(requests.Request(method="GET", url=url, **kwargs))
def _do(self, request: requests.Request) -> "Driver":
request.url = self._resolve_url(request.url)
prepped = self.session.prepare_request(request)
return self._handle_response(self.session.send(prepped))
def _handle_response(self, response: requests.Response) -> "Driver":
if response.status_code in range(300, 304):
redirected_to = response.headers.get("Location", None)
if not redirected_to:
raise DriverError("Found a redirect, but no onward location given")
return self.get(redirected_to)
self._last_response = self.content_resolver.resolve(response)
self._raw_response = response
return self
@property
def url(self) -> Optional[str]:
"""The URL of the current page
:returns: ``None`` if no page has been loaded, otherwise the URL of the most recently
loaded page.
:rtype: str
"""
return self._last_response.url if self._last_response is not None else None
@property
def last_response(self) -> Optional[activesoup.Response]:
"""Get the response object that was the result of the most recent page load
:returns: ``None`` if no page has been loaded, otherwise the parsed result of the most
recent page load
:rtype: activesoup.Response
"""
return self._last_response
def __getattr__(self, item) -> Any:
if not self._last_response:
raise DriverError("Not on a page")
return getattr(self._last_response, item)
def __getitem__(self, item) -> Any:
if not self._last_response:
raise DriverError("Not on a page")
return self._last_response[item]
def __str__(self) -> str:
last_resp_str = str(self._last_response) if self._last_response else "unbound"
return f"<activesoup.driver.Driver[{last_resp_str}]>"
```
#### File: activesoup/src/conftest.py
```python
import pytest
@pytest.fixture(autouse=True)
def add_html_parsing(doctest_namespace):
import requests
import activesoup.html
def html_page(raw_html):
response_from_server = requests.Response()
response_from_server._content = raw_html.encode('utf-8')
return activesoup.html.resolve(driver=None, response=response_from_server) # typing: ignore
doctest_namespace["html_page"] = html_page
@pytest.fixture(autouse=True)
def add_json_parsing(doctest_namespace):
import requests
import activesoup.response
def json_page(raw_json):
response_from_server = requests.Response()
response_from_server._content = raw_json.encode('utf-8')
return activesoup.response.JsonResponse(raw_response=response_from_server)
doctest_namespace["json_page"] = json_page
@pytest.fixture(autouse=True)
def fake_github(requests_mock):
for form in ("https://github.com/jelford/activesoup/", "https://github.com/jelford/activesoup"):
requests_mock.get(form,
text="<html><body><h1>Fake activesoup repo</h1></body></html>",
headers={
"Content-Type": "text/html"
})
requests_mock.get("https://github.com/jelford/activesoup/issues/new",
text="<html><body><form></form></body></html>",
headers={
"Content-Type": "text/html"
})
requests_mock.post("https://github.com/jelford/activesoup/issues/new",
status_code=302,
headers={"Location": "https://github.com/jelford/activesoup/issues/1"})
requests_mock.get("https://github.com/jelford/activesoup/issues/1", text="Dummy page")
```
|
{
"source": "jelford/cloud-init-gen",
"score": 2
}
|
#### File: jelford/cloud-init-gen/build-cloud-init.py
```python
import toml
import gzip
import io
import shutil
import base64
import os
config = None
from contextlib import contextmanager
@contextmanager
def indent(depth=4, char=' '):
try:
current_indent = indent._current_level
except AttributeError:
indent._current_level = 0
indent._current_level += depth
def prtr(*args, **kwargs):
print(char * indent._current_level, *args, **kwargs)
try:
yield prtr
finally:
indent._current_level -= depth
def header():
print('#cloud-config')
def packages():
try:
packages = config['packages']
except KeyError:
return
print('packages:')
with indent(depth=2) as p:
for package_name in packages:
p('-', package_name)
def users():
try:
users = config['users']
except KeyError:
return
print('users:')
with indent(depth=2) as p:
for name, user in users.items():
p(f'- name: {name}')
with indent(depth=2) as p:
groups, shell, key_file = [user.get(k) for k in ('groups', 'shell', 'key_file')]
if groups:
p(f'groups: {", ".join(groups)}')
if shell:
p(f'shell: {shell}')
if key_file:
p('ssh-authorized-keys:')
with indent(depth=2):
key_path = os.path.expanduser(key_file)
with open(key_path, 'r') as f:
content = f.read()
p('-', content.strip())
def files():
try:
files = config['files']
except KeyError:
return
print('write_files:')
with indent(depth=2) as p:
for _, f in files.items():
p(f'- path: {f["remote"]}')
with indent(depth=2) as p:
p('encoding: "gz+b64"')
data_buffer = io.BytesIO()
local_path = os.path.expanduser(f['local'])
with open(local_path, 'rb') as local_file:
with gzip.open(data_buffer, mode='wb') as gz:
shutil.copyfileobj(local_file, gz)
encoded_file_content = base64.standard_b64encode(data_buffer.getbuffer())
p('content: |')
with indent(depth=2) as p:
p(encoded_file_content.decode('utf-8'))
def run():
global config
with open('cloud-init-config.toml', 'r', encoding='utf-8') as f:
config = toml.load(f)
header()
packages()
users()
files()
if __name__ == '__main__':
run()
```
|
{
"source": "jelford/crumhorn",
"score": 2
}
|
#### File: backends/digitalocean/cloud.py
```python
import datetime
import random
import string
import digitalocean
import crumhorn.configuration.userdata as userdata
from crumhorn.keyutil import get_fingerprint
from .droplet import Droplet
def _generate_new_droplet_name(machine_configuration):
return '{config_name}-{when}-{rand}'.format(
config_name=machine_configuration.name,
when=datetime.datetime.now().strftime('%Y%m%d%H%m'),
rand=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)))
class Cloud():
def __init__(self, authentication_token, region_name, root_ssh_key_fingerprint):
self.root_ssh_key_fingerprint = root_ssh_key_fingerprint
self.region_name = region_name
self.authentication_token = authentication_token
self._manager_api = digitalocean.Manager(token=authentication_token)
def find_base_snapshot_name(self, machine_configuration):
if isinstance(machine_configuration, type('')) or isinstance(machine_configuration, type(b'')):
return machine_configuration
else:
return '{name}-{region}-{hash}'.format(name=machine_configuration.name, region=self.region_name,
hash=machine_configuration.config_hash.decode('utf-8'))
def first_boot(self, machine_configuration, size_slug):
try:
existing_id = self.find_image_id(machine_configuration)
raise ValueError(
'Snapshot already exists for \'{name}\' - id is \'{id}\''.format(name=machine_configuration.name,
id=existing_id))
except KeyError:
pass
configuration = str(userdata.as_userdata_string(machine_configuration))
droplet = digitalocean.Droplet(token=self.authentication_token,
name=machine_configuration.name,
region=self.region_name,
image=self.find_image_id(machine_configuration.base_image_configuration),
size_slug=size_slug,
backups=False,
ssh_keys=[self.root_ssh_key_fingerprint],
user_data=configuration)
droplet.create()
return Droplet(self, droplet, machine_configuration)
def launch(self, machine_configuration, size_slug):
snapshot_id = self.find_image_id(machine_configuration)
droplet = digitalocean.Droplet(token=self.authentication_token,
name=_generate_new_droplet_name(machine_configuration),
region=self.region_name,
image=snapshot_id,
size_slug=size_slug,
backups=False,
ssh_keys=[self.root_ssh_key_fingerprint],
user_data=None)
droplet.create()
return Droplet(self, droplet, machine_configuration)
def find_image_id(self, machine_configuration):
snapshot_name = self.find_base_snapshot_name(machine_configuration)
snapshots = {s.name: s for s in self._manager_api.get_my_images()}
try:
return snapshots[snapshot_name].id
except KeyError:
pass
distributions = {i.slug: i for i in self._manager_api.get_images(type='distribution')}
try:
return distributions[snapshot_name].id
except KeyError:
raise KeyError('No snapshot named {}'.format(snapshot_name))
def initialize_cloud(environment):
return Cloud(
authentication_token=environment['digitaloceantoken'],
region_name='lon1',
root_ssh_key_fingerprint=get_fingerprint(environment['ssh_key']))
```
#### File: src/crumhorn/compile.py
```python
from __future__ import absolute_import
import base64
import hashlib
import re
import sys
import tarfile
from os import path
import docopt
import toml
from crumhorn.configuration import machineconfiguration
from crumhorn.configuration.environment import environment
from crumhorn.platform.compatibility.tempfile import NamedTemporaryFile, TemporaryDirectory
_missing_data_pattern = re.compile('filename \'(?P#[^\']+)\' not found')
class MissingDataFileError(KeyError):
pass
def _files_from_configuration(config_dict):
return [f['local'] for f in config_dict.get(config_dict['horn'].get('name', {}), {}).get('files', [])]
def compile_folder(source, output, base_package=None, machinespec_repository=None):
source = path.abspath(source)
output = path.abspath(output)
configuration = toml.load(path.join(source, 'horn.toml'))
# sort to ensure stable hashing for unchanged content
local_files = sorted(_files_from_configuration(configuration) + ['horn.toml'])
if base_package is None:
parent = configuration['horn'].get('parent', None)
if parent is not None:
base_package = machinespec_repository.find_machine_spec(parent)
with tarfile.open(output, mode='w:gz') as dest:
lock_hash = hashlib.sha512()
for f in local_files:
f_path = path.join(source, f)
try:
with open(f_path, 'rb') as opened:
lock_hash.update(opened.read())
except IOError:
raise MissingDataFileError(f)
file_to_add = path.abspath(f_path)
dest_location = path.relpath(file_to_add, source)
dest.add(file_to_add, arcname=dest_location)
if base_package is not None:
with TemporaryDirectory() as tempdir:
with tarfile.open(base_package, mode='r:gz') as base:
base.extractall(path=tempdir)
with open(path.join(tempdir, 'horn.toml'), 'rb') as base_hash:
lock_hash.update(base_hash.read())
dest.add(tempdir, arcname='base')
with NamedTemporaryFile(mode='wb') as lock_file:
lock = base64.urlsafe_b64encode(lock_hash.digest())
lock_file.file.write(lock)
lock_file.file.close()
dest.add(lock_file.name, arcname='lock')
# Check the resultant machinespec can load
machineconfiguration.load_configuration(output)
def main(argv=None):
argv = argv if argv is not None else sys.argv[1:]
options = docopt.docopt(__doc__, argv=argv)
source = options['<package>']
dest = options['<destination>']
if not dest:
dest = path.basename(source) + '.crumspec'
base_package = options['--from']
compile_folder(source, dest, base_package,
machinespec_repository=environment.build_environment().machinespec_repository)
if __name__ == '__main__':
main()
```
#### File: configuration/environment/environment.py
```python
import os
from crumhorn.configuration.environment import machinespec_repository
class CrumhornEnvironment:
def __init__(self, machinespec_repository, cloud_config):
self.cloud_config = cloud_config
self.machinespec_repository = machinespec_repository
def build_environment():
machinespec_repo = machinespec_repository.MachineSpecRepository(
{'repository.searchpath': ':'.join([os.getcwd(), os.environ.get('crumhorn.repository.searchpath', '')])})
cloud_config = {'digitaloceantoken': os.environ['digitaloceantoken']}
return CrumhornEnvironment(machinespec_repo, cloud_config)
```
#### File: crumhorn/configuration/userdata.py
```python
import base64
import itertools
from crumhorn.platform.compatibility.gzip import compress
def as_userdata_string(machine_configuration):
return '\n'.join(itertools.chain(['#cloud-config'], _as_userdata_parts(machine_configuration)))
def _titled_list(list_name, items):
if not items: return
yield '{}:'.format(list_name)
for i in items:
yield ' - {}'.format(i)
def _file_as_byte_echo(file):
return 'echo \'{encoded_content}\' | base64 -d | gzip -d > {target_file}' \
.format(
encoded_content=base64.standard_b64encode(compress(file.content)).decode('utf-8'),
target_file=file.target_path)
def _as_userdata_parts(machine_configuration):
if machine_configuration is None:
return
try:
required_packages = machine_configuration.required_packages
except AttributeError:
required_packages = []
for i in _titled_list('packages', required_packages):
yield i
try:
files_to_copy = machine_configuration.files
except AttributeError:
files_to_copy = []
file_copy_commands = [_file_as_byte_echo(f) for f in files_to_copy] + [
'chmod +x {target_path}'.format(target_path=f.target_path) for f in files_to_copy if 'executable' in f.flags]
try:
raw_cmds = machine_configuration.raw_commands or []
except AttributeError:
raw_cmds = []
try:
services = machine_configuration.services or []
except AttributeError:
services = []
service_cmds = ['systemctl enable {name}'.format(name=s.name) for s in services] + \
['systemctl start {name}'.format(name=s.name) for s in services if s.requires_start] + \
['systemctl restart {name}'.format(name=s.name) for s in services if s.requires_restart]
for i in _titled_list('runcmd', itertools.chain(file_copy_commands, raw_cmds, service_cmds, ['shutdown +1'])):
yield i
```
#### File: configuration/environment/test_machinespec_repository.py
```python
from crumhorn.configuration.environment import machinespec_repository
def test_can_find_machine_spec_from_search_path(tmpdir):
path_to_crumspec = tmpdir.join('machinespec.crumspec')
path_to_crumspec.write('any data')
repository = machinespec_repository.MachineSpecRepository(environment={'repository.searchpath': tmpdir.strpath})
assert repository.find_machine_spec(
machinespec_repository.MachineSpecIdentifier('machinespec')) == path_to_crumspec.strpath
```
|
{
"source": "jelford/deterministic-password-generator",
"score": 3
}
|
#### File: src/deterministicpasswordgenerator/compile.py
```python
import zipfile
from getpass import getpass
import os
import stat
import tempfile
from os import path
from .crypto import encrypt
def compile_ruleset(ruleset_path, ruleset_encryption_password=None, output_path=None):
output_path = output_path or os.getcwd()
ruleset_encryption_password = ruleset_encryption_password or getpass('Password (used to encrypt compiled ruleset):')
ruleset_name = path.basename(ruleset_path)
with tempfile.SpooledTemporaryFile() as output_ruleset:
with zipfile.PyZipFile(output_ruleset, mode='w') as ruleset:
ruleset.writepy(pathname=ruleset_path)
output_ruleset.seek(0)
encrypted_output = encrypt(output_ruleset.read(), key=ruleset_encryption_password)
compiled_ruleset_output_path = path.join(output_path, '{ruleset}.dpgr'.format(ruleset=ruleset_name))
with open(compiled_ruleset_output_path, 'wb') as output:
os.chmod(compiled_ruleset_output_path, stat.S_IREAD)
output.write(encrypted_output)
```
#### File: tests/deterministicpasswordgenerator/test_compile.py
```python
import zipfile
import os
import pytest
import stat
import tempfile
from os import path
from deterministicpasswordgenerator.compile import compile_ruleset
from deterministicpasswordgenerator.rule_bank import load_rule_bank
@pytest.yield_fixture(params=['mock_ruleset_multifile', 'mock_ruleset_simple'])
def ruleset_name(request):
yield request.param
def test_compiled_ruleset_can_be_read_by_parser(ruleset_name: str, tempdir: tempfile.TemporaryDirectory):
path_to_ruleset = rulset_path(ruleset_name)
assert path.isdir(path_to_ruleset)
compile_ruleset(path_to_ruleset, output_path=tempdir.name, ruleset_encryption_password='<PASSWORD>')
rule_bank = load_rule_bank(directory=tempdir.name, encryption_key='encryption-key')
assert rule_bank.get_strategy(ruleset_name) is not None
def test_compiled_ruleset_is_not_readable(ruleset_name, tempdir: tempfile.TemporaryDirectory):
path_to_ruleset = rulset_path(ruleset_name)
compile_ruleset(path_to_ruleset, output_path=tempdir.name, ruleset_encryption_password='<PASSWORD>')
with pytest.raises(zipfile.BadZipfile):
zipfile.ZipFile(path.join(tempdir.name, ruleset_name + '.dpgr'))
def test_compile_asks_for_password_if_none_given(ruleset_name, mocker, tempdir: tempfile.TemporaryDirectory):
mocker.patch('deterministicpasswordgenerator.compile.getpass', side_effect=RequestedPasswordInput())
mocker.patch('builtins.input', side_effect=Forbidden('Should use password-input mode for password'))
with pytest.raises(RequestedPasswordInput):
compile_ruleset(rulset_path(ruleset_name), output_path=tempdir.name)
def test_compiled_rulesets_are_readonly(ruleset_name, tempdir: tempfile.TemporaryDirectory):
path_to_ruleset = rulset_path(ruleset_name)
compile_ruleset(path_to_ruleset, output_path=tempdir.name, ruleset_encryption_password='<PASSWORD>')
compiled_path = path.join(tempdir.name, ruleset_name + '.dpgr')
stat_result = os.stat(compiled_path)
assert stat.S_IRUSR == stat.S_IRUSR & stat_result.st_mode
assert stat.S_IWUSR != stat.S_IWUSR & stat_result.st_mode
assert stat.S_IRGRP != stat.S_IRGRP & stat_result.st_mode
assert stat.S_IWGRP != stat.S_IWGRP & stat_result.st_mode
assert stat.S_IWOTH != stat.S_IWOTH & stat_result.st_mode
assert stat.S_IROTH != stat.S_IROTH & stat_result.st_mode
def rulset_path(ruleset_name: str):
path_to_ruleset = path.join(path.dirname(path.abspath(__file__)), ruleset_name)
return path_to_ruleset
class RequestedPasswordInput(RuntimeError):
pass
class Forbidden(AssertionError):
pass
```
|
{
"source": "jelford/dontforget",
"score": 3
}
|
#### File: jelford/dontforget/dontforget.py
```python
__version__ = "0.0.2"
from pathlib import Path
from os import makedirs
from functools import wraps
from hashlib import blake2b
import sqlite3
import pickle
import gzip
import json
from typing import Callable, Tuple, Optional, Any
__all__ = ["set_hash_customization", "set_storage_directory", "cached"]
def set_hash_customization(custom_hash_data: bytes) -> None:
"""
Before using any hashed function, you may personalize the hash key used by
dontforget with data of your own. Use this to bust the cache, for example
between deployments of your software, enabling parallel tests to run against
the same cache, or when the internals of your classes have changed in such
a way as to make unpickling unsafe.
:param custom_hash_data: up to 16 bytes of data which will be used to personalize
the hash function.
"""
global _custom_hash_data
if len(custom_hash_data) > 16:
raise ValueError(
"custom_hash_data too large to be used for hash personalization"
)
_custom_hash_data = custom_hash_data
def set_storage_directory(new_cache_root: Path) -> None:
"""
:param new_cache_root: choose a new storage location for dontforget's data.
"""
global _cache_root
_cache_root = Path(new_cache_root)
def cached(func: Callable) -> Callable:
"""
Function decorator that caches the results of invocations to the local file system.
:param func: The function to cache must take only hashable arguments,
or dictionaries with hashable keys and values. The function's output
must be pickleable.
"""
global _CACHED_ABSENT_MARKER
makedirs(_cache_root, exist_ok=True)
@wraps(func)
def cached_func(*args, **kwargs):
key = _cache_key_from(func, *args, **kwargs)
cached_value = _lookup_in_cache(key)
if cached_value is _CACHED_ABSENT_MARKER:
return None
elif cached_value is not None:
return cached_value
loaded_value = func(*args, **kwargs)
_put_in_cache(key, loaded_value)
return loaded_value
return cached_func
_cache_root = Path.cwd() / ".dontforget-cache"
_CACHED_ABSENT_MARKER = object()
class UnrecognizedCacheEncodingException(RuntimeError):
pass
_custom_hash_data = b"dontforget" + __version__.encode("utf-8")
def _cache_key_from(func, *args, **kwargs) -> str:
h = blake2b(digest_size=32, person=_custom_hash_data)
h.update(func.__name__.encode("utf-8"))
h.update(func.__code__.co_code)
h.update(str(func.__code__.co_consts).encode("utf-8"))
h.update(str(func.__defaults__).encode("utf-8"))
h.update(str(func.__kwdefaults__).encode("utf-8"))
for a in args:
a_as_bytes = f"{hash(a)}".encode("utf-8")
h.update(a_as_bytes)
for k, v in kwargs.items():
k_as_bytes = f"{hash(k)}".encode("utf-8")
h.update(k_as_bytes)
v_as_bytes = f"{hash(v)}".encode("utf-8")
h.update(v_as_bytes)
return f"{func.__name__}-{h.hexdigest()}"
def _encode(data) -> Tuple[Optional[bytes], Optional[str]]:
if data is None:
return None, None
if type(data) == str:
return data.encode("utf-8"), "str/utf-8"
if type(data) in (dict, list):
try:
return json.dumps(data).encode("utf-8"), "json/utf-8"
except ValueError:
pass
return pickle.dumps(data), "pickle"
def _decode(data, format) -> Any:
if format == "str/utf-8":
return data.decode("utf-8")
if format == "json/utf-8":
return json.loads(data.decode("utf-8"))
if format == "pickle":
return pickle.loads(data)
else:
raise UnrecognizedCacheEncodingException(format)
def _put_in_cache(key, value) -> None:
if value is not None:
encoded_data, data_format = _encode(value)
data_to_cache: Optional[bytes] = gzip.compress(encoded_data, 9)
assert data_to_cache is not None # for mypy
absent_marker = 0
if len(data_to_cache) < 4000:
contents_for_db: Optional[bytes] = data_to_cache
path_to_file = None
else:
contents_for_db = None
path_to_file = f"{key}.gz"
with open(_cache_root / path_to_file, "wb") as f:
f.write(data_to_cache)
else:
data_format = None
data_to_cache = None
contents_for_db = None
path_to_file = None
absent_marker = 1
with sqlite3.connect(str(_cache_root / "index.db")) as conn:
conn.execute(
"""CREATE TABLE IF NOT EXISTS objects """
"""(func_hash TEXT PRIMARY KEY, path TEXT, content BLOB, format TEXT, absent INT)"""
)
conn.execute(
"""INSERT INTO objects VALUES (?, ?, ?, ?, ?)""",
(key, path_to_file, contents_for_db, data_format, absent_marker),
)
def _lookup_in_cache(key) -> Any:
with sqlite3.connect(str(_cache_root / "index.db")) as conn:
cursor = conn.cursor()
try:
cursor.execute(
"""SELECT path, content, format, absent FROM objects WHERE func_hash = ?""",
(key,),
)
except sqlite3.OperationalError:
return None
result = cursor.fetchone()
if result is None:
return
path, content, format, absent = result
if absent == 1:
return _CACHED_ABSENT_MARKER
if content is None:
assert path, "Found entry in db without content but also without path"
with open(path, "rb") as content_f:
content = content_f.read()
decompressed = gzip.decompress(content)
decoded = _decode(decompressed, format)
return decoded
```
#### File: jelford/dontforget/test_dontforget.py
```python
import pytest # type: ignore
from pathlib import Path
import dontforget as df
from string import ascii_letters
import random
@pytest.yield_fixture(scope="function")
def tmpdir_dontforget(tmpdir):
df.set_storage_directory(str(tmpdir))
df.set_hash_customization(bytearray(random.getrandbits(8) for _ in range(16)))
yield df
def test_does_not_repeat_function_call_with_same_arguments(tmpdir_dontforget, mocker):
m = mocker.Mock()
@tmpdir_dontforget.cached
def function(n):
m.call()
return 42
assert function(5) == 42
assert function(5) == 42
m.call.assert_called_once()
def test_does_not_repeat_function_that_returns_none(tmpdir_dontforget, mocker):
m = mocker.Mock()
@tmpdir_dontforget.cached
def function():
m.call()
return None
assert function() is None
assert function() is None
m.call.assert_called_once()
def test_change_of_hash_seed_is_encorporated_into_the_key(tmpdir_dontforget, mocker):
m = mocker.Mock()
@tmpdir_dontforget.cached
def function():
m.call()
return None
assert function() is None
tmpdir_dontforget.set_hash_customization(b"newseed")
assert function() is None
assert (
len(m.method_calls) == 2
), "Expected function() to be called again after changing the hash customization"
def test_saves_large_objects_out_to_separate_files(tmpdir_dontforget):
@tmpdir_dontforget.cached
def func_with_long_return():
# A string with a high degree of entropy; compression won't be very effective
return "".join(random.choice(ascii_letters) for _ in range(10000))
func_with_long_return()
assert (
len([l for l in Path(tmpdir_dontforget._cache_root).iterdir()]) > 1
), "Expected a large return value to be spilled to disk"
def test_compresses_data_before_saving_out(tmpdir_dontforget):
@tmpdir_dontforget.cached
def func_with_long_return():
# A string with a low degree of entropy; compression will be very effective
return "a" * 10000
func_with_long_return()
assert (
len([l for l in Path(tmpdir_dontforget._cache_root).iterdir()]) == 1
), "Expected a return value that compresses well to become small"
def test_same_function_reloaded_retains_cache_key(tmpdir_dontforget, mocker):
m = mocker.Mock()
function_definition = "\n".join(
(
"@dontforget.cached",
"def func():",
" m.call()",
" return 42",
"",
"func()",
)
)
exec(function_definition, {"m": m, "dontforget": tmpdir_dontforget})
exec(function_definition, {"m": m, "dontforget": tmpdir_dontforget})
m.call.assert_called_once()
def test_function_body_change_busts_cache(tmpdir_dontforget, mocker):
m = mocker.Mock()
function_definition = "\n".join(
(
"@dontforget.cached",
"def func():",
" m.call()",
" return 42",
"",
"func()",
)
)
def run(body):
exec(body, {"m": m, "dontforget": tmpdir_dontforget})
run(function_definition)
run(function_definition.replace("42", "43"))
assert (
len(m.method_calls) == 2
), "Expected func() to require re-evaluation after a constant changed"
run(function_definition.replace("return 42", "i=42\n return 42"))
assert (
len(m.method_calls) == 3
), "Expected func() to require re-evaluation after the function body changed"
run(function_definition.replace("def func():", "def func(foo=1):"))
assert (
len(m.method_calls) == 4
), "Expected func() to require re-evaluation after the default args changed"
run(function_definition.replace("def func():", "def func(*, foo=1):"))
assert (
len(m.method_calls) == 5
), "Expected func() to require re-evaluation after the default keyword-only args"
```
|
{
"source": "jelford/webwatcher",
"score": 3
}
|
#### File: src/webwatcher/main.py
```python
from typing import Collection
from datetime import datetime, timezone
import functools
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from typing import Iterable, Optional
import docopt
import requests
from requests.exceptions import ConnectionError
from webwatcher.diffa import Diffa
from webwatcher.observation import PageObservation, Screenshot
from webwatcher.screenshotter import Screenshotter
from webwatcher.storage import Storage
from webwatcher.temporarystorage import temporary_storage
from webwatcher.webfetcher import WebFetcher
from webwatcher.watchconfiguration import \
PageUnderObsevation, watched_pages, print_config_template
def get_previous_observation(storage: Storage, page: PageUnderObsevation) \
-> Optional[PageObservation]:
persisted_data = storage.find(url=page.url) \
.having('timestamp') \
.order_by('timestamp',
desc=True) \
.fetch()
if not persisted_data:
return None
else:
persisted_data = persisted_data[0]
screenshot_content_hash = persisted_data['screenshot_content']
if screenshot_content_hash is not None:
screenshot : Optional[Screenshot] = Screenshot(content_hash=screenshot_content_hash)
else:
screenshot = None
return PageObservation(
url=persisted_data['url'],
observation_time=persisted_data['timestamp'],
availability=persisted_data['was_available'],
screenshot=screenshot,
raw_content_location=persisted_data.fetch_local('raw_content')
)
class Observer:
def __init__(self, screenshotter, webfetcher):
self.screenshotter = screenshotter
self.webfetcher = webfetcher
def observe(self, page: PageUnderObsevation) -> PageObservation:
was_available, raw_content = self.webfetcher.fetch(page.url)
screenshot = self.screenshotter.take_screenshot_of(page.url)
return PageObservation(
url=page.url,
observation_time=datetime.now(timezone.utc),
availability=was_available,
screenshot=screenshot,
raw_content_location=raw_content)
def _raise_first(errors: Iterable[Exception]):
for e in errors:
raise e
def observe_the_web(
diffa: Diffa,
storage: Storage,
watcher: Observer,
under_observation: Iterable[PageUnderObsevation]) -> None:
diffs = dict()
errors = dict()
for page in under_observation:
try:
observation = watcher.observe(page)
previous_observation = get_previous_observation(storage, page)
diff = diffa.diff(observation, previous_observation)
if diff:
diffs[page.url] = diff
storage.persist(observation)
except Exception as ex:
errors[page.url] = ex
for url, diff in diffs.items():
print('Differences in {url}'.format(url=url))
for k, v in diff.differences().items():
print('\t{k}: {v}'.format(**locals()))
if errors:
print('Errors:')
for url, e in errors.items():
print('While inspecting', url)
print('\t {type} {args}'.format(type=type(e), args=e.args))
_raise_first(errors.values())
def run_web_watcher(config_file) -> None:
with temporary_storage() as temp_storage:
diffa = Diffa()
storage = Storage()
screenshotter = Screenshotter(temp_storage)
fetcher = WebFetcher(temp_storage)
watcher = Observer(screenshotter, fetcher)
under_observation = watched_pages(config_file)
if under_observation is None:
sys.exit(1)
observe_the_web(
diffa,
storage,
watcher,
under_observation)
def main() -> None:
args = docopt.docopt(__doc__)
if args['--show-config-template']:
print_config_template()
sys.exit(0)
else:
run_web_watcher(config_file=args['--config'])
if __name__ == '__main__':
main()
```
#### File: src/webwatcher/observation.py
```python
from datetime import datetime
class Screenshot:
def __init__(self, content_hash, content_path=None):
self.content_hash = content_hash
self.content_path = content_path
def __hash__(self):
return hash(self.content_hash)
def __eq__(self, other):
try:
return self.content_hash == other.content_hash
except AttributeError:
return False
def __str__(self):
return 'Screenshot{{hash={hash}}}'.format(hash=self.content_hash)
class PageObservation:
def __init__(self,
url: str,
observation_time: datetime,
availability: bool,
screenshot,
raw_content_location: str) -> None:
self.url = url
self.observation_time = observation_time
self.availability = availability
self.screenshot = screenshot
self.raw_content_location = raw_content_location
def artefacts(self):
artefacts = dict()
if self.screenshot is not None:
artefacts['screenshot'] = self.screenshot.content_path
if self.raw_content_location is not None:
artefacts['raw_content'] = self.raw_content_location
return artefacts
def get_meta_info(self):
meta = {
'type': 'observation',
'url': self.url,
'timestamp': self.observation_time,
'was_available': self.availability,
}
if self.screenshot:
meta['screenshot_content'] = self.screenshot.content_hash
return meta
```
#### File: src/webwatcher/screenshotter.py
```python
import functools
import logging
import os
import re
import shutil
import subprocess
import tarfile
from typing import Optional
import requests
from webwatcher.environment import cache_folder
from webwatcher.filehash import file_hash
from webwatcher.http_session import http_session
from webwatcher.observation import Screenshot
_FIREFOX_BETA_DOWNLOAD_URL = \
'https://ftp.mozilla.org/pub/firefox/releases/' \
'57.0b14/linux-x86_64/en-US/firefox-57.0b14.tar.bz2'
_FIREFOX_BETA_DOWNLOAD_HASH = \
'772c307edcbdab9ba9bf652c44b69b6c014b831f28cf91a958de67ea6d42ba5f'
def _call_quietly(args, timeout) -> None:
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
stdout, stderr = p.communicate(input=None, timeout=timeout)
except subprocess.TimeoutExpired:
p.kill()
raise
if p.returncode != 0:
raise subprocess.CalledProcessError(
p.returncode,
args,
stdout,
stderr)
class Screenshotter:
def __init__(self, temp_storage):
self._temp = temp_storage
def take_screenshot_of(self, url: str) -> Optional[Screenshot]:
output = self._temp.new_file(leave_open=False, suffix='.png')
ff_path = _path_to_modern_firefox()
with self._temp.new_folder() as profile_dir:
try:
args = [
ff_path,
'--screenshot',
output.name,
url,
'--no-remote',
'--profile',
profile_dir
]
_call_quietly(args, timeout=2)
except subprocess.TimeoutExpired:
return None
except:
logging.warn('Error while calling to firefox at: {}', ff_path)
raise
return Screenshot(
content_hash=file_hash(output.name).hexdigest(),
content_path=output.name)
def _download_firefox_package():
firefox_extraction_path = cache_folder('firefox')
extracted_firefox_bin = firefox_extraction_path / 'firefox' / 'firefox'
if extracted_firefox_bin.is_file():
if os.access(extracted_firefox_bin, os.X_OK):
return extracted_firefox_bin
download_cache_dir = cache_folder('downloads')
try:
os.makedirs(download_cache_dir)
except FileExistsError:
pass
download_path = download_cache_dir / 'firefox.tar.bz2'
if download_path.exists():
downloaded_hash = file_hash(download_path).hexdigest()
need_to_download = downloaded_hash != _FIREFOX_BETA_DOWNLOAD_HASH
else:
logging.debug('Need to download firefox as the following'
'arent present or dont hash right:',
download_path, extracted_firefox_bin)
need_to_download = True
if need_to_download:
firefox_download_url = os.getenv('FIREFOX_DOWNLOAD_URL') or \
_FIREFOX_BETA_DOWNLOAD_URL
with open(download_path, 'wb') as download_file:
with http_session.get(firefox_download_url, stream=True) as r:
shutil.copyfileobj(r.raw, download_file)
downloaded_package = tarfile.open(name=download_path, mode='r:bz2')
downloaded_package.extractall(path=firefox_extraction_path)
return extracted_firefox_bin
@functools.lru_cache()
def _path_to_modern_firefox() -> str:
ff_path = shutil.which('firefox')
if ff_path:
try:
version_text = \
subprocess.check_output([ff_path, '--version'], timeout=1)
except:
pass
else:
vnumber = re.search(b'Mozilla Firefox ([\.\d]+)', version_text)
if vnumber:
version = vnumber.group(1)
parsed_version_info = version.split(b'.')
if parsed_version_info >= [b'57', b'0']:
return ff_path
return _download_firefox_package()
```
#### File: tests/storage/test_persistence.py
```python
from pathlib import Path
from mocking import MockPersistable
def test_empty_thing_can_persist(local_storage):
storage = local_storage
to_persist = MockPersistable()
assert storage.find().fetch() == []
storage.persist(to_persist)
assert len(storage.find().fetch()) == 1
def test_can_retrieve_thing_from_storage(local_storage, tmpdir):
storage = local_storage
artefact = tmpdir.join('some_file')
artefact.write('sample_data')
to_persist = MockPersistable(
artefacts={
'some_file': str(artefact)
}
)
assert storage.find().fetch() == []
storage.persist(to_persist)
retreived = storage.find().fetch()[0]
assert Path(retreived.fetch_local('some_file')).exists()
```
|
{
"source": "jelgun/networkx",
"score": 3
}
|
#### File: networkx/generators/spectral_graph_forge.py
```python
import networkx as nx
from networkx.utils import np_random_state
__all__ = ["spectral_graph_forge"]
def _mat_spect_approx(A, level, sorteigs=True, reverse=False, absolute=True):
"""Returns the low-rank approximation of the given matrix A
Parameters
----------
A : 2D numpy array
level : integer
It represents the fixed rank for the output approximation matrix
sorteigs : boolean
Whether eigenvectors should be sorted according to their associated
eigenvalues before removing the firsts of them
reverse : boolean
Whether eigenvectors list should be reversed before removing the firsts
of them
absolute : boolean
Whether eigenvectors should be sorted considering the absolute values
of the corresponding eigenvalues
Returns
-------
B : 2D numpy array
low-rank approximation of A
Notes
-----
Low-rank matrix approximation is about finding a fixed rank matrix close
enough to the input one with respect to a given norm (distance).
In the case of real symmetric input matrix and euclidean distance, the best
low-rank approximation is given by the sum of first eigenvector matrices.
References
----------
.. [1] <NAME> and <NAME>, The approximation of one matrix by another
of lower rank
.. [2] <NAME>, Symmetric gauge functions and unitarily invariant norms
"""
import numpy as np
d, V = np.linalg.eigh(A)
d = np.ravel(d)
n = len(d)
if sorteigs:
if absolute:
k = np.argsort(np.abs(d))
else:
k = np.argsort(d)
# ordered from the lowest to the highest
else:
k = range(n)
if not reverse:
k = np.flipud(k)
z = np.zeros(n)
for i in range(level, n):
V[:, k[i]] = z
B = V @ np.diag(d) @ V.T
return B
@np_random_state(3)
def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
"""Returns a random simple graph with spectrum resembling that of `G`
This algorithm, called Spectral Graph Forge (SGF), computes the
eigenvectors of a given graph adjacency matrix, filters them and
builds a random graph with a similar eigenstructure.
SGF has been proved to be particularly useful for synthesizing
realistic social networks and it can also be used to anonymize
graph sensitive data.
Parameters
----------
G : Graph
alpha : float
Ratio representing the percentage of eigenvectors of G to consider,
values in [0,1].
transformation : string, optional
Represents the intended matrix linear transformation, possible values
are 'identity' and 'modularity'
seed : integer, random_state, or None (default)
Indicator of numpy random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
H : Graph
A graph with a similar eigenvector structure of the input one.
Raises
------
NetworkXError
If transformation has a value different from 'identity' or 'modularity'
Notes
-----
Spectral Graph Forge (SGF) generates a random simple graph resembling the
global properties of the given one.
It leverages the low-rank approximation of the associated adjacency matrix
driven by the *alpha* precision parameter.
SGF preserves the number of nodes of the input graph and their ordering.
This way, nodes of output graphs resemble the properties of the input one
and attributes can be directly mapped.
It considers the graph adjacency matrices which can optionally be
transformed to other symmetric real matrices (currently transformation
options include *identity* and *modularity*).
The *modularity* transformation, in the sense of Newman's modularity matrix
allows the focusing on community structure related properties of the graph.
SGF applies a low-rank approximation whose fixed rank is computed from the
ratio *alpha* of the input graph adjacency matrix dimension.
This step performs a filtering on the input eigenvectors similar to the low
pass filtering common in telecommunications.
The filtered values (after truncation) are used as input to a Bernoulli
sampling for constructing a random adjacency matrix.
References
----------
.. [1] <NAME>, <NAME>, <NAME>opoulou, "Spectral Graph Forge:
Graph Generation Targeting Modularity", IEEE Infocom, '18.
https://arxiv.org/abs/1801.01715
.. [2] <NAME>, "Networks: an introduction", Oxford university press,
2010
Examples
--------
>>> G = nx.karate_club_graph()
>>> H = nx.spectral_graph_forge(G, 0.3)
>>>
"""
import numpy as np
from scipy import stats
available_transformations = ["identity", "modularity"]
alpha = np.clip(alpha, 0, 1)
A = nx.to_numpy_array(G)
n = A.shape[1]
level = int(round(n * alpha))
if transformation not in available_transformations:
msg = f"'{transformation}' is not a valid transformation. "
msg += f"Transformations: {available_transformations}"
raise nx.NetworkXError(msg)
K = np.ones((1, n)) @ A
B = A
if transformation == "modularity":
B -= K.T @ K / K.sum()
B = _mat_spect_approx(B, level, sorteigs=True, absolute=True)
if transformation == "modularity":
B += K.T @ K / K.sum()
B = np.clip(B, 0, 1)
np.fill_diagonal(B, 0)
for i in range(n - 1):
B[i, i + 1 :] = stats.bernoulli.rvs(B[i, i + 1 :], random_state=seed)
B[i + 1 :, i] = np.transpose(B[i, i + 1 :])
H = nx.from_numpy_array(B)
return H
```
|
{
"source": "jelias1/MDML_Client",
"score": 3
}
|
#### File: MDML_Client/benchmarking/system_timing.py
```python
import time
import json
import numpy as np
import cv2
from base64 import b64encode
import mdml_client as mdml # pip install mdml_client #
print("****************************************************************************")
print("*** This example publish an image 10 times a second for 30 seconds. ***")
print("*** Press Ctrl+C to stop the example. ***")
print("****************************************************************************")
time.sleep(5)
# Approved experiment ID (supplied by MDML administrators - will not work otherwise)
Exp_ID = 'TEST'
# MDML message broker host
host = 'merfpoc.egs.anl.gov'
# MDML username and password
username = 'test'
password = '<PASSWORD>'
# Create MDML experiment
My_MDML_Exp = mdml.experiment(Exp_ID, username, password, host)
# Receive events about your experiment from MDML
def user_func(msg):
msg_obj = json.loads(msg)
if msg_obj['type'] == "NOTE":
print(f'MDML NOTE: {msg_obj["message"]}')
elif msg_obj['type'] == "ERROR":
print(f'MDML ERROR: {msg_obj["message"]}')
elif msg_obj['type'] == "RESULTS":
print(f'MDML ANALYSIS RESULT FOR "{msg_obj["analysis_id"]}": {msg_obj["message"]}')
else:
print("ERROR WITHIN MDML, CONTACT ADMINS.")
My_MDML_Exp.set_debug_callback(user_func)
My_MDML_Exp.start_debugger()
# Sleep to let debugger thread set up
time.sleep(1)
# Add and validate a configuration for the experiment
My_MDML_Exp.add_config('./examples_config.json', 'mdml_examples')
# Send configuration file to the MDML
My_MDML_Exp.send_config() # this starts the experiment
# Sleep to let MDML ingest the configuration
time.sleep(2)
reset = False
try:
i = 0
while True:
while i < 15000:
if i < 1000:
# Generating random images
random_image = np.random.randint(255, size=(50,50,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.1)
elif i < 2000:
# Generating random images
random_image = np.random.randint(255, size=(100,200,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.1)
elif i < 3000:
# Generating random images
random_image = np.random.randint(255, size=(200,200,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.1)
elif i < 4000:
# Generating random images
random_image = np.random.randint(255, size=(200,400,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.5)
elif i < 5000:
# Generating random images
random_image = np.random.randint(255, size=(400,400,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.5)
elif i < 6000:
# Generating random images
random_image = np.random.randint(255, size=(400,800,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 7000:
# Generating random images
random_image = np.random.randint(255, size=(800,800,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 8000:
# Generating random images
random_image = np.random.randint(255, size=(800,1600,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 9000:
# Generating random images
random_image = np.random.randint(255, size=(1600,1600,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 10000:
# Generating random images
random_image = np.random.randint(255, size=(400,500,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 11000:
# Generating random images
random_image = np.random.randint(255, size=(400,500,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1)
elif i < 12000:
# Generating random images
random_image = np.random.randint(255, size=(400,500,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1.5)
elif i < 13000:
# Generating random images
random_image = np.random.randint(255, size=(400,500,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(1.5)
elif i < 14000:
# Generating random images
random_image = np.random.randint(255, size=(50,100,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.1)
elif i < 15000:
# Generating random images
random_image = np.random.randint(255, size=(100,100,3), dtype=np.uint8)
_, img = cv2.imencode('.jpg', random_image)
img_bytes = img.tobytes()
img_b64bytes = b64encode(img_bytes)
img_byte_string = img_b64bytes.decode('utf-8')
# Publish image
My_MDML_Exp.publish_image('IMAGE', img_byte_string, 'random_image_' + str(i) + '.JPG', 0)
time.sleep(.1)
i += 1
if not reset:
print("Ending MDML experiment")
My_MDML_Exp.reset()
reset = True
except KeyboardInterrupt:
if not reset:
My_MDML_Exp.reset()
My_MDML_Exp.stop_debugger()
```
#### File: jelias1/MDML_Client/labview_client.py
```python
import mdml_client as mdml
EXPERIMENT_SESSION = 0
def lv_MDML_connect(userdata):
global EXPERIMENT_SESSION
for i in range(len(userdata)):
dat = userdata[i]
if not isinstance(dat, str):
userdata[i] = dat.decode('utf-8')
experiment_id = userdata[0].upper()
username = userdata[1]
password = <PASSWORD>]
host = userdata[3]
EXPERIMENT_SESSION = mdml.experiment(experiment_id, username, password, host)
def lv_send_config(filepath):
global EXPERIMENT_SESSION
if not isinstance(filepath, str):
filepath = filepath.decode('utf-8')
EXPERIMENT_SESSION.add_config(filepath)
EXPERIMENT_SESSION.send_config()
def lv_publish_data(device_id, data):
global EXPERIMENT_SESSION
if not isinstance(device_id, str):
device_id = device_id.decode('utf-8')
data = [d.decode('utf-8') for d in data]
data = '\t'.join(data)
EXPERIMENT_SESSION.publish_data(device_id, data, '\t', True)
print("hello labview")
return data
def lv_MDML_disconnect():
global EXPERIMENT_SESSION
EXPERIMENT_SESSION.reset()
```
#### File: MDML_Client/tutorials/streaming_analysis.py
```python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--host", help="MDML instance host",
required=True)
parser.add_argument("--username", help="MDML username",
required=True)
parser.add_argument("--password", help="MDML password",
required=True)
parser.add_argument("--register", help="register the function with FuncX",
action="store_true")
parser.add_argument("--run",
choices=['local', 'funcx', 'mdml'],
help="Run the function in 1 of three ways: 'local', 'funcx', or 'mdml'.")
args = parser.parse_args()
### FIRST, YOUR FUNCX FUNCTION MUST BE CREATED AND THEN REGISTERED. ###
def basic_analysis(params):
import mdml_client as mdml
# Connect to the MDML to query for data
exp = mdml.experiment(params['experiment_id'], params['user'], params['pass'], params['host'])
# Grabbing the latest temperature value
query = [{
"device": "DATA1",
"variables": ["temperature"],
"last": 1
}]
res = exp.query(query, verify_cert=False) # Running the query
tempF = res['DATA1'][0]['temperature']
tempC = (tempF-32)*(5/9)
return {'time': mdml.unix_time(True), 'tempC': tempC}
# Registering the function
if args.register:
from funcx.sdk.client import FuncXClient
fxc = FuncXClient()
funcx_func_uuid = fxc.register_function(basic_analysis,
description="Temperature conversion")
print(f'funcX UUID: {funcx_func_uuid}')
else: # Use the most recent function funcx ID (manually put here after running --register once)
funcx_func_uuid = "1712a2fc-cc40-4b2c-ae44-405d58f78c5d" # Sept 16th 2020
# Now that the function is ready for use, we need to start an experiment to use it with
import sys
import time
sys.path.insert(1, '../') # using local mdml_client
import mdml_client as mdml
exp = mdml.experiment("TEST", args.username, args.password, args.host)
exp.add_config(auto=True)
exp.send_config()
time.sleep(1)
# Send some data to analyze
data = {'time': mdml.unix_time(True), 'temperature': 212, 'humidity':58, 'note': 'Temperature and humidity values'}
exp.publish_data(device_id = "DATA1", data = data, add_device = True)
# Now, run the analysis
# Define function parameters
params = {
'experiment_id': 'TEST',
'user': args.username,
'pass': <PASSWORD>,
'host': args.host
# Other function specific params here.
}
funcx_endp_id = "a62a830a-5cd1-42a8-a4a8-a44fa552c899" # merf.egs.anl.gov endpoint
# Running the function locally only
if args.run == 'local':
basic_analysis(params)
# Use funcX to run the function
elif args.run == 'funcx':
if not args.register:
from funcx.sdk.client import FuncXClient
fxc = FuncXClient()
task_id = fxc.run(params, endpoint_id=funcx_endp_id, function_id=funcx_func_uuid)
import time
print("Sleeping for the computation.")
time.sleep(2)
result = fxc.get_result(task_id)
print(result)
# Use funcX through MDML to run the function
elif args.run == 'mdml':
exp.globus_login()
exp.publish_analysis('TEMP_ANALYSIS', funcx_func_uuid, funcx_endp_id, params, trigger=['DATA1']) # Change the analysis device ID
time.sleep(4)
data = {'time': mdml.unix_time(True), 'temperature': 32, 'humidity':59, 'note': 'Temperature and humidity values'}
exp.publish_data(device_id = "DATA1", data = data)
try:
print("Entering infinite loop... Crtl+C to exit and end the experiment.")
while True:
time.sleep(10)
except KeyboardInterrupt:
print("Quitting...")
finally:
print("Reseting...")
exp.reset()
time.sleep(1)
print("Disconnecting...")
exp.disconnect()
```
|
{
"source": "jeliason/isv_neuroscience",
"score": 2
}
|
#### File: jeliason/isv_neuroscience/sp_connectome.py
```python
import nest
import numpy
from itertools import izip
from helper import *
from mpi4py import MPI
import ast
import datetime
class VirtualConnectome:
def __init__(self):
'''
Simulation parameters
'''
self.comm = MPI.COMM_WORLD
self.rank = self.comm.Get_rank()
assert(nest.Rank() == self.rank)
# simulation step (ms).
self.dt = 0.1
self.number_excitatory_neurons = 32
self.number_inhibitory_neurons = 8
self.regions = 68
# Structural_plasticity properties
self.update_interval = 1000
self.record_interval = 1000.0
# rate of background Poisson input
self.bg_rate = 11900.0 #From Deco's paper 2014
self.neuron_model = 'iaf_psc_exp'
self.G = 0.5
# Connectivity data
self.connectivity_filename = 'connectivity_sample.txt'
self.regions_filename = 'regions_sample.txt'
'''
All neurons should have the same homoeostatic rules.
We want the excitatory populations to fire around 3.06Hz
From literature, the desired firing rate of the inhibitory populations should be between 8Hz and 15Hz...
'''
# Inhibitory synaptic elements of excitatory neurons
self.growth_curve_e_i = {
'growth_curve': "gaussian",
'growth_rate': -0.01, # (elements/ms)
'continuous': False,
'eta': -3.0, # Hz
'eps': 3.0, # Hz
}
# Inhibitory synaptic elements of inhibitory neurons
self.growth_curve_i_i = {
'growth_curve': "gaussian",
'growth_rate': -0.01, # (elements/ms)
'continuous': False,
'eta': -8.0, # Hz
'eps': -7.0, # Hz
}
'''
Now we specify the neuron model from Deco 2014
'''
self.model_params_ex = {'tau_m': 20.0, # membrane time constant (ms)
'tau_syn_ex': 2, # excitatory synaptic time constant (ms)
'tau_syn_in': 10, # inhibitory synaptic time constant (ms)
't_ref': 2.0, # absolute refractory period (ms)
'E_L': -70.0, # resting membrane potential (mV)
'V_th': -50.0, # spike threshold (mV)
'C_m': 500.0, # membrane capacitance (pF)
'V_reset': -55.0, # reset potential (mV)
}
self.model_params_in = {'tau_m': 25.0, # membrane time constant (ms)
'tau_syn_ex': 2, # excitatory synaptic time constant (ms)
'tau_syn_in': 10, # inhibitory synaptic time constant (ms)
't_ref': 1.0, # absolute refractory period (ms)
'E_L': -70.0, # resting membrane potential (mV)
'V_th': -50.0, # spike threshold (mV)
'C_m': 200.0, # membrane capacitance (pF)
'V_reset': -55.0, # reset potential (mV)
}
self.nodes_e = [None] * self.regions
self.nodes_i = [None] * self.regions
self.loc_e = [[] for i in range(self.regions)]
self.loc_i = [[] for i in range(self.regions)]
# Create a list to store mean values
if nest.Rank() == 0:
self.mean_fr_e = [[] for i in range(self.regions)]
self.mean_fr_i = [[] for i in range(self.regions)]
self.total_connections_e = [None] * self.regions#[[] for i in range(self.regions)]
self.total_connections_i = [None] * self.regions#[[] for i in range(self.regions)]
self.last_connections_msg = None
'''
We initialize variables for the post-synaptic currents of the excitatory, inhibitory and
external synapses. These values were calculated from a PSP amplitude of 1 for excitatory
synapses, -1 for inhibitory synapses and 0.11 for external synapses.
'''
self.psc_e = 585.0
self.psc_i = -585.0
self.psc_ext = 0.62
self.setup_nett()
def setup_nett(self):
'''
Only needs to happen on rank 0 in MPI setup
'''
if nest.Rank() == 0:
try: #nett already initialized?
nett.initialize('tcp://127.0.0.1:8000') #2000
except RuntimeError:
pass
self.fr_e_slot_out = nett.slot_out_float_vector_message('fr_e')
self.fr_i_slot_out = nett.slot_out_float_vector_message('fr_i')
self.total_connections_slot_out = nett.slot_out_float_vector_message('total_connections')
self.num_regions_slot_out = nett.slot_out_float_message('num_regions')
self.run_slot_in = nett.slot_in_float_message()
self.quit_slot_in = nett.slot_in_float_message()
self.pause_slot_in = nett.slot_in_float_message()
self.update_interval_slot_in = nett.slot_in_float_message()
self.save_slot_in = nett.slot_in_float_message()
self.quit_slot_in.connect('tcp://127.0.0.1:2003', 'quit')
self.pause_slot_in.connect('tcp://127.0.0.1:2003', 'pause')
self.update_interval_slot_in.connect('tcp://127.0.0.1:2003', 'update_interval')
self.save_slot_in.connect('tcp://127.0.0.1:2003', 'save')
self.observe_quit_slot = observe_slot(self.quit_slot_in, float_message())
self.observe_quit_slot.start()
self.observe_pause_slot = observe_slot(self.pause_slot_in, float_message())
self.observe_pause_slot.start()
self.observe_update_interval_slot = observe_slot(self.update_interval_slot_in, float_message())
self.observe_update_interval_slot.start()
self.observe_save_slot = observe_slot(self.save_slot_in, float_message())
self.observe_save_slot.start()
self.observe_growth_rate_slot = observe_growth_rate_slot(self.regions)
self.observe_growth_rate_slot.start()
self.observe_eta_slot = observe_eta_slot(self.regions)
self.observe_eta_slot.start()
def prepare_simulation(self):
nest.ResetKernel()
nest.set_verbosity('M_ERROR')
nest.SetKernelStatus(
{
'resolution': self.dt
}
)
'''
Set Structural Plasticity synaptic update interval
'''
nest.SetStructuralPlasticityStatus({
'structural_plasticity_update_interval': self.update_interval,
})
'''
Set Number of virtual processes. Remember SP does not work well with openMP right now, so calls must always be done using mpiexec
'''
nest.SetKernelStatus({'total_num_virtual_procs': 8})
#nest.SetKernelStatus({'total_num_virtual_procs': 1})
'''
Now we define Structural Plasticity synapses. One for the inner inhibition of each region and one
static synaptic model for the DTI obtained connectivity data.
'''
spsyn_names=['synapse_in'+str(nam) for nam in range(self.regions)]
nest.CopyModel('static_synapse', 'synapse_ex')
nest.SetDefaults('synapse_ex', {'weight': self.psc_e*10, 'delay': 1.0})
sps = {}
for x in range(0,self.regions) :
nest.CopyModel('static_synapse', 'synapse_in'+str(x))
nest.SetDefaults('synapse_in'+str(x), {'weight': self.psc_i*1000, 'delay': 1.0})
sps[spsyn_names[x]]= {
'model': 'synapse_in'+str(x),
'post_synaptic_element': 'Den_in'+str(x),
'pre_synaptic_element': 'Axon_in'+str(x),
}
nest.SetStructuralPlasticityStatus({'structural_plasticity_synapses': sps})
def create_nodes(self):
'''
We define the synaptic elements. We have no excitatory synaptic elements, only inhibitory.
Then we create n populations of ex and inh neurons which represent n regions of the brain.
'''
synaptic_elements_e = {}
synaptic_elements_i = {}
for x in range(0,self.regions) :
synaptic_elements_e = {
'Den_in'+str(x): self.growth_curve_e_i,
}
synaptic_elements_i = {
'Axon_in'+str(x): self.growth_curve_i_i,
}
self.nodes_e[x] = nest.Create('iaf_psc_alpha', self.number_excitatory_neurons, {
'synaptic_elements': synaptic_elements_e
})
self.nodes_i[x] = nest.Create('iaf_psc_alpha', self.number_inhibitory_neurons, {
'synaptic_elements': synaptic_elements_i
})
self.loc_e[x] = [stat['global_id'] for stat in nest.GetStatus(self.nodes_e[x]) if stat['local']]
self.loc_i[x] = [stat['global_id'] for stat in nest.GetStatus(self.nodes_i[x]) if stat['local']]
def connect_external_input(self):
'''
We create and connect the Poisson generator for external input. It is not very clear which values should be used here... Need to read more on this
'''
noise = nest.Create('poisson_generator')
nest.SetStatus(noise, {"rate": self.bg_rate})
for x in range(0,self.regions) :
nest.Connect(noise, self.nodes_e[x], 'all_to_all', {'weight': self.psc_ext*8.42, 'delay': 1.0})
nest.Connect(noise, self.nodes_i[x], 'all_to_all', {'weight': self.psc_ext*8.7, 'delay': 1.0}) #*1.7
nest.Connect(self.nodes_e[x], self.nodes_e[x], 'all_to_all', {'weight': self.psc_ext, 'delay': 1.0})
def connect_inter_region(self):
'''
We load the connectivity data from the experimental file and apply this values to the network connections among regions
'''
print "loading: "+ self.connectivity_filename
linecounter = 0
numbercounter = 0
target = 0
num_sources = 0
source = 0
cap = 0.0
with open(self.connectivity_filename, 'r+') as input_file:
with open(self.regions_filename, 'r+') as input_file_reg:
for line, line_reg in izip(input_file, input_file_reg):
line = line.strip()
line_reg = line_reg.strip()
if linecounter !=0:
if linecounter % 2 == 1: #Read target region id and number of incoming sources
numbercounter = 0
for number in line.split():
if numbercounter == 0:
target = int(number)
else:
num_sources = int(number)
numbercounter = numbercounter +1
else: #Read cap values
for number, srs in izip(line.split(),line_reg.split()) :
source = int(srs)
cap = float(number)*self.G
nest.Connect(self.nodes_e[source], self.nodes_e[target], 'all_to_all', {'weight': cap*100, 'delay': 1.0}) #10000 # cap*100
linecounter = linecounter +1
def get_num_regions(self):
return self.regions
def record_fr(self):
if nest.Rank() == 0:
msg_fr_e = float_vector_message()
msg_fr_i = float_vector_message()
for x in range(0,self.regions) :
fr_e = nest.GetStatus(self.loc_e[x], 'fr'), # Firing rate
fr_e = self.comm.gather(fr_e, root=0)
fr_i = nest.GetStatus(self.loc_i[x], 'fr'), # Firing rate
fr_i = self.comm.gather(fr_i, root=0)
if nest.Rank() == 0:
mean = numpy.mean(list(fr_e))
#print mean
self.mean_fr_e[x].append(mean)
msg_fr_e.value.append(mean)
mean = numpy.mean(list(fr_i))
self.mean_fr_i[x].append(mean)
msg_fr_i.value.append(mean)
if nest.Rank() == 0:
self.fr_e_slot_out.send(msg_fr_e.SerializeToString())
self.fr_i_slot_out.send(msg_fr_i.SerializeToString())
def record_connectivity(self):
if nest.Rank() == 0:
msg = float_vector_message()
print nest.GetConnections(self.nodes_i[0], self.nodes_e[0])
for x in range(0,self.regions) :
syn_elems_e = nest.GetStatus(self.loc_e[x], 'synaptic_elements')
syn_elems_i = nest.GetStatus(self.loc_i[x], 'synaptic_elements')
sum_neurons = sum(neuron['Axon_in'+str(x)]['z_connected'] for neuron in syn_elems_i)
sum_neurons = self.comm.gather(sum_neurons, root=0)
if nest.Rank() == 0:
self.total_connections_i[x] = (sum(sum_neurons))
msg.value.append(sum(sum_neurons))
if nest.Rank() == 0:
self.last_connections_msg = msg
self.total_connections_slot_out.send(msg.SerializeToString())
def simulate(self):
self.update_update_interval()
nest.SetStructuralPlasticityStatus({'structural_plasticity_update_interval': self.update_interval, })
self.update_growth_rate()
self.update_eta()
if nest.Rank()==0:
print ("Start")
nest.Simulate(self.record_interval)
if nest.Rank()==0:
print ("End")
self.record_fr()
self.record_connectivity()
def update_update_interval(self):
if nest.Rank() == 0:
self.update_interval= int(self.observe_update_interval_slot.msg.value)
else:
self.update_interval=0
self.update_interval = self.comm.bcast(self.update_interval, root=0)
#sanity check
if self.update_interval == 0:
self.update_interval = 1000
def update_growth_rate(self):
if nest.Rank() == 0:
growth_rate_dict = self.observe_growth_rate_slot.growth_rate_dict
else:
growth_rate_dict = 0
growth_rate_dict = self.comm.bcast(growth_rate_dict, root=0)
print growth_rate_dict
for x in range(0, self.regions) :
synaptic_elements_e = { 'growth_rate': growth_rate_dict[x], }
nest.SetStatus(self.nodes_e[x], 'synaptic_elements_param', {'Den_in'+str(x):synaptic_elements_e})
nest.SetStatus(self.nodes_i[x], 'synaptic_elements_param', {'Axon_in'+str(x):synaptic_elements_e})
def update_eta(self):
if nest.Rank() == 0:
eta_dict = self.observe_eta_slot.eta_dict
else:
eta_dict = 0
eta_dict = self.comm.bcast(eta_dict, root=0)
for x in range(0, self.regions) :
synaptic_elements_e = { 'eta': eta_dict[x], }
nest.SetStatus(self.nodes_e[x], 'synaptic_elements_param', {'Den_in'+str(x):synaptic_elements_e})
nest.SetStatus(self.nodes_i[x], 'synaptic_elements_param', {'Axon_in'+str(x):synaptic_elements_e})
def send_num_regions(self):
#send out number of regions in each iteration
msg = float_message()
msg.value = self.get_num_regions()
self.num_regions_slot_out.send(msg.SerializeToString())
def get_quit_state(self):
if nest.Rank() == 0:
quit_state = self.observe_quit_slot.state
else:
quit_state = False
quit_state = self.comm.bcast(quit_state, root=0)
return quit_state
def get_save_state(self):
save_state = False
if nest.Rank() != 0:
return
if self.observe_save_slot.state == True:
self.observe_save_slot.set_state(False)#make it true upon next receive msg in this slot
save_state = True
return save_state
def get_pause_state(self):
if nest.Rank() == 0:
pause_state = self.observe_pause_slot.state
else:
pause_state = False
pause_state = self.comm.bcast(pause_state, root=0)
return pause_state
def store_connectivity(self, timestamp):
f = open('connectivity_' + str(timestamp) +'.bin', "wb")
for x in range(0,self.regions) :
connections = nest.GetStatus(nest.GetConnections(self.loc_e[x]))
f.write(str(connections))
f.close()
def store_current_connections(self, timestamp):
f = open('current_connectivity_'+ str(timestamp) +'.bin', "wb")
f.write(str(self.total_connections_i))
f.close()
def store_sp_status(self, timestamp):
f = open('sp_status_'+ str(timestamp) +'.bin', "wb")
status = nest.GetStructuralPlasticityStatus({})
f.write(str(status))
f.close()
def save_state(self):
if nest.Rank() != 0:
return
print 'saving state to disk'
time_stamp = str(datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) #take time stamp only once for all files to make it unique
update_interval = self.update_interval
growth_rate = self.observe_growth_rate_slot.growth_rate_dict
eta_state = self.observe_eta_slot.eta_dict
f = open('update_interval_'+ str(time_stamp) +'.bin', "wb")
f.write(str(update_interval))
f.close()
f = open('growth_rate_'+ str(time_stamp) +'.bin', "wb")
f.write(str(growth_rate))
f.close()
f = open('eta_state_'+ str(time_stamp) +'.bin', "wb")
f.write(str(eta_state))
f.close()
self.store_connectivity(time_stamp)
self.store_current_connections(time_stamp)
self.store_sp_status(time_stamp)
print 'saving done'
def load_sp_state(self):
if nest.Rank() != 0:
return
f = open('sp_status_.bin', 'r')
var = f.read()
print str(var)
status = ast.literal_eval(var)
nest.SetStructuralPlasticityStatus(status)
f.close()
def run():
vc = VirtualConnectome()
vc.prepare_simulation()
vc.create_nodes()
vc.connect_external_input()
vc.connect_inter_region()
nest.EnableStructuralPlasticity()
if nest.Rank() == 0:
vc.send_num_regions()
while vc.get_quit_state() == False:
while vc.get_pause_state() == False:
vc.simulate()
if nest.Rank() == 0:
print 'iteration done'
if vc.get_save_state() == True:
vc.save_state()
if __name__ == '__main__':
run()
print 'simulation ended'
```
|
{
"source": "jelic98/c_compiler",
"score": 3
}
|
#### File: c_compiler/src/nodes.py
```python
class Node():
pass
class Program(Node):
def __init__(self, nodes):
self.nodes = nodes
class Decl(Node):
def __init__(self, type_, id_):
self.type_ = type_
self.id_ = id_
class ArrayDecl(Node):
def __init__(self, type_, id_, size, elems):
self.type_ = type_
self.id_ = id_
self.size = size
self.elems = elems
class ArrayElem(Node):
def __init__(self, id_, index):
self.id_ = id_
self.index = index
class Assign(Node):
def __init__(self, id_, expr):
self.id_ = id_
self.expr = expr
class If(Node):
def __init__(self, cond, true, false):
self.cond = cond
self.true = true
self.false = false
class While(Node):
def __init__(self, cond, block):
self.cond = cond
self.block = block
class For(Node):
def __init__(self, init, cond, step, block):
self.init = init
self.cond = cond
self.step = step
self.block = block
class FuncImpl(Node):
def __init__(self, type_, id_, params, block):
self.type_ = type_
self.id_ = id_
self.params = params
self.block = block
class FuncCall(Node):
def __init__(self, id_, args):
self.id_ = id_
self.args = args
class Block(Node):
def __init__(self, nodes):
self.nodes = nodes
class Params(Node):
def __init__(self, params):
self.params = params
class Args(Node):
def __init__(self, args):
self.args = args
class Elems(Node):
def __init__(self, elems):
self.elems = elems
class Break(Node):
pass
class Continue(Node):
pass
class Return(Node):
def __init__(self, expr):
self.expr = expr
class Type(Node):
def __init__(self, value):
self.value = value
class Int(Node):
def __init__(self, value):
self.value = value
class Char(Node):
def __init__(self, value):
self.value = value
class String(Node):
def __init__(self, value):
self.value = value
class Id(Node):
def __init__(self, value):
self.value = value
class BinOp(Node):
def __init__(self, symbol, first, second):
self.symbol = symbol
self.first = first
self.second = second
class UnOp(Node):
def __init__(self, symbol, first):
self.symbol = symbol
self.first = first
```
#### File: c_compiler/src/optimizer.py
```python
from src.visitor import Visitor
class Optimizer(Visitor):
def __init__(self, ast):
self.ast = ast
self.global_ = None
self.local = []
self.remove_unused_symbols = False
self.remove_current_symbol = False
self.trash = []
def remove_symbol(self, parent, node):
if self.remove_unused_symbols:
self.visit(node, node.id_)
if self.remove_current_symbol:
self.trash.append((parent, node))
def visit_Program(self, parent, node):
self.global_ = node.symbols
for n in node.nodes:
self.visit(node, n)
self.remove_unused_symbols = True
for n in node.nodes:
self.visit(node, n)
for parent, node in self.trash:
parent.nodes.remove(node)
def visit_Decl(self, parent, node):
self.remove_symbol(parent, node)
def visit_ArrayDecl(self, parent, node):
self.remove_symbol(parent, node)
if node.size is not None:
self.visit(node, node.size)
if node.elems is not None:
self.visit(node, node.elems)
def visit_ArrayElem(self, parent, node):
self.visit(node, node.id_)
self.visit(node, node.index)
def visit_Assign(self, parent, node):
self.visit(node, node.id_)
self.visit(node, node.expr)
def visit_If(self, parent, node):
self.visit(node, node.cond)
self.visit(node, node.true)
if node.false is not None:
self.visit(node, node.false)
def visit_While(self, parent, node):
self.visit(node, node.cond)
self.visit(node, node.block)
def visit_For(self, parent, node):
self.visit(node, node.init)
self.visit(node, node.cond)
self.visit(node, node.block)
self.visit(node, node.step)
def visit_FuncImpl(self, parent, node):
self.remove_symbol(parent, node)
self.visit(node, node.block)
def visit_FuncCall(self, parent, node):
self.visit(node, node.id_)
self.visit(node, node.args)
def visit_Block(self, parent, node):
self.local.append(node.symbols)
for n in node.nodes:
self.visit(node, n)
self.local.pop()
def visit_Params(self, parent, node):
pass
def visit_Args(self, parent, node):
for a in node.args:
self.visit(node, a)
def visit_Elems(self, parent, node):
for e in node.elems:
self.visit(node, e)
def visit_Break(self, parent, node):
pass
def visit_Continue(self, parent, node):
pass
def visit_Return(self, parent, node):
if node.expr is not None:
self.visit(node, node.expr)
def visit_Type(self, parent, node):
pass
def visit_Int(self, parent, node):
pass
def visit_Char(self, parent, node):
pass
def visit_String(self, parent, node):
pass
def visit_Id(self, parent, node):
id_ = node.value
symbols = self.global_
for scope in reversed(self.local):
if scope.contains(id_):
symbols = scope
break
if symbols.contains(id_):
symbol = symbols.get(id_)
if self.remove_unused_symbols:
self.remove_current_symbol = False
if not hasattr(symbol, 'used') and id_ != 'main':
self.remove_current_symbol = True
symbols.remove(id_)
else:
symbol.used = None
def visit_BinOp(self, parent, node):
self.visit(node, node.first)
self.visit(node, node.second)
def visit_UnOp(self, parent, node):
self.visit(node, node.first)
def optimize(self):
self.visit(None, self.ast)
```
#### File: c_compiler/src/parser.py
```python
from src.token import Class
from src.nodes import *
from functools import wraps
import pickle
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.curr = tokens.pop(0)
self.prev = None
def restorable(call):
@wraps(call)
def wrapper(self, *args, **kwargs):
state = pickle.dumps(self.__dict__)
result = call(self, *args, **kwargs)
self.__dict__ = pickle.loads(state)
return result
return wrapper
def eat(self, class_):
if self.curr.class_ == class_:
self.prev = self.curr
self.curr = self.tokens.pop(0)
else:
self.die_type(class_.name, self.curr.class_.name)
def program(self):
nodes = []
while self.curr.class_ != Class.EOF:
if self.curr.class_ == Class.TYPE:
nodes.append(self.decl())
else:
self.die_deriv(self.program.__name__)
return Program(nodes)
def id_(self):
is_array_elem = self.prev.class_ != Class.TYPE
id_ = Id(self.curr.lexeme)
self.eat(Class.ID)
if self.curr.class_ == Class.LPAREN and self.is_func_call():
self.eat(Class.LPAREN)
args = self.args()
self.eat(Class.RPAREN)
return FuncCall(id_, args)
elif self.curr.class_ == Class.LBRACKET and is_array_elem:
self.eat(Class.LBRACKET)
index = self.expr()
self.eat(Class.RBRACKET)
id_ = ArrayElem(id_, index)
if self.curr.class_ == Class.ASSIGN:
self.eat(Class.ASSIGN)
expr = self.expr()
return Assign(id_, expr)
else:
return id_
def decl(self):
type_ = self.type_()
id_ = self.id_()
if self.curr.class_ == Class.LBRACKET:
self.eat(Class.LBRACKET)
size = None
if self.curr.class_ != Class.RBRACKET:
size = self.expr()
self.eat(Class.RBRACKET)
elems = None
if self.curr.class_ == Class.ASSIGN:
self.eat(Class.ASSIGN)
self.eat(Class.LBRACE)
elems = self.elems()
self.eat(Class.RBRACE)
self.eat(Class.SEMICOLON)
return ArrayDecl(type_, id_, size, elems)
elif self.curr.class_ == Class.LPAREN:
self.eat(Class.LPAREN)
params = self.params()
self.eat(Class.RPAREN)
self.eat(Class.LBRACE)
block = self.block()
self.eat(Class.RBRACE)
return FuncImpl(type_, id_, params, block)
else:
self.eat(Class.SEMICOLON)
return Decl(type_, id_)
def if_(self):
self.eat(Class.IF)
self.eat(Class.LPAREN)
cond = self.logic()
self.eat(Class.RPAREN)
self.eat(Class.LBRACE)
true = self.block()
self.eat(Class.RBRACE)
false = None
if self.curr.class_ == Class.ELSE:
self.eat(Class.ELSE)
self.eat(Class.LBRACE)
false = self.block()
self.eat(Class.RBRACE)
return If(cond, true, false)
def while_(self):
self.eat(Class.WHILE)
self.eat(Class.LPAREN)
cond = self.logic()
self.eat(Class.RPAREN)
self.eat(Class.LBRACE)
block = self.block()
self.eat(Class.RBRACE)
return While(cond, block)
def for_(self):
self.eat(Class.FOR)
self.eat(Class.LPAREN)
init = self.id_()
self.eat(Class.SEMICOLON)
cond = self.logic()
self.eat(Class.SEMICOLON)
step = self.id_()
self.eat(Class.RPAREN)
self.eat(Class.LBRACE)
block = self.block()
self.eat(Class.RBRACE)
return For(init, cond, step, block)
def block(self):
nodes = []
while self.curr.class_ != Class.RBRACE:
if self.curr.class_ == Class.IF:
nodes.append(self.if_())
elif self.curr.class_ == Class.WHILE:
nodes.append(self.while_())
elif self.curr.class_ == Class.FOR:
nodes.append(self.for_())
elif self.curr.class_ == Class.BREAK:
nodes.append(self.break_())
elif self.curr.class_ == Class.CONTINUE:
nodes.append(self.continue_())
elif self.curr.class_ == Class.RETURN:
nodes.append(self.return_())
elif self.curr.class_ == Class.TYPE:
nodes.append(self.decl())
elif self.curr.class_ == Class.ID:
nodes.append(self.id_())
self.eat(Class.SEMICOLON)
else:
self.die_deriv(self.block.__name__)
return Block(nodes)
def params(self):
params = []
while self.curr.class_ != Class.RPAREN:
if len(params) > 0:
self.eat(Class.COMMA)
type_ = self.type_()
id_ = self.id_()
params.append(Decl(type_, id_))
return Params(params)
def args(self):
args = []
while self.curr.class_ != Class.RPAREN:
if len(args) > 0:
self.eat(Class.COMMA)
args.append(self.expr())
return Args(args)
def elems(self):
elems = []
while self.curr.class_ != Class.RBRACE:
if len(elems) > 0:
self.eat(Class.COMMA)
elems.append(self.expr())
return Elems(elems)
def return_(self):
self.eat(Class.RETURN)
expr = self.expr()
self.eat(Class.SEMICOLON)
return Return(expr)
def break_(self):
self.eat(Class.BREAK)
self.eat(Class.SEMICOLON)
return Break()
def continue_(self):
self.eat(Class.CONTINUE)
self.eat(Class.SEMICOLON)
return Continue()
def type_(self):
type_ = Type(self.curr.lexeme)
self.eat(Class.TYPE)
return type_
def factor(self):
if self.curr.class_ == Class.INT:
value = Int(self.curr.lexeme)
self.eat(Class.INT)
return value
elif self.curr.class_ == Class.CHAR:
value = Char(self.curr.lexeme)
self.eat(Class.CHAR)
return value
elif self.curr.class_ == Class.STRING:
value = String(self.curr.lexeme)
self.eat(Class.STRING)
return value
elif self.curr.class_ == Class.ID:
return self.id_()
elif self.curr.class_ in [Class.MINUS, Class.NOT, Class.ADDRESS]:
op = self.curr
self.eat(self.curr.class_)
first = None
if self.curr.class_ == Class.LPAREN:
self.eat(Class.LPAREN)
first = self.logic()
self.eat(Class.RPAREN)
else:
first = self.factor()
return UnOp(op.lexeme, first)
elif self.curr.class_ == Class.LPAREN:
self.eat(Class.LPAREN)
first = self.logic()
self.eat(Class.RPAREN)
return first
elif self.curr.class_ == Class.SEMICOLON:
return None
else:
self.die_deriv(self.factor.__name__)
def term(self):
first = self.factor()
while self.curr.class_ in [Class.STAR, Class.FWDSLASH, Class.PERCENT]:
if self.curr.class_ == Class.STAR:
op = self.curr.lexeme
self.eat(Class.STAR)
second = self.factor()
first = BinOp(op, first, second)
elif self.curr.class_ == Class.FWDSLASH:
op = self.curr.lexeme
self.eat(Class.FWDSLASH)
second = self.factor()
first = BinOp(op, first, second)
elif self.curr.class_ == Class.PERCENT:
op = self.curr.lexeme
self.eat(Class.PERCENT)
second = self.factor()
first = BinOp(op, first, second)
return first
def expr(self):
first = self.term()
while self.curr.class_ in [Class.PLUS, Class.MINUS]:
if self.curr.class_ == Class.PLUS:
op = self.curr.lexeme
self.eat(Class.PLUS)
second = self.term()
first = BinOp(op, first, second)
elif self.curr.class_ == Class.MINUS:
op = self.curr.lexeme
self.eat(Class.MINUS)
second = self.term()
first = BinOp(op, first, second)
return first
def compare(self):
first = self.expr()
if self.curr.class_ == Class.EQ:
op = self.curr.lexeme
self.eat(Class.EQ)
second = self.expr()
return BinOp(op, first, second)
elif self.curr.class_ == Class.NEQ:
op = self.curr.lexeme
self.eat(Class.NEQ)
second = self.expr()
return BinOp(op, first, second)
elif self.curr.class_ == Class.LT:
op = self.curr.lexeme
self.eat(Class.LT)
second = self.expr()
return BinOp(op, first, second)
elif self.curr.class_ == Class.GT:
op = self.curr.lexeme
self.eat(Class.GT)
second = self.expr()
return BinOp(op, first, second)
elif self.curr.class_ == Class.LTE:
op = self.curr.lexeme
self.eat(Class.LTE)
second = self.expr()
return BinOp(op, first, second)
elif self.curr.class_ == Class.GTE:
op = self.curr.lexeme
self.eat(Class.GTE)
second = self.expr()
return BinOp(op, first, second)
else:
return first
def logic_term(self):
first = self.compare()
while self.curr.class_ == Class.AND:
op = self.curr.lexeme
self.eat(Class.AND)
second = self.compare()
first = BinOp(op, first, second)
return first
def logic(self):
first = self.logic_term()
while self.curr.class_ == Class.OR:
op = self.curr.lexeme
self.eat(Class.OR)
second = self.logic_term()
first = BinOp(op, first, second)
return first
@restorable
def is_func_call(self):
try:
self.eat(Class.LPAREN)
self.args()
self.eat(Class.RPAREN)
return self.curr.class_ != Class.LBRACE
except:
return False
def parse(self):
return self.program()
def die(self, text):
raise SystemExit(text)
def die_deriv(self, fun):
self.die("Derivation error: {}".format(fun))
def die_type(self, expected, found):
self.die("Expected: {}, Found: {}".format(expected, found))
```
#### File: c_compiler/src/runner.py
```python
from src.visitor import Visitor
from src.symbols import Symbol
from src.nodes import *
import re
class Runner(Visitor):
def __init__(self, ast):
self.ast = ast
self.global_ = {}
self.local = {}
self.scope = {}
self.call_stack = []
self.search_new_call = True
self.return_ = False
def get_symbol(self, node):
recursion = self.is_recursion()
ref_call = -2 if not self.search_new_call else -1
ref_scope = -2 if recursion and not self.search_new_call else -1
id_ = node.value
if len(self.call_stack) > 0:
fun = self.call_stack[ref_call]
for scope in reversed(self.scope[fun]):
if scope in self.local:
curr_scope = self.local[scope][ref_scope]
if id_ in curr_scope:
return curr_scope[id_]
return self.global_[id_]
def init_scope(self, node):
fun = self.call_stack[-1]
if fun not in self.scope:
self.scope[fun] = []
scope = id(node)
if scope not in self.local:
self.local[scope] = []
self.local[scope].append({})
for s in node.symbols:
self.local[scope][-1][s.id_] = s.copy()
def clear_scope(self, node):
scope = id(node)
self.local[scope].pop()
def is_recursion(self):
if len(self.call_stack) > 0:
curr_call = self.call_stack[-1]
prev_calls = self.call_stack[:-1]
for call in reversed(prev_calls):
if call == curr_call:
return True
return False
def visit_Program(self, parent, node):
for s in node.symbols:
self.global_[s.id_] = s.copy()
for n in node.nodes:
self.visit(node, n)
def visit_Decl(self, parent, node):
id_ = self.get_symbol(node.id_)
id_.value = None
def visit_ArrayDecl(self, parent, node):
id_ = self.get_symbol(node.id_)
id_.symbols = node.symbols
size, elems = node.size, node.elems
if elems is not None:
self.visit(node, elems)
elif size is not None:
for i in range(size.value):
id_.symbols.put(i, id_.type_, None)
id_.symbols.get(i).value = None
def visit_ArrayElem(self, parent, node):
id_ = self.get_symbol(node.id_)
index = self.visit(node, node.index)
return id_.symbols.get(index.value)
def visit_Assign(self, parent, node):
id_ = self.visit(node, node.id_)
value = self.visit(node, node.expr)
if isinstance(value, Symbol):
value = value.value
id_.value = value
def visit_If(self, parent, node):
cond = self.visit(node, node.cond)
if cond:
self.init_scope(node.true)
self.visit(node, node.true)
self.clear_scope(node.true)
else:
if node.false is not None:
self.init_scope(node.false)
self.visit(node, node.false)
self.clear_scope(node.false)
def visit_While(self, parent, node):
cond = self.visit(node, node.cond)
while cond:
self.init_scope(node.block)
self.visit(node, node.block)
self.clear_scope(node.block)
cond = self.visit(node, node.cond)
def visit_For(self, parent, node):
self.visit(node, node.init)
cond = self.visit(node, node.cond)
while cond:
self.init_scope(node.block)
self.visit(node, node.block)
self.clear_scope(node.block)
self.visit(node, node.step)
cond = self.visit(node, node.cond)
def visit_FuncImpl(self, parent, node):
id_ = self.get_symbol(node.id_)
id_.params = node.params
id_.block = node.block
if node.id_.value == 'main':
self.call_stack.append(node.id_.value)
self.init_scope(node.block)
self.visit(node, node.block)
self.clear_scope(node.block)
self.call_stack.pop()
def visit_FuncCall(self, parent, node):
func = node.id_.value
args = node.args.args
if func == 'printf':
format_ = args[0].value
format_ = format_.replace('\\n', '\n')
for a in args[1:]:
if isinstance(a, Int):
format_ = format_.replace('%d', a.value, 1)
elif isinstance(a, Char):
format_ = format_.replace('%c', chr(a.value), 1)
elif isinstance(a, String):
format_ = format_.replace('%s', a.value, 1)
elif isinstance(a, Id) or isinstance(a, ArrayElem):
id_ = self.visit(node.args, a)
if hasattr(id_, 'symbols') and id_.type_ == 'char':
elems = id_.symbols
ints = [s.value for s in elems]
non_nulls = [i for i in ints if i is not None]
chars = [chr(i) for i in non_nulls]
value = ''.join(chars)
else:
value = id_.value
if id_.type_ == 'char':
value = chr(value)
format_ = re.sub('%[dcs]', str(value), format_, 1)
else:
value = self.visit(node.args, a)
format_ = re.sub('%[dcs]', str(value), format_, 1)
print(format_, end='')
elif func == 'scanf':
format_ = args[0].value
inputs = input().split()
matches = re.findall('%[dcs]', format_)
for i, m in enumerate(matches):
id_ = self.visit(node.args, args[i + 1])
if m == '%d':
id_.value = int(inputs[i])
elif m == '%c':
id_.value = ord(inputs[i][0])
elif m == '%s':
word = inputs[i]
length = len(id_.symbols)
for c in word:
id_.symbols.put(length, id_.type_, None)
id_.symbols.get(length).value = ord(c)
length += 1
elif func == 'strlen':
a = args[0]
if isinstance(a, String):
return len(a.value)
elif isinstance(a, Id):
id_ = self.visit(node.args, a)
return len(id_.symbols)
elif func == 'strcat':
a, b = args[0], args[1]
dest = self.get_symbol(a)
values = []
if isinstance(b, Id):
src = self.get_symbol(b)
elems = [s.value for s in src.symbols]
non_nulls = [c for c in elems if c is not None]
values = [c for c in non_nulls]
elif isinstance(b, String):
values = [ord(c) for c in b.value]
i = len(dest.symbols)
for v in values:
dest.symbols.put(i, dest.type_, None)
dest.symbols.get(i).value = v
i += 1
else:
impl = self.global_[func]
self.call_stack.append(func)
self.init_scope(impl.block)
self.visit(node, node.args)
result = self.visit(node, impl.block)
self.clear_scope(impl.block)
self.call_stack.pop()
self.return_ = False
return result
def visit_Block(self, parent, node):
result = None
scope = id(node)
fun = self.call_stack[-1]
self.scope[fun].append(scope)
if len(self.local[scope]) > 5:
exit(0)
for n in node.nodes:
if self.return_:
break
if isinstance(n, Break):
break
elif isinstance(n, Continue):
continue
elif isinstance(n, Return):
self.return_ = True
if n.expr is not None:
result = self.visit(n, n.expr)
else:
self.visit(node, n)
self.scope[fun].pop()
return result
def visit_Params(self, parent, node):
pass
def visit_Args(self, parent, node):
fun_parent = self.call_stack[-2]
impl = self.global_[fun_parent]
self.search_new_call = False
args = [self.visit(impl.block, a) for a in node.args]
args = [a.value if isinstance(a, Symbol) else a for a in args]
fun_child = self.call_stack[-1]
impl = self.global_[fun_child]
scope = id(impl.block)
self.scope[fun_child].append(scope)
self.search_new_call = True
for p, a in zip(impl.params.params, args):
id_ = self.visit(impl.block, p.id_)
id_.value = a
self.scope[fun_child].pop()
def visit_Elems(self, parent, node):
id_ = self.get_symbol(parent.id_)
for i, e in enumerate(node.elems):
value = self.visit(node, e)
id_.symbols.put(i, id_.type_, None)
id_.symbols.get(i).value = value
def visit_Break(self, parent, node):
pass
def visit_Continue(self, parent, node):
pass
def visit_Return(self, parent, node):
pass
def visit_Type(self, parent, node):
pass
def visit_Int(self, parent, node):
return node.value
def visit_Char(self, parent, node):
return ord(node.value)
def visit_String(self, parent, node):
return node.value
def visit_Id(self, parent, node):
return self.get_symbol(node)
def visit_BinOp(self, parent, node):
first = self.visit(node, node.first)
if isinstance(first, Symbol):
first = first.value
second = self.visit(node, node.second)
if isinstance(second, Symbol):
second = second.value
if node.symbol == '+':
return int(first) + int(second)
elif node.symbol == '-':
return int(first) - int(second)
elif node.symbol == '*':
return int(first) * int(second)
elif node.symbol == '/':
return int(first) / int(second)
elif node.symbol == '%':
return int(first) % int(second)
elif node.symbol == '==':
return first == second
elif node.symbol == '!=':
return first != second
elif node.symbol == '<':
return int(first) < int(second)
elif node.symbol == '>':
return int(first) > int(second)
elif node.symbol == '<=':
return int(first) <= int(second)
elif node.symbol == '>=':
return int(first) >= int(second)
elif node.symbol == '&&':
bool_first = first != 0
bool_second = second != 0
return bool_first and bool_second
elif node.symbol == '||':
bool_first = first != 0
bool_second = second != 0
return bool_first or bool_second
else:
return None
def visit_UnOp(self, parent, node):
first = self.visit(node, node.first)
backup_first = first
if isinstance(first, Symbol):
first = first.value
if node.symbol == '-':
return -first
elif node.symbol == '!':
bool_first = first != 0
return not bool_first
elif node.symbol == '&':
return backup_first
else:
return None
def run(self):
self.visit(None, self.ast)
```
|
{
"source": "jelic98/raf_pg",
"score": 3
}
|
#### File: raf_pg/homework_1/main.py
```python
import numpy as np
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox as mb
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
Style().theme_use('default')
self.master = master
self.master.title("Frequency Spectrum Analyzer")
self.path = StringVar(self, value="data/1.wav")
Label(self, text="Path").grid(row=0, column=0, padx=10, pady=10)
Entry(self, textvariable=self.path).grid(row=0, column=1, padx=10, pady=10)
self.win_size = IntVar(self, value=100)
Label(self, text="Window size (ms)").grid(row=1, column=0, padx=10, pady=10)
Entry(self, textvariable=self.win_size).grid(row=1, column=1, padx=10, pady=10)
self.win_num = IntVar(self, value=1)
Label(self, text="Window number").grid(row=2, column=0, padx=10, pady=10)
Entry(self, textvariable=self.win_num).grid(row=2, column=1, padx=10, pady=10)
self.win_funs = {"Hanning":0, "Hamming":1, "None":2}
self.win_fun = IntVar(self, value=0)
Label(self, text="Windowing").grid(row=3, column=0, padx=10, pady=10)
for i, (k, v) in enumerate(self.win_funs.items()):
Radiobutton(self, variable=self.win_fun, text=k, value=v).grid(row=4, column=i, padx=10, pady=10)
Button(self, command=self.action_load, text="Load WAV").grid(row=5, column=0, padx=10, pady=10)
Button(self, command=self.action_synthesize, text="Synthesize WAV").grid(row=5, column=1, padx=10, pady=10)
Button(self, command=self.action_spectrum, text="Show spectrum").grid(row=6, column=0, padx=10, pady=10)
Button(self, command=self.action_spectrogram, text="Show spectrogram").grid(row=6, column=1, padx=10, pady=10)
self.pack(fill=BOTH, expand=1)
def action_load(self):
# Reading WAV file
raw = wf.read(self.path.get())
self.rate, self.data = raw[0], raw[1]
self.length = len(self.data)
# Endpointing
p, q = 25, 25
dur_noise, dur_window = 0.1, 0.01
n_noise, n_window = int(self.rate * dur_noise), int(self.rate * dur_window)
noise = np.abs(self.data[:n_noise])
lmt = np.mean(noise) + 2 * np.std(noise)
windows = [1 if np.mean(np.abs(self.data[i:i+n_window])) > lmt else 0 for i in range(0, self.length, n_window)]
self.window_replace(windows, 0, 1, p)
i, j = self.window_replace(windows, 1, 0, q)
if j - i < q:
mb.showerror("Error", "Only silence detected")
return
self.data = self.data[i*n_window:j*n_window]
self.length = len(self.data)
# Windowing function
win_funs = [np.hanning, np.hamming, np.ones]
self.data = self.data * win_funs[self.win_fun.get()](self.length)
# Window slicing
win_size, win_num = self.win_size.get(), self.win_num.get()
win_start, win_end = win_size * (win_num - 1), win_size * win_num
self.data = self.data[self.rate*win_start//1000:self.rate*win_end//1000]
self.length = len(self.data)
# Discrete Fourier Transform
self.freq = np.linspace(1000 // (self.length / self.rate), self.rate // 2, self.length)
self.amp = np.abs(np.fft.fft(self.data))
self.amp = np.interp(self.amp, (self.amp.min(), self.amp.max()), (0, 100))
def action_synthesize(self):
path = self.path.get()
length, rate, freqs = 5, 44100, [220, 480, 620]
data, t = np.zeros(rate * length), np.linspace(0, length, rate * length)
for f in freqs:
data = np.add(data, np.sin(f * 2 * np.pi * t))
wf.write(path, rate, data)
def action_spectrum(self):
plt.plot(self.freq, self.amp)
plt.xlabel("Frequency (Hz)")
plt.ylabel("Magnitude (%)")
plt.show()
def action_spectrogram(self):
plt.specgram(self.data, Fs=self.rate)
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
plt.gca().grid(axis='y')
plt.show()
def window_replace(self, arr, curr, repl, occrs):
i, lmt, max_i, max_j = 0, len(arr), -1, -1
if arr[-1] != repl:
arr.append(repl)
lmt -= 1
while i < lmt:
if arr[i] == curr:
j = arr.index(repl, i+1)
if j - i > max_j - max_i:
max_i, max_j = i, j
elif j - i < occrs:
arr[i:j] = [repl] * (j-i)
i = j
i += 1
return max_i, max_j
root = Tk()
root.resizable(False, False)
App(root)
root.mainloop()
```
|
{
"source": "jelic98/raf_pp",
"score": 3
}
|
#### File: interpreter/app/executor.py
```python
from app.type import *
from app.nodes import *
vars = {}
funs = {}
call_stack = []
block_stack = []
types = {
CEO_BROJ: "~ceo_broj",
STRUNA: "~struna",
JESTE_NIJE: "~jeste_nije"
}
class Var:
def __init__(self, tip, naziv):
self.tip = tip
self.naziv = naziv
self.vrednost = None
class Fun:
def __init__(self, tip, naziv, vars, args, sadrzaj):
self.tip = tip
self.naziv = naziv
self.vars = vars
self.args = args
self.sadrzaj = sadrzaj
class NodeVisitor(object):
def visit(self, node):
method_name = 'visit_' + type(node).__name__
visitor = getattr(self, method_name, 'error_method')
return visitor(node)
def error_method(self, node):
raise Exception("Method missing: {}".format('visit_' + type(node).__name__))
class Executor(NodeVisitor):
def __init__(self, parser):
self.parser = parser
def visit_Program(self, node):
for cvor in node.cvorovi:
if isinstance(cvor, Postojanje):
self.visit(cvor)
for cvor in node.cvorovi:
if isinstance(cvor, Rutina):
self.visit(cvor)
for cvor in node.cvorovi:
if isinstance(cvor, Dodela):
self.visit(cvor)
for cvor in node.cvorovi:
if(not isinstance(cvor, Postojanje)
and not isinstance(cvor, Dodela)
and not isinstance(cvor, Rutina)):
self.visit(cvor)
def visit_Postojanje(self, node):
self.add_var(node.tip, node.naziv.naziv)
def visit_Dodela(self, node):
izraz = self.visit(node.izraz)
varijabla = node.varijabla
if izraz is None:
return
if isinstance(varijabla, Naziv):
var = self.get_var(varijabla.naziv)
if var.tip.tip == types[STRUNA] and str(izraz[0]).isdigit():
tokens = izraz.split(" ")
if len(tokens) == 1:
self.set_var(tokens[0], varijabla.naziv)
else:
i = 0
for token in tokens:
self.set_var(token, varijabla.naziv, [i])
i += 1
else:
self.set_var(izraz, varijabla.naziv)
elif isinstance(varijabla, ElementNiza):
self.set_var(izraz, varijabla.naziv.naziv, varijabla.indeksi)
def visit_Polje(self, node):
pass
def visit_Rutina(self, node):
tip = None
if node.tip is not None:
tip = self.visit(node.tip)
naziv = node.naziv.naziv
vars = {}
args = []
for polje in node.polja.cvorovi:
polje_naziv = polje.naziv.naziv
vars[polje_naziv] = Var(polje.tip, polje_naziv)
args.append(polje_naziv)
if naziv in funs:
raise Exception("Funciton {} is already defined".format(naziv))
funs[naziv] = Fun(tip, naziv, vars, args, node.sadrzaj)
def visit_Argumenti(self, node):
args = []
for arg in node.argumenti:
args.append(self.visit(arg))
return args
def visit_RutinaPoziv(self, node):
argumenti = self.visit(node.argumenti)
naziv = node.naziv.naziv
if naziv not in funs:
raise Exception("Funciton {} is not defined".format(naziv))
if len(argumenti) != len(funs[naziv].args):
raise Exception("Calling function {} with {} arguments instead of {}".format(naziv, len(argumenti), len(funs[naziv].args)))
i = 0;
for arg in argumenti:
if((funs[naziv].vars[funs[naziv].args[i]].tip.tip == types[CEO_BROJ]
and not str(arg).isdigit())
or (funs[naziv].vars[funs[naziv].args[i]].tip.tip == types[JESTE_NIJE]
and not arg == "jeste"
and not arg == "nije")
or (funs[naziv].vars[funs[naziv].args[i]].tip.tip == types[STRUNA])
and not isinstance(arg, list)):
raise Exception("Not passing {} to {} function call".format(funs[naziv].vars[funs[naziv].args[i]].tip.tip, naziv))
funs[naziv].vars[funs[naziv].args[i]].vrednost = arg
i += 1
call_stack.append(funs[naziv])
vrednost = self.visit(funs[naziv].sadrzaj)
call_stack.pop()
for (naziv_var, var) in funs[naziv].vars.items():
funs[naziv].vars[naziv_var].vrednost = None
if funs[naziv].vars[naziv_var].tip.tip == types[STRUNA]:
funs[naziv].vars[naziv_var].vrednost = []
return vrednost
def visit_UgradjenaRutinaPoziv(self, node):
argumenti = self.visit(node.argumenti)
naziv = node.naziv.naziv
if naziv == "ucitaj":
return input()
elif naziv == "ispisi":
print(str(argumenti[0]).replace("\\n", "\n"), end="")
elif naziv == "spoji_strune":
s = ""
for arg in node.argumenti.argumenti:
if isinstance(arg, Naziv):
vrednost = vars[arg.naziv].vrednost
if self.get_var(arg.naziv).tip.tip == types[STRUNA]:
for v in vrednost:
s += str(v)
else:
s += str(vrednost)
else:
s += str(self.visit(arg))
return s
elif naziv == "duzina_strune":
return len(argumenti[0])
elif naziv == "podeli_strunu":
return argumenti[0].split(argumenti[1])
else:
raise Exception("Funciton {} is not defined".format(naziv))
return None
def visit_Vrati(self, node):
izraz = node.izraz
if isinstance(izraz, Naziv):
if self.get_var(izraz.naziv).tip.tip != call_stack[-1].tip:
raise Exception("Returning {} instead of {} from {} function call".format(self.get_var(izraz.naziv).tip.tip, call_stack[-1].tip, call_stack[-1].naziv))
izraz = self.get_var(izraz.naziv).vrednost
if((call_stack[-1].tip == types[CEO_BROJ]
and not str(izraz).isdigit())
or (call_stack[-1].tip == types[JESTE_NIJE]
and not izraz == "jeste"
and not izraz == "nije")
or (call_stack[-1].tip == types[STRUNA])
and not isinstance(izraz, list)):
raise Exception("Not returning {} from {} function call".format(call_stack[-1].tip, call_stack[-1].naziv))
return izraz
def visit_PrekiniPonavljanje(self, node):
pass
def visit_NaredbaUslov(self, node):
pitanje = self.visit(node.pitanje)
if pitanje:
self.visit(node.da)
else:
if node.ne != None:
self.visit(node.ne)
def visit_NaredbaPonavljanje(self, node):
pitanje = self.visit(node.pitanje)
while pitanje:
block_stack.append({})
for cvor in node.ponovi.cvorovi:
self.visit(cvor)
if isinstance(node, PrekiniPonavljanje):
return
block_stack.pop()
pitanje = self.visit(node.pitanje)
def visit_CelinaCelina(self, node):
block_stack.append({})
res = None
for cvor in node.cvorovi:
if isinstance(cvor, Vrati):
res = self.visit(cvor)
break
self.visit(cvor)
block_stack.pop()
return res
def visit_CeoBroj(self, node):
return node.broj
def visit_Struna(self, node):
return node.struna
def visit_JesteNije(self, node):
return node.jestenije == "jeste"
def visit_TipPodatka(self, node):
return node.tip
def visit_Naziv(self, node):
return self.get_var(node.naziv).vrednost
def visit_ElementNiza(self, node):
vrednost = self.visit(node.naziv)
for indeks in node.indeksi:
if indeks is not None:
if isinstance(indeks, Naziv):
indeks = int(self.get_var(indeks.naziv).vrednost)
elif isinstance(indeks, AST):
indeks = int(self.visit(indeks))
else:
indeks = int(indeks)
vrednost = vrednost[indeks]
return vrednost
def visit_BinarnaOperacija(self, node):
prvi = self.visit(node.prvi)
drugi = self.visit(node.drugi)
if node.simbol == '+':
return int(prvi) + int(drugi)
elif node.simbol == '-':
return int(prvi) - int(drugi)
elif node.simbol == '*':
return int(prvi) * int(drugi)
elif node.simbol == '/':
return int(prvi) / int(drugi)
elif node.simbol == '%':
return int(prvi) % int(drugi)
elif node.simbol == '<':
return int(prvi) < int(drugi)
elif node.simbol == '>':
return int(prvi) > int(drugi)
elif node.simbol == '<=':
return int(prvi) >= int(drugi)
elif node.simbol == '>=':
return int(prvi) <= int(drugi)
elif node.simbol == '=':
if isinstance(node.prvi, CeoBroj) or isinstance(node.drugi, CeoBroj):
return int(prvi) == int(drugi)
elif isinstance(node.prvi, Struna) or isinstance(node.drugi, Struna):
return prvi == drugi
elif isinstance(node.prvi, JesteNije) or isinstance(node.drugi, JesteNije):
return prvi == drugi
elif node.simbol == '!=':
return int(prvi) != int(drugi)
elif node.simbol == '&&':
return prvi and drugi
elif node.simbol == '||':
return prvi or drugi
return None
def visit_UnarnaOperacija(self, node):
prvi = self.visit(node.prvi)
if node.simbol == '-':
return -prvi
elif node.simbol == '!':
return not prvi
return None
def add_var(self, tip, naziv):
naziv = naziv.lower()
if len(block_stack) > 0:
if naziv in block_stack[-1]:
raise Exception("Variable {} is already defined".format(naziv))
block_stack[-1][naziv] = Var(tip, naziv)
if tip.tip == types[STRUNA]:
block_stack[-1][naziv].vrednost = []
return
if len(call_stack) > 0 and naziv not in call_stack[-1].vars:
call_stack[-1].vars[naziv] = Var(tip, naziv)
if tip.tip == types[STRUNA]:
call_stack[-1].vars[naziv].vrednost = []
elif len(call_stack) == 0 and naziv not in vars:
vars[naziv] = Var(tip, naziv)
if tip.tip == types[STRUNA]:
vars[naziv].vrednost = []
else:
raise Exception("Variable {} is already defined".format(naziv))
def get_var(self, naziv):
naziv = naziv.lower()
for block in reversed(block_stack):
if naziv in block:
return block[naziv]
if len(call_stack) > 0 and naziv in call_stack[-1].vars:
return call_stack[-1].vars[naziv]
elif naziv in vars:
return vars[naziv]
else:
raise Exception("Variable {} is not defined".format(naziv))
def set_var(self, vrednost, naziv, indeksi=None):
naziv = naziv.lower()
for block in reversed(block_stack):
if naziv in block:
if indeksi is None:
block[naziv].vrednost = vrednost
else:
self.set_arr_var(vrednost, block[naziv].vrednost, indeksi)
return
if len(call_stack) > 0 and naziv in call_stack[-1].vars:
if indeksi is None:
call_stack[-1].vars[naziv].vrednost = vrednost
else:
self.set_arr_var(vrednost, call_stack[-1].vars[naziv].vrednost, indeksi)
else:
if indeksi is None:
vars[naziv].vrednost = vrednost
else:
self.set_arr_var(vrednost, vars[naziv].vrednost, indeksi)
def set_arr_var(self, nova, niz, indeksi):
prev_vrednost = None
prev_indeks = None
vrednost = niz
i = 0
for indeks in indeksi:
if indeks is not None:
if isinstance(indeks, Naziv):
indeks = int(self.get_var(indeks.naziv).vrednost)
elif isinstance(indeks, AST):
indeks = int(self.visit(indeks))
else:
indeks = int(indeks)
if vrednost is None:
prev_vrednost[prev_indeks] = []
vrednost = prev_vrednost[prev_indeks]
if indeks >= len(vrednost):
for i in range(indeks - len(vrednost) + 1):
vrednost.append(None)
prev_vrednost = vrednost
prev_indeks = indeks
vrednost = vrednost[indeks]
i += 1
prev_vrednost[prev_indeks] = nova
def log_vars(self):
print("*** GLOBAL SCOPE ***")
for (naziv, var) in vars.items():
print("{} {}={}".format(var.tip.tip, var.naziv, var.vrednost))
if len(call_stack) > 0:
print("*** CALL STACK ***")
for fun in call_stack:
for (naziv, var) in fun.vars.items():
print("{} {}={}".format(var.tip.tip, var.naziv, var.vrednost))
if len(block_stack) > 0:
print("*** BLOCK STACK ***")
for (naziv, var) in block_stack[-1].items():
print("{} {}={}".format(var.tip.tip, var.naziv, var.vrednost))
print("---------- * ----------")
def execute(self):
tree = self.parser.program()
self.visit(tree)
return None
```
|
{
"source": "jelimoore/trbodatasvc",
"score": 2
}
|
#### File: src/TrboDataSvc/ars.py
```python
import socket
from multiprocessing import Process, Value
import TrboDataSvc.util as util
import logging
class ArsConsts():
ARS_ID_MISMATCH = -1
ARS_UNDEF = 0
ARS_HELLO = 1
ARS_BYE = 2
ARS_PING = 3
ARS_PONG = 4
class ArsOpByte():
ARS_HELLO = b'\xf0'
ARS_BYE = b'\x31'
ARS_PING = b'\x74'
ARS_PONG = b'\x3f'
class ARS():
def __init__(self, port=4005):
self._ip = "0.0.0.0"
self._cai = 12
self._port = port
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._process = Process(target=self._listenForIncoming)
self._callback = None
def register_callback(self, callback):
""" Allow callback to be registered """
self._callback = callback
def listen(self):
#start listening on specified UDP port
self._sock.bind((self._ip, self._port))
self._process.start()
#p.join()
def close(self):
logging.info("Closing connection, bye!")
self._sock.close()
self._process.terminate()
def _listenForIncoming(self):
while True:
data, addr = self._sock.recvfrom(1024)
opByte = data[2:3]
ip, port = addr
rid = util.ip2id(ip)
ack_needed = False # do we need to send an ack for the message? let's save air time if we don't need to
messageType = ArsConsts.ARS_UNDEF # initialize the messageType var with an undefined value, use as fallback
if (opByte == ArsOpByte.ARS_BYE): # bye message
#no need for an ack on bye, the radio is going away!
ack_needed = False
messageType = ArsConsts.ARS_BYE
if (opByte == ArsOpByte.ARS_HELLO): # hello message
# let's check that the ID being hello'ed and the sending radio are the same!
#content = dataIn[5:] # strip the header
#arsId = content.replace(b'\x00', b'').decode() # remove trailing nulls
#print("IP ID: {} ARS ID: {}".format(id, arsId))
#if (arsId == id):
# messageType = ArsConsts.ARS_HELLO
#else:
# messageType = ArsConsts.ARS_ID_MISMATCH
messageType = ArsConsts.ARS_HELLO
ack_needed = True
if (opByte == ArsOpByte.ARS_PONG): # pong message
#no ack needed, since this is a response
ack_needed = False
messageType = ArsConsts.ARS_PONG
logging.debug("Got an ARS message from radio {}: {}".format(rid, messageType))
# Send the ack if the callback returns true
if (self._callback(rid, messageType) == True and ack_needed == True):
self._sendAck(rid)
def _sendAck(self, rid):
ackMessage = b'\x00\x02\xbf\x01'
ip = util.id2ip(self._cai, rid)
logging.debug("Sending ARS Ack to {}".format(rid))
self._sock.sendto(ackMessage, (ip, 4005))
def queryRadio(self, rid):
ip = util.id2ip(self._cai, int(rid))
queryMessage = b'\x00\x01\x74'
self._sock.sendto(queryMessage, (ip, 4005))
```
#### File: src/TrboDataSvc/jobticket.py
```python
import socket
from multiprocessing import Process, Value
import TrboDataSvc.util as util
import logging
class JobTicket():
def __init__(self, port=4013):
self._ip = "0.0.0.0"
self._cai = 12
self._port = port
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._callback = None
def register_callback(self, callback):
""" Allow callback to be registered """
self._callback = callback
def listen(self):
#start listening on specified UDP port
self._sock.bind((self._ip, self._port))
#create subprocess for listening so we don't tie up the main thread of whoever called us
p = Process(target=self._listenForIncoming)
p.start()
#p.join()
def _listenForIncoming(self):
while True:
data, addr = self._sock.recvfrom(1024)
ip, port = addr
rid = util.ip2id(self._cai, ip)
logging.debug("Received job ticket data from radio {}: {}".format(rid, data))
# Send the ack if the callback returns true
#if (self._callback(rid, messageType) == True):
# self._sendAck(rid)
```
|
{
"source": "jelinj8/pydPiper",
"score": 3
}
|
#### File: pydPiper/sources/musicdata.py
```python
from __future__ import unicode_literals
import abc,logging,urllib2,contextlib
class musicdata:
__metaclass__ = abc.ABCMeta
# Children of this class will own interacting with the underlying music service
# Must monitor for changes to the players state
# Uses a queue (received from caller) to send any updates that occur
# Will use a thread to receive updates from service.
# Will update musicdata on receipt of new data
# Will send a message over the data queue whenever an update is received
# Will only send keys that have been updated
# May use a thread to issue keyalives to the music service if needed
# Future state
# Will allow command issuance to music service.
musicdata_init = {
'state':u"stop",
'musicdatasource':u"",
'stream':u"",
'actPlayer':u"",
'artist':u"",
'title':u"",
'uri':u"",
'encoding':u"",
'tracktype':u"",
'bitdepth':u"",
'bitrate':u"",
'samplerate':u"",
'elapsed_formatted':u"",
'album':u"",
'elapsed':-1,
'channels':0,
'length':0,
'remaining':u"",
'volume':-1,
'repeat':False,
'single':False,
'random':False,
'playlist_display':u"",
'playlist_position':-1,
'playlist_length':-1,
'my_name':u"", # Volumio 2 only
# Deprecated values
'current':-1,
'duration':-1,
'position':u"",
'playlist_count':-1,
'type':u""
}
varcheck = {
u'unicode':
[
# Player state
u'state',
u'actPlayer',
u'musicdatasource',
# Track information
u'album',
u'artist',
u'title',
u'uri',
u'encoding',
u'tracktype',
u'bitdepth',
u'bitrate',
u'samplerate',
u'elapsed_formatted',
u'remaining',
u'playlist_display',
u'my_name'
],
u'bool':
[
# Player state
u'random',
u'single',
u'repeat'
],
u'int':
[
# Player state
u'volume',
# Track information
u'channels',
u'length',
u'elapsed',
u'playlist_position',
u'playlist_length'
]
}
def __init__(self, q):
self.musicdata = self.musicdata_init.copy()
self.musicdata_prev = self.musicdata.copy()
self.dataqueue = q
def validatemusicvars(self, vars):
for vtype, members in self.varcheck.iteritems():
if vtype == u'unicode':
for v in members:
try:
if type(vars[v]) is unicode:
continue
if type(vars[v]) is None:
vars[v] = u""
elif type(vars[v]) is str:
logging.debug(u"Received string in {0}. Converting to Unicode".format(v))
vars[v] = vars[v].decode()
else:
# This happens so often when playing from webradio that I'm disabling logging for now.
# logging.debug(u"Received non-string type {0} in {1}. Converting to null".format(type(vars[v]),v))
vars[v] = u""
except KeyError:
logging.debug(u"Missing required value {0}. Adding empty version".format(v))
vars[v] = u""
elif vtype == u'bool':
for v in members:
try:
if type(vars[v]) is bool:
continue
if type(vars[v]) is None:
vars[v] = False
elif type(vars[v]) is int:
logging.debug(u"Received integer in {0}. Converting to boolean".format(v))
vars[v] = bool(vars[v])
else:
logging.debug(u"Received non-bool type {0} in {1}. Converting to False".format(type(vars[v]),v))
vars[v] = False
except KeyError:
logging.debug(u"Missing required value {0}. Adding empty version".format(v))
vars[v] = False
elif vtype == u'int':
for v in members:
try:
if type(vars[v]) is int:
continue
if type(vars[v]) is None:
vars[v] = 0
elif type(vars[v]) is bool:
logging.debug(u"Received boolean in {0}. Converting to integer".format(v))
vars[v] = int(vars[v])
else:
logging.debug(u"Received non-integer type {0} in {1}. Converting to 0".format(type(vars[v]),v))
vars[v] = 0
except KeyError:
logging.debug(u"Missing required value {0}. Adding empty version".format(v))
vars[v] = 0
def webradioname(self,url):
# Attempt to get name of webradio station
# Requires station to send name using the M3U protocol
# url - url of the station
# Only check for a radio station name if you are actively playing a track
if self.musicdata[u'state'] != u'play':
return u''
retval = u''
with contextlib.closing(urllib2.urlopen(url)) as page:
cnt = 20
try:
for line in page:
line = line.decode('utf-8')
cnt -= 1
if line.startswith(u'#EXTINF:'):
try:
retval = line.split(u'#EXTINF:')[1].split(',')[1].split(')')[1].strip()
except IndexError:
try:
retval = line.split(u'#EXTINF:')[1].split(',')[0].split(')')[1].strip()
except IndexError:
retval = u''
if retval != u'':
if retval is unicode:
logging.debug(u"Found {0}".format(retval))
return retval
else:
try:
logging.debug(u"Found {0}".format(retval))
return retval.decode()
except:
logging.debug(u"Not sure what I found {0}".format(retval))
return u''
elif line.startswith(u'Title1='):
try:
retval = line.split(u'Title1=')[1].split(':')[1:2][0]
except:
retval = line.split(u'Title1=')[0]
retval = retval.split(u'(')[0].strip()
return retval.decode()
if cnt == 0: break
except:
# Likely got junk data. Skip
pass
logging.debug(u"Didn't find an appropriate header at {0}".format(url))
def sendUpdate(self):
# Figure out what has changed and then send just those values across dataqueue
md = { }
for k, v in self.musicdata.iteritems():
pv = self.musicdata_prev[k] if k in self.musicdata_prev else None
if pv != v:
md[k] = v
# Send md to queue if anything has changed
if len(md) > 0:
# elapsed is special as it needs to be sent to guarantee that the timer gets updated correctly. Even if it hasn't changed, send it anyway
md[u'elapsed'] = self.musicdata[u'elapsed']
md[u'state'] = self.musicdata[u'state']
self.dataqueue.put(md)
# Update musicdata_prev
self.musicdata_prev = self.musicdata.copy()
def intn(self,val):
# A version of int that returns 0 if the value is not convertable
try:
retval = int(val)
except:
retval = 0
return retval
def booln(self,val):
# A version of bool that returns False if the value is not convertable
try:
retval = bool(val)
except:
retval = False
return retval
def floatn(self,val):
# A version of float that returns 0.0 if the value is not convertable
try:
retval = float(val)
except:
retval = 0.0
return retval
def clear(self):
# revert data back to init state
self.musicdata = self.musicdata_init.copy()
@abc.abstractmethod
def run():
# Start thread(s) to monitor music source
# Threads must be run as daemons
# Future state: start thread to issue commands to music source
return
<EMAIL>
#def command(cmd):
# Send command to music service
# Throws NotImplementedError if music service does not support commands
# return
```
#### File: pydPiper/sources/musicdata_rune.py
```python
from __future__ import unicode_literals
import json, redis, threading, logging, Queue, time, getopt, sys, logging
import musicdata
class musicdata_rune(musicdata.musicdata):
def __init__(self, q, server=u'localhost', port=6379, pwd=u''):
super(musicdata_rune, self).__init__(q)
self.server = server
self.port = port
self.pwd = pwd
self.connection_failed = 0
self.dataclient = None
# Now set up a thread to listen to the channel and update our data when
# the channel indicates a relevant key has changed
data_t = threading.Thread(target=self.run)
data_t.daemon = True
data_t.start()
def connect(self):
# Try up to 10 times to connect to REDIS
self.connection_failed = 0
logging.debug(u"Connecting to Rune Redis service on {0}:{1}".format(self.server, self.port))
while True:
if self.connection_failed >= 10:
logging.debug(u"Could not connect to Rune Redis service")
raise RuntimeError(u"Could not connect to Rune Redis service")
try:
# Connection to REDIS
client = redis.StrictRedis(self.server, self.port, self.pwd)
# Configure REDIS to send keyspace messages for set events
client.config_set(u'notify-keyspace-events', u'KEA')
self.dataclient = client
logging.debug(u"Connected to Rune Redis service")
break
except:
self.dataclient = None
self.connection_failed += 1
time.sleep(1)
def subscribe(self):
# Try to subscribe. If you fail, reconnect and try again.
# If you fail, allow the resulting exception to be passed on.
try:
# Create a pubsub to receive messages
self.pubsub = self.dataclient.pubsub(ignore_subscribe_messages=True)
# Subscribe to act_player_info keyspace events
self.pubsub.psubscribe(u'__key*__:act_player_info')
except redis.ConnectionError:
self.connect()
# Try again to subscribe
# Create a pubsub to receive messages
self.pubsub = self.dataclient.pubsub(ignore_subscribe_messages=True)
# Subscribe to act_player_info keyspace events
self.pubsub.subscribe(u'__key*__:act_player_info')
def run(self):
logging.debug(u"RUNE musicdata service starting")
while True:
if self.dataclient is None:
try:
# Try to connect
self.connect()
self.subscribe()
self.status()
self.sendUpdate()
except (redis.ConnectionError, RuntimeError):
self.dataclient = None
# On connection error, sleep 5 and then return to top and try again
time.sleep(5)
continue
try:
# Wait for notice that key has changed
msg = self.pubsub.get_message()
if msg:
# act_player_info key event occured
self.status()
self.sendUpdate()
time.sleep(.01)
except (redis.ConnectionError, RuntimeError):
# if we lose our connection while trying to query DB
# sleep 5 and then return to top to try again
self.dataclient = None
logging.debug(u"Could not get status from Rune Redis service")
time.sleep(5)
continue
def status(self):
# Read musicplayer status and update musicdata
try:
msg = self.dataclient.get(u'act_player_info')
status = json.loads(msg)
except ValueError:
logging.debug(u"Bad status message received. Contents were {0}".format(msg))
raise RuntimeError(u"Bad status message received.")
except:
# Caught something else. Report it and then inform calling function that the connection is bad
e = sys.exc_info()[0]
logging.debug(u"Caught {0} trying to get status from Rune".format(e))
raise RuntimeError(u"Could not get status from Rune")
state = status.get(u'state')
if state != u"play":
self.musicdata[u'state'] = u"stop"
else:
self.musicdata[u'state'] = u"play"
# Update remaining variables
self.musicdata[u'artist'] = status[u'currentartist'] if u'currentartist' in status else u""
self.musicdata[u'title'] = status[u'currentsong'] if u'currentsong' in status else u""
self.musicdata[u'album'] = status[u'currentalbum'] if u'currentalbum' in status else u""
self.musicdata[u'volume'] = self.intn(status[u'volume']) if u'volume' in status else 0
self.musicdata[u'length'] = self.intn(status[u'time']) if u'time' in status else 0
self.musicdata[u'elapsed'] = self.intn(status[u'elapsed']) if u'elapsed' in status else 0
self.musicdata[u'actPlayer'] = status[u'actPlayer'] if u'actPlayer' in status else u""
self.musicdata[u'single'] = bool(self.intn(status[u'single'])) if u'single' in status else False
self.musicdata[u'random'] = bool(self.intn(status[u'random'])) if u'random' in status else False
self.musicdata[u'repeat'] = bool(self.intn(status[u'repeat'])) if u'repeat' in status else False
self.musicdata[u'musicdatasource'] = u"Rune"
# For backwards compatibility
self.musicdata[u'duration'] = self.musicdata[u'length']
self.musicdata[u'current'] = self.musicdata[u'elapsed']
# Set default values
self.musicdata[u'samplerate'] = u""
self.musicdata[u'bitrate'] = u""
self.musicdata[u'channels'] = 0
self.musicdata[u'bitdepth'] = u""
self.musicdata[u'tracktype'] = u""
self.musicdata[u'encoding'] = u""
self.musicdata[u'tracktype'] = u""
if self.musicdata[u'actPlayer'] == u'Spotify':
self.musicdata[u'bitrate'] = u"320 kbps"
plp = self.musicdata[u'playlist_position'] = self.intn(status[u'song'])+1 if u'song' in status else 0
plc = self.musicdata[u'playlist_length'] = self.intn(status[u'playlistlength']) if u'playlistlength' in status else 0
# For backwards compatibility
self.musicdata[u'playlist_count'] = self.musicdata[u'playlist_length']
self.musicdata[u'playlist_display'] = u"{0}/{1}".format(plp, plc)
self.musicdata[u'actPlayer'] = u"Spotify"
self.musicdata[u'tracktype'] = u"Spotify"
self.musicdata[u'stream'] = u'not webradio'
elif self.musicdata[u'actPlayer'] == u'MPD':
plp = self.musicdata[u'playlist_position'] = self.intn(status[u'song'])+1 if u'song' in status else 0
plc = self.musicdata[u'playlist_length'] = self.intn(status[u'playlistlength']) if u'playlistlength' in status else 0
# For backwards compatibility
self.musicdata[u'playlist_count'] = self.musicdata[u'playlist_length']
self.musicdata[u'bitrate'] = u"{0} kbps".format(status[u'bitrate']) if u'bitrate' in status else u""
# if radioname is None then this is coming from a playlist (e.g. not streaming)
if status.get(u'radioname') == None:
self.musicdata[u'playlist_display'] = u"{0}/{1}".format(plp, plc)
self.musicdata[u'stream'] = u'not webradio'
else:
self.musicdata[u'playlist_display'] = u"Radio"
self.musicdata[u'stream'] = u'webradio'
# if artist is empty, place radioname in artist field
if self.musicdata[u'artist'] == u"" or self.musicdata[u'artist'] is None:
self.musicdata[u'artist'] = status[u'radioname'] if u'radioname' in status else u""
audio = status[u'audio'] if u'audio' in status else None
chnum = 0
if audio is None:
tracktype = u"MPD"
else:
audio = audio.split(u':')
if len(audio) == 3:
sample = round(float(audio[0])/1000,1)
bits = audio[1]
chnum = int(audio[2])
if audio[2] == u'1':
channels = u'Mono'
elif audio[2] == u'2':
channels = u'Stereo'
elif int(audio[2]) > 2:
channels = u'Multi'
else:
channels = u""
if channels == u"":
tracktype = u"{0} bit, {1} kHz".format(bits, sample)
else:
tracktype = u"{0} {1} bit {2} kHz".format(channels, bits, sample)
else:
# If audio information not available just send that MPD is the source
tracktype = u"MPD"
self.musicdata[u'tracktype'] = tracktype
self.musicdata[u'channels'] = chnum
elif self.musicdata[u'actPlayer'] == u'Airplay':
self.musicdata[u'playlist_position'] = 1
self.musicdata[u'playlist_count'] = 1
self.musicdata[u'playlist_length'] = 1
self.musicdata[u'tracktype'] = u"Airplay"
self.musicdata[u'playlist_display'] = u"Aplay"
self.musicdata[u'stream'] = u'not webradio'
else:
# Unexpected player type
logging.debug(u"Unexpected player type {0} discovered".format(actPlayer))
self.musicdata[u'playlist_position'] = 1
self.musicdata[u'playlist_count'] = 1
self.musicdata[u'playlist_length'] = 1
self.musicdata[u'tracktype'] = actPlayer
self.musicdata[u'playlist_display'] = u"Radio"
self.musicdata[u'stream'] = u'webradio'
# if duration is not available, then suppress its display
if int(self.musicdata[u'length']) > 0:
timepos = time.strftime(u"%-M:%S", time.gmtime(int(self.musicdata[u'elapsed']))) + "/" + time.strftime(u"%-M:%S", time.gmtime(int(self.musicdata[u'length'])))
remaining = time.strftime(u"%-M:%S", time.gmtime( int(self.musicdata[u'length']) - int(self.musicdata[u'elapsed']) ) )
else:
timepos = time.strftime(u"%-M:%S", time.gmtime(int(self.musicdata[u'elapsed'])))
remaining = timepos
self.musicdata[u'remaining'] = remaining.decode()
self.musicdata[u'elapsed_formatted'] = timepos.decode()
# For backwards compatibility
self.musicdata[u'position'] = self.musicdata[u'elapsed_formatted']
self.validatemusicvars(self.musicdata)
if __name__ == u'__main__':
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename=u'musicdata_rune.log', level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())
try:
opts, args = getopt.getopt(sys.argv[1:],u"hs:p:w:",[u"server=",u"port=",u"pwd="])
except getopt.GetoptError:
print u'musicdata_rune.py -s <server> -p <port> -w <password>'
sys.exit(2)
# Set defaults
server = u'localhost'
port = 6379
pwd= u''
for opt, arg in opts:
if opt == u'-h':
print u'musicdata_rune.py -s <server> -p <port> -w <password>'
sys.exit()
elif opt in (u"-s", u"--server"):
server = arg
elif opt in (u"-p", u"--port"):
port = arg
elif opt in (u"-w", u"--pwd"):
pwd = arg
import sys
q = Queue.Queue()
mdr = musicdata_rune(q, server, port, pwd)
try:
start = time.time()
while True:
if start+120 < time.time():
break;
try:
item = q.get(timeout=1000)
print u"++++++++++"
for k,v in item.iteritems():
print u"[{0}] '{1}' type {2}".format(k,v,type(v))
print u"++++++++++"
print
q.task_done()
except Queue.Empty:
pass
except KeyboardInterrupt:
print u''
pass
print u"Exiting..."
```
#### File: pydPiper/sources/musicdata_spop.py
```python
from __future__ import unicode_literals
import threading, logging, Queue, time, sys, telnetlib, json, getopt
import musicdata
class musicdata_spop(musicdata.musicdata):
def __init__(self, q, server=u'localhost', port=6602, pwd=u''):
super(musicdata_spop, self).__init__(q)
self.server = server
self.port = port
self.pwd = <PASSWORD>
self.connection_failed = 0
self.timeout = 20
self.idle_state = False
self.dataclient = None
# Now set up a thread to listen to the channel and update our data when
# the channel indicates a relevant key has changed
data_t = threading.Thread(target=self.run)
data_t.daemon = True
data_t.start()
# Start the idle timer
idle_t = threading.Thread(target=self.idlealert)
idle_t.daemon = True
idle_t.start()
def idlealert(self):
while True:
# Generate a noidle event every timeout seconds
time.sleep(self.timeout)
# If blocked waiting for a response then allow idleaert to issue notify to unblock the service
if self.idle_state:
try:
#self.dataclient.noidle()
self.dataclient.write(u"notify\n")
self.dataclient.read_until(u"\n")
except (IOError, AttributeError):
# If not idle (or not created yet) return to sleeping
pass
def connect(self):
# Try up to 10 times to connect to REDIS
self.connection_failed = 0
self.dataclient = None
logging.debug(u"Connecting to SPOP service on {0}:{1}".format(self.server, self.port))
while True:
if self.connection_failed >= 10:
logging.debug(u"Could not connect to SPOP")
break
try:
# Connection to MPD
client = telnetlib.Telnet(self.server, self.port)
client.read_until("\n")
self.dataclient = client
break
except:
self.dataclient = None
self.connection_failed += 1
time.sleep(1)
if self.dataclient is None:
raise IOError(u"Could not connect to SPOP")
else:
logging.debug(u"Connected to SPOP service")
def run(self):
logging.debug(u"SPOP musicdata service starting")
while True:
if self.dataclient is None:
try:
# Try to connect
self.connect()
self.status()
self.sendUpdate()
except (IOError, RuntimeError):
self.dataclient = None
# On connection error, sleep 5 and then return to top and try again
time.sleep(5)
continue
try:
# Wait for notice that state has changed
self.idle_state = True
self.dataclient.write("idle\n")
msg = self.dataclient.read_until("\n")
self.idle_state = False
self.status()
self.sendUpdate()
time.sleep(.01)
except (IOError, RuntimeError):
self.dataclient = None
logging.debug(u"Could not get status from SPOP")
time.sleep(5)
continue
def status(self):
# Read musicplayer status and update musicdata
try:
self.dataclient.write(u"status\n")
msg = self.dataclient.read_until("\n").strip()
status = json.loads(msg)
except (IOError, ValueError):
logging.debug(u"Bad status message received. Contents were {0}".format(msg))
raise RuntimeError(u"Bad status message received.")
except:
# Caught something else. Report it and then inform calling function that the connection is bad
e = sys.exc_info()[0]
logging.debug(u"Caught {0} trying to get status from SPOP".format(e))
raise RuntimeError(u"Could not get status from SPOP")
state = status.get(u'status')
if state != u"playing":
self.musicdata[u'state'] = u"stop"
else:
self.musicdata[u'state'] = u"play"
# Update remaining variables
self.musicdata[u'artist'] = status[u'artist'] if u'artist' in status else u""
self.musicdata[u'title'] = status[u'title'] if u'title' in status else u""
self.musicdata[u'album'] = status[u'album'] if u'album' in status else u""
self.musicdata[u'volume'] = 0
self.musicdata[u'length'] = self.intn(status[u'duration']/1000) if u'duration' in status else 0
self.musicdata[u'elapsed'] = self.intn(status[u'position']) if u'position' in status else 0
self.musicdata[u'playlist_position'] = self.intn(status[u'current_track']) if u'current_track' in status else 0
self.musicdata[u'playlist_length'] = self.musicdata[u'playlist_count'] = self.intn(status[u'total_tracks']) if u'total_tracks' in status else 0
self.musicdata[u'uri'] = status[u'uri'] if u'uri' in status else u""
self.musicdata[u'repeat'] = status[u'repeat'] if u'repeat' in status else False
self.musicdata[u'random'] = status[u'shuffle'] if u'shuffle' in status else False
self.musicdata[u'single'] = False # Not support in SPOP
self.musicdata[u'current'] = self.musicdata[u'elapsed']
self.musicdata[u'duration'] = self.musicdata[u'length']
self.musicdata[u'actPlayer'] = u"Spotify"
self.musicdata[u'musicdatasource'] = u"SPOP"
self.musicdata[u'bitrate'] = u""
self.musicdata[u'tracktype'] = u""
plp = self.musicdata[u'playlist_position']
plc = self.musicdata[u'playlist_length']
if self.musicdata[u'length'] > 0:
timepos = time.strftime(u"%-M:%S", time.gmtime(self.musicdata[u'elapsed'])) + "/" + time.strftime(u"%-M:%S", time.gmtime(self.musicdata[u'length']))
remaining = time.strftime(u"%-M:%S", time.gmtime(self.musicdata[u'length'] - self.musicdata[u'duration'] ) )
else:
timepos = time.strftime(u"%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
remaining = timepos
self.musicdata[u'remaining'] = remaining.decode()
self.musicdata[u'elapsed_formatted'] = self.musicdata[u'position'] = timepos.decode()
self.musicdata[u'playlist_display'] = u"{0}/{1}".format(plp, plc)
self.musicdata[u'tracktype'] = u"SPOP"
self.validatemusicvars(self.musicdata)
if __name__ == u'__main__':
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename=u'musicdata_spop.log', level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())
try:
opts, args = getopt.getopt(sys.argv[1:],u"hs:p:w:",[u"server=",u"port=",u"pwd="])
except getopt.GetoptError:
print u'musicdata_spop.py -s <server> -p <port> -w <password>'
sys.exit(2)
# Set defaults
server = u'localhost'
port = 6602
pwd= u''
for opt, arg in opts:
if opt == u'-h':
print u'musicdata_spop.py -s <server> -p <port> -w <password>'
sys.exit()
elif opt in (u"-s", u"--server"):
server = arg
elif opt in (u"-p", u"--port"):
port = arg
elif opt in (u"-w", u"--pwd"):
pwd = arg
import sys
q = Queue.Queue()
mds = musicdata_spop(q, server, port, pwd)
try:
start = time.time()
while True:
if start+120 < time.time():
break;
try:
item = q.get(timeout=1000)
print u"+++++++++"
for k,v in item.iteritems():
print u"[{0}] '{1}' type {2}".format(k,v,type(v))
print u"+++++++++"
print
q.task_done()
except Queue.Empty:
pass
except KeyboardInterrupt:
print u''
pass
print u"Exiting..."
```
#### File: pydPiper/utils/fontutil.py
```python
from __future__ import unicode_literals
def fntlines(start, end, w,h):
for i in range (start,end+1):
x = (i % 16)*w
y = i/16*h
print "char id={0} x={1} y={2} width={3} height={4} xoffset=0 yoffset=0 xadvance={5} page=0 chnl=0".format(i,x,y,w,h,w)
```
|
{
"source": "jeli-t/algorithms",
"score": 4
}
|
#### File: algorithms/data_structures/red_black_tree.py
```python
class Red_black_tree():
def __init__(self):
self.nil = Node(0, 'black', None, None)
self.root = self.nil
def __repr__(self):
return str(self.root)
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.nil:
y.left.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else: x.parent.right = y
x.left = x
x.parent = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.nil:
y.right.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else: x.parent.left = y
x.right = x
x.parent = y
def insert(self, z):
y = self.nil
x = self.root
while x != self.nil:
y = x
if z.key < x.key:
x = x.left
else: x = x.right
z.parent = y
if y == self.nil:
self.root = z
elif z.key < y.key or y.key == None:
y.left = z
else: y.right = z
z.left = self.nil
z.right = self.nil
z.color = 'red'
self.insert_fixup(z)
def insert_fixup(self, z):
while z != self.root and z.parent.color == 'red':
if z.parent == z.parent.parent.left:
y = z.parent.parent.right
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.right:
z = z.parent
self.left_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.right_rotate(z.parent.parent)
else:
y = z.parent.parent.left
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.left:
z = z.parent
self.right_rotate(z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.left_rotate(z.parent.parent)
self.root.color = 'black'
def transplant(self, u, v):
if u.parent == self.nil:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else: u.parent.right = v
v.parent = u.parent
def delete(self, z):
y = z
y_original_color = y.color
if z.left == self.nil:
x = z.right
self.transplant(z, z.right)
elif z.right == self.nil:
x = z.left
self.transplant(z, z.left)
else:
y = self.minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self.transplant(y, y.right)
y.right = z.right
y.right.parent = y
self.transplant(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == 'black':
self.delete_fixup(x)
def delete_fixup(self, x):
while x != self.root and x.color == 'black':
if x == x.parent.left:
w = x.parent.right
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.left_rotate(x.parent)
w = x.parent.right
if w.left.color == 'black' and w.right.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.right.color == 'black':
w.left.color = 'black'
w.color = 'red'
self.right_rotate(w)
w = x.parent.right
w.color = x.parent.color
x.parent.color = 'black'
w.right.color = 'black'
self.left_rotate(x.parent)
x = self.root
else:
w = x.parent.left
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.right_rotate(x.parent)
w = x.parent.left
if w.right.color == 'black' and w.left.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.left.color == 'black':
w.right.color = 'black'
w.color = 'red'
self.left_rotate(w)
w = x.parent.left
w.color = x.parent.color
x.parent.color = 'black'
w.left.color = 'black'
self.right_rotate(x.parent)
x = self.root
x.color = 'black'
def minimum(self, x):
while x.left.left != None:
x = x.left
return x.key
def maximum(self, x):
while x.right.right != None:
x = x.right
return x.key
def search(self, x, key):
if x == None or key == x.key:
return x
if key < x.key:
return self.search(x.left, key)
else: return self.search(x.right, key)
class Node():
def __init__(self, key, color = 'red', parent = None, left = None, right = None):
self.key = key
self.color = color
self.parent = parent
self.left = left
self.right = right
def __repr__(self) -> str:
return '{|%s%s|:%s,%s}' % (self.color, self.key, self.left, self.right)
def example_usage():
rb_tree = Red_black_tree()
node_1 = Node(6) # 6
node_2 = Node(4) # / \
node_3 = Node(8) # 4 8
node_4 = Node(2) # /
rb_tree.insert(node_1) # 2
rb_tree.insert(node_2)
rb_tree.insert(node_3)
rb_tree.insert(node_4)
print('Tree text reprezentation:', rb_tree)
print('Searching for key = 4:', rb_tree.search(rb_tree.root, 4))
print('Minimum:', rb_tree.minimum(rb_tree.root))
print('Maksimum:', rb_tree.maximum(rb_tree.root))
rb_tree.delete(node_2)
print('Tree text reprezentation after removing node 2 (key=4):', rb_tree)
if __name__ == "__main__":
example_usage() # run an example on start
```
#### File: algorithms/data_structures/stack.py
```python
class StackOverflowError(BaseException):
pass
class StackEmptyError(BaseException):
pass
class Stack():
def __init__(self, max_size = 10):
self.max_size = max_size
self.s = []
def __repr__(self):
return str(self.s)
def push(self, x):
if len(self.s) < self.max_size:
self.s.append(x)
else: raise StackOverflowError
def pop(self):
if len(self.s) > 0:
self.s.pop(-1)
else: raise StackEmptyError
def peek(self):
x = self.s[-1]
self.pop()
return x
def example_usage():
stack = Stack(5) # []
stack.push(1111) # [1111]
stack.push(2222) # [1111, 2222]
stack.push(3333) # [1111, 2222, 3333]
print('Stack:', stack)
print('Peek:', stack.peek()) # [1111, 2222]
stack.push(4444) # [1111, 2222, 4444]
print('Stack:', stack)
if __name__ == "__main__":
example_usage() # run an example on start
```
#### File: algorithms/sorting_algorithms/bubble_sort.py
```python
def bubble_sort(A):
for i in range(0, len(A)):
for j in range(len(A) - 1, i, -1):
if A[j] < A[j - 1]:
A[j - 1], A[j] = A[j], A[j - 1]
return A
def example_usage():
A = [3, 7, 1, 8, 4, 6, 9, 2, 5]
print('Unsorted:\t', A)
print('Sorted:\t\t', bubble_sort(A))
if __name__ == "__main__":
example_usage() # run an example on start
```
#### File: algorithms/sorting_algorithms/counting_sort.py
```python
def counting_sort(A, B, k):
C = []
for i in range(0, k + 1):
C.append(0)
for j in range(0, len(A)):
C[A[j]] += 1
for i in range(1, k):
C[i] = C[i] + C[i-1]
for j in reversed(range(0, len(A))):
B[C[A[j]]-1] = A[j]
C[A[j]] -= 1
return B
def example_usage():
A = [3, 7, 1, 8, 4, 6, 9, 2, 5]
print('Unsorted:\t', A)
print('Sorted:\t\t', counting_sort(A, [0] * len(A), max(A) + 1))
if __name__ == "__main__":
example_usage() # run an example on start
```
|
{
"source": "jelitox/aiohttp-session",
"score": 3
}
|
#### File: aiohttp-session/aiohttp_session/cookie_storage.py
```python
import base64
import json
from typing import Any, Callable, Optional, Union
from aiohttp import web
from cryptography import fernet
from cryptography.fernet import InvalidToken
from . import AbstractStorage, Session
from .log import log
class EncryptedCookieStorage(AbstractStorage):
"""Encrypted JSON storage.
"""
def __init__(
self,
secret_key: Union[str, bytes, bytearray], *,
cookie_name: str = "AIOHTTP_SESSION",
domain: Optional[str] = None,
max_age: Optional[int] = None,
path: str = '/',
secure: Optional[bool] = None,
httponly: bool = True,
encoder: Callable[[object], str] = json.dumps,
decoder: Callable[[str], Any] = json.loads
) -> None:
super().__init__(cookie_name=cookie_name, domain=domain,
max_age=max_age, path=path, secure=secure,
httponly=httponly,
encoder=encoder, decoder=decoder)
if isinstance(secret_key, str):
pass
elif isinstance(secret_key, (bytes, bytearray)):
secret_key = base64.urlsafe_b64encode(secret_key)
# TODO: Typing error fixed in https://github.com/pyca/cryptography/pull/5951
self._fernet = fernet.Fernet(secret_key) # type: ignore[arg-type]
async def load_session(self, request: web.Request) -> Session:
cookie = self.load_cookie(request)
if cookie is None:
return Session(None, data=None, new=True, max_age=self.max_age)
else:
try:
data = self._decoder(
self._fernet.decrypt(
cookie.encode('utf-8'),
ttl=self.max_age
).decode('utf-8')
)
return Session(None, data=data,
new=False, max_age=self.max_age)
except InvalidToken:
log.warning("Cannot decrypt cookie value, "
"create a new fresh session")
return Session(None, data=None, new=True, max_age=self.max_age)
async def save_session(
self,
request: web.Request,
response: web.StreamResponse,
session: Session
) -> None:
if session.empty:
return self.save_cookie(response, '',
max_age=session.max_age)
cookie_data = self._encoder(
self._get_session_data(session)
).encode('utf-8')
self.save_cookie(
response,
self._fernet.encrypt(cookie_data).decode('utf-8'),
max_age=session.max_age
)
```
#### File: aiohttp-session/examples/postgres_storage.py
```python
import json
import uuid
from typing import Any, Callable, Dict, Optional
import psycopg2.extras
from aiohttp import web
from aiohttp_session import AbstractStorage, Session
from aiopg import Pool
class PgStorage(AbstractStorage):
"""PG storage"""
def __init__(self, pg_pool: Pool, *, cookie_name: str = "AIOHTTP_SESSION", # type: ignore[no-any-unimported]
domain: Optional[str] = None, max_age: Optional[int] = None,
path: str = '/', secure: Optional[bool] = None, httponly: bool = True,
key_factory: Callable[[], str] = lambda: uuid.uuid4().hex,
encoder: Callable[[object], str] = psycopg2.extras.Json,
decoder: Callable[[str], Any] = json.loads):
super().__init__(cookie_name=cookie_name, domain=domain,
max_age=max_age, path=path, secure=secure,
httponly=httponly,
encoder=encoder, decoder=decoder)
self._pg = pg_pool
self._key_factory = key_factory
async def load_session(self, request: web.Request) -> Session:
cookie = self.load_cookie(request)
data = {}
if cookie is None:
return Session(None, data={}, new=True, max_age=self.max_age)
else:
async with self._pg.acquire() as conn:
key = uuid.UUID(cookie)
async with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
await cur.execute("SELECT session, extract(epoch from created) FROM web.sessions WHERE uuid = %s", (key,))
data = await cur.fetchone()
if not data:
return Session(None, data={}, new=True, max_age=self.max_age)
return Session(key, data=data, new=False, max_age=self.max_age)
async def save_session(self, request: web.Request, response: web.StreamResponse,
session: Session) -> None:
key = session.identity
if key is None:
key = self._key_factory()
self.save_cookie(response, key, max_age=session.max_age)
else:
if session.empty:
self.save_cookie(response, "", max_age=session.max_age)
else:
key = str(key)
self.save_cookie(response, key, max_age=session.max_age)
data = self._get_session_data(session)
if not data:
return
data_encoded = self._encoder(data["session"])
expire = data["created"] + (session.max_age or 0)
async with self._pg.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("INSERT INTO web.sessions (uuid,session,created,expire)"
" VALUES (%s, %s, to_timestamp(%s),to_timestamp(%s))"
" ON CONFLICT (uuid)"
" DO UPDATE"
" SET (session,expire)=(EXCLUDED.session, EXCLUDED.expire)",
[key, data_encoded, data["created"], expire])
```
|
{
"source": "jelitox/async-notify",
"score": 3
}
|
#### File: async-notify/notify/exceptions.py
```python
class notifyException(Exception):
"""Base class for other exceptions."""
code: int = None
payload: str = None
def __init__(self, message: str = None, *args, code: int = None, payload: str = None, **kwargs):
super(notifyException, self).__init__(*args, **kwargs)
self.args = (
message,
code,
)
self.message = message
if code:
self.code = code
if payload:
self.payload = payload
def __str__(self):
return f"{__name__} -> {self.message}"
def get(self):
return self.message
class DataError(notifyException, ValueError):
"""An error caused by invalid query input."""
class NotSupported(notifyException):
"""Not Supported functionality."""
class ProviderError(notifyException):
"""Database Provider Error."""
class NotImplementedError(notifyException):
"""Exception for Not implementation."""
class UninitializedError(ProviderError):
"""Exception when provider cant be initialized."""
class ConnectionError(ProviderError):
"""Generic Connection Error."""
class ConnectionTimeout(ProviderError):
"""Connection Timeout Error."""
class TooManyConnections(ProviderError):
"""Too Many Connections."""
```
#### File: providers/email/email.py
```python
from notify.settings import (
EMAIL_SMTP_USERNAME,
EMAIL_SMTP_PASSWORD,
EMAIL_SMTP_HOST,
EMAIL_SMTP_PORT
)
from notify.providers.abstract import ProviderEmail
class Email(ProviderEmail):
"""
email.
Basic SMTP Provider.
"""
provider = 'email'
blocking: bool = False
def __init__(self, hostname: str = None, port: str = None, username: str = None, password: str = None, **kwargs):
"""
"""
self._attachments: list = []
self.force_tls: bool = True
self.username = None
self.password = None
super(Email, self).__init__(**kwargs)
# server information
if hostname:
self._host = hostname
else:
if not self._host: # already configured
try:
self._host = kwargs['hostname']
except KeyError:
self._host = EMAIL_SMTP_HOST
if port:
self._port = port
else:
if not self._port:
try:
self._port = kwargs['port']
except KeyError:
self._port = EMAIL_SMTP_PORT
# connection related settings
if username:
self.username = username
if self.username is None:
self.username = EMAIL_SMTP_USERNAME
if password:
self.password = password
if self.password is None:
self.password = EMAIL_SMTP_PASSWORD
if self.username is None or self.password is None:
raise RuntimeWarning(
'to send messages via **{0}** you need to configure user & password. \n'
'Either send them as function argument via key \n'
'`username` & `password` or set up env variable \n'
'as `EMAIL_USERNAME` & `EMAIL_PASSWORD`.'.format(self._name)
)
try:
# sent from another account
if 'account' in kwargs:
self.actor = kwargs['account']
else:
self.actor = self.username
except KeyError:
self.actor = self.username
```
#### File: notify/providers_old/__init__.py
```python
import asyncio
import time
from functools import partial
import uuid
from abc import ABC, ABCMeta, abstractmethod
from typing import List, Dict, Optional, Union, Callable, Awaitable
from notify.exceptions import (
ProviderError,
NotImplementedError,
notifyException
)
from notify.models import Account, Actor
from enum import Enum
from notify.settings import NAVCONFIG, logging_notify, LOG_LEVEL
from notify.utils import colors, SafeDict
from concurrent.futures import ThreadPoolExecutor
from asyncdb.exceptions import (_handle_done_tasks, default_exception_handler,
shutdown)
# email system
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# logging system
import logging
from logging.config import dictConfig
dictConfig(logging_notify)
NOTIFY = 'notify'
SMS = 'sms'
EMAIL = 'email'
PUSH = 'push'
IM = 'im'
class ProviderType(Enum):
NOTIFY = 'notify'
SMS = 'sms'
EMAIL = 'email'
PUSH = 'push'
IM = 'im'
class ProviderBase(ABC):
"""ProviderBase.
Base class for All providers
"""
__metaclass__ = ABCMeta
provider: str = None
provider_type: ProviderType = NOTIFY
longrunning: bool = True
_loop = None
_debug: bool = False
_params: dict = None
_logger = None
_config = None
_tplenv = None
_template = None
_templateargs: dict = {}
sent: Callable = None
def __init__(self, *args, **kwargs):
self._params = kwargs
self._logger = logging.getLogger('Notify')
self._logger.setLevel(LOG_LEVEL)
self._config = NAVCONFIG
from notify import TemplateEnv
self._tplenv = TemplateEnv
for arg, val in self._params.items():
try:
object.__setattr__(self, arg, val)
except AttributeError:
pass
if 'loop' in kwargs:
self._loop = kwargs['loop']
del kwargs['loop']
else:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
# configure debug:
if 'debug' in kwargs:
self._debug = kwargs['debug']
del kwargs['debug']
@abstractmethod
def send(self, *args, **kwargs):
pass
@abstractmethod
def connect(self, *args, **kwargs):
pass
@abstractmethod
def close(self):
pass
def _prepare(self, recipient: Actor, message, template: str = None, **kwargs):
"""
_prepare.
Prepare works in the preparation of message for sending.
"""
#1 replacement of strings
if self._params:
msg = message.format_map(SafeDict(**self._params))
else:
msg = message
if template:
# using template parser:
self._template = self._tplenv.get_template(template)
#print(self._template.environment.list_templates())
return msg
@classmethod
def name(self):
return self.__name__
@classmethod
def type(self):
return self.provider_type
def get_loop(self):
return self._loop
def set_loop(self, loop=None):
if not loop:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
else:
self._loop = loop
def _render(self, to: Actor, message, **kwargs):
"""
_render.
Returns the parseable version of template.
"""
msg = message
if self._template:
self._templateargs = {
"recipient": to,
"username": to,
"message": message,
**kwargs
}
msg = self._template.render(**self._templateargs)
return msg
def create_task(self, to, message, **kwargs):
task = asyncio.create_task(self._send(to, message, **kwargs))
handler = partial(_handle_done_tasks, self._logger)
task.add_done_callback()
fn = partial(self.__sent__, to, message)
task.add_done_callback(fn)
return task
async def send(self, recipient: List[Actor] = [], message: str = '', **kwargs):
"""
send.
public method to send messages and notifications
"""
# template (or message) for preparation
msg = self._prepare(recipient, message, **kwargs)
rcpt = []
if isinstance(recipient, list):
rcpt = recipient
else:
rcpt.append(recipient)
# working on Queues or executor:
if self.longrunning is True:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.set_exception_handler(default_exception_handler)
tasks = []
for to in rcpt:
task = self.create_task(to, message, **kwargs)
tasks.append(task)
# creating the executor
fn = partial(self.execute_notify, loop, tasks, **kwargs)
with ThreadPoolExecutor(max_workers=10) as pool:
result = loop.run_in_executor(pool, fn)
else:
# working on a asyncio.queue functionality
queue = asyncio.Queue(maxsize=len(rcpt)+1)
started_at = time.monotonic()
tasks = []
consumers = []
i = 0
for to in rcpt:
# create the consumers:
consumer = asyncio.create_task(self.process_notify(queue))
consumers.append(consumer)
# create the task:
task = self.create_task(to, message, **kwargs)
tasks.append(task)
i += 1
# send tasks to queue processor (producer)
await self.notify_producer(queue, tasks)
# wait until the consumer has processed all items
await queue.join()
total_slept_for = time.monotonic() - started_at
# Cancel our worker tasks.
for task in consumers:
task.cancel()
#print(f'{i} workers works in parallel for {total_slept_for:.2f} seconds')
return True
# PUB/SUB Logic based on Asyncio Queues
async def notify_producer(self, queue, tasks: list):
"""
Process Notify.
Fill the asyncio Queue with tasks
"""
for task in tasks:
queue.put_nowait(task)
async def process_notify(self, queue):
"""
Consumer logic of Asyncio Queue
"""
while True:
# Get a "work item" out of the queue.
task = await queue.get()
# process the task
await task
# Notify the queue that the item has been processed
queue.task_done()
#print(f'{name} has slept for {1:.2f} seconds')
def execute_notify(
self,
loop: asyncio.AbstractEventLoop,
tasks: List[Awaitable],
**kwargs
):
"""
execute_notify.
Executing notification in a event loop.
"""
try:
group = asyncio.gather(*tasks, loop=loop, return_exceptions=False)
try:
results = loop.run_until_complete(group)
except (RuntimeError, Exception) as err:
raise Exception(err)
#TODO: Processing accordly the exceptions (and continue)
# for task in tasks:
# if not task.done():
# await asyncio.gather(*tasks, return_exceptions=True)
# task.cancel()
except Exception as err:
raise Exception(err)
def __sent__(
self,
recipient: Actor,
message: str,
task: Awaitable,
**kwargs
):
"""
processing the callback for every notification that we sent.
"""
result = task.result()
if callable(self.sent):
# logging:
self._logger.info('Notification sent to> {}'.format(recipient))
self.sent(recipient, message, result, task)
class ProviderEmailBase(ProviderBase):
"""
ProviderEmailBase.
Base class for All Email providers
"""
provider_type = EMAIL
_server = None
async def send(
self,
recipient: List[Actor] = [],
message: str = '',
**kwargs
):
result = None
# making the connection to the service:
try:
if asyncio.iscoroutinefunction(self.connect):
if not self.is_connected():
await self.connect()
else:
self.connect()
except Exception as err:
raise RuntimeError(err)
# after connection, proceed exactly like other connectors.
try:
result = await super(ProviderEmailBase, self).send(recipient, message, **kwargs)
except Exception as err:
raise RuntimeError(err)
return result
class ProviderMessageBase(ProviderBase):
"""ProviderMessageBase.
Base class for All Message providers
"""
provider_type = SMS
class ProviderIMBase(ProviderBase):
"""ProviderIMBase.
Base class for All Message to Instant messenger providers
"""
provider_type = IM
_response = None
```
#### File: providers_old/twitter/twitter.py
```python
from notify.settings import TWITTER_ACCESS_TOKEN, TWITTER_TOKEN_SECRET, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET
from notify.providers import ProviderIMBase, IM
from typing import List, Optional
from notify.models import Actor, Chat
import tweepy
class Twitter(ProviderIMBase):
provider = 'twitter'
provider_type = IM
_consumer_key: str = None
_consumer_secret: str = None
_token: str = None
_secret: str = None
client = None
sid = None
def __init__(
self,
consumer_key=None,
consumer_secret=None,
token=None,
secret=None,
*args,
**kwargs
):
"""
:param token: twilio auth token given by Twilio
:param sid: twilio auth id given by Twilio
"""
super(Twitter, self).__init__(*args, **kwargs)
self._token = TWITTER_ACCESS_TOKEN if token is None else token
self._secret = TWITTER_TOKEN_SECRET if secret is None else sid
self._consumer_key = TWITTER_CONSUMER_KEY if consumer_key is None else consumer_key
self._consumer_secret = TWITTER_CONSUMER_SECRET if consumer_secret is None else consumer_secret
self.connect()
def close(self):
self.client = None
def connect(self):
"""
Verifies that a token and sid were given
"""
if self._token is None or self._secret is None:
raise RuntimeError(
'to send Tweets via {0} you need to configure TWITTER_ACCESS_TOKEN & TWITTER_TOKEN_SECRET in \n'
'environment variables or send properties to theinstance.'.format(self._token)
)
try:
auth = tweepy.OAuthHandler(
self._consumer_key,
self._consumer_secret
)
if auth:
auth.set_access_token(self._token, self._secret)
self.client = tweepy.API(auth)
except Exception as err:
raise RuntimeError('Twitter API error: {}'.format(err))
# determine actor:
self.actor = self.client.me()
async def _send(self, to: Optional[Actor] = None, message: str = '', **kwargs):
"""
_send.
Publish a Twitter using Tweepy
:param to: Optional Reply-To Message.
:param message: message to Publish
"""
try:
msg = self._render(to, message, **kwargs)
result = self.client.update_status(status=msg)
# TODO: processing the output, adding callbacks
return result
except Exception as e:
print(e)
raise RuntimeError(
'Error Publishing Tweet, Current Error: {}'.format(e)
)
```
#### File: providers/telegram/Telegram.py
```python
import logging
from io import BytesIO
from PIL import Image
from pathlib import Path, PurePath
from typing import List, Union
from notify.providers.abstract import ProviderIM, ProviderType
# telegram
from aiogram import Bot, types, executor, types
from aiogram.dispatcher import Dispatcher
from aiogram.dispatcher.webhook import SendMessage
from aiogram.utils.exceptions import (
TelegramAPIError,
BadRequest,
MessageError,
NotFound,
Unauthorized,
NetworkError,
ChatNotFound
)
from aiogram.utils.emoji import emojize
from aiogram.utils.markdown import bold, code, italic, text
# TODO: web-hooks
# from aiogram.utils.executor import start_webhook
from notify.settings import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
from notify.models import Actor, Chat
from notify.exceptions import notifyException
class Telegram(ProviderIM):
provider: str = 'telegram'
provider_type = ProviderType.IM
blocking: bool = False
parseMode: str = 'html' # can be MARKDOWN_V2 or HTML
def __init__(self, *args, **kwargs):
self._bot = None
self._info = None
self._bot_token = None
self._chat_id: str = None
self._connected: bool = False
super(Telegram, self).__init__(*args, **kwargs)
# connection related settings
try:
self._bot_token = kwargs['bot_token']
except KeyError:
self._bot_token = TELEGRAM_BOT_TOKEN
try:
self._chat_id = kwargs['chat_id']
except KeyError:
self._chat_id = TELEGRAM_CHAT_ID
async def close(self):
self._bot = None
self._connected = False
async def connect(self):
info = None
# creation of bot
try:
self._bot = Bot(token=self._bot_token)
self._info = await self._bot.get_me()
self._logger.debug(f"🤖 Hello, I'm {self._info.first_name}.\nHave a nice Day!")
self._connected = True
except Exception as err:
raise notifyException(
f"Notify: Error creating Telegram Bot {err}"
)
def set_chat(self, chat):
self._chat_id = chat
def get_chat(self, **kwargs):
# define destination
try:
chat = kwargs['chat_id']
if isinstance(chat, Chat):
self._chat_id = chat.chat_id
del kwargs['chat_id']
except KeyError:
self._chat_id = TELEGRAM_CHAT_ID
return self._chat_id
async def _send(self, to: Union[str, Actor, Chat], message: str, **kwargs):
"""
_send.
Logic associated with the construction of notifications
"""
# start sending a message:
try:
msg = self._render(to, message, **kwargs)
self._logger.info('Messsage> {}'.format(msg))
except Exception as err:
raise RuntimeError(f'Notify Telegram: Error Parsing Message: {err}')
# Parsing Mode:
if self.parseMode == 'html':
mode = types.ParseMode.HTML
else:
mode = types.ParseMode.MARKDOWN_V2
if 'chat_id' in kwargs:
chat_id = self.get_chat(**kwargs)
else:
if isinstance(to, Chat):
chat_id = to.chat_id
elif isinstance(to, str):
chat_id = to
else:
chat_id = self._chat_id
try:
args = {
'chat_id': chat_id,
'text': msg,
'parse_mode': mode,
**kwargs
}
print(args)
response = await self._bot.send_message(
**args
)
# TODO: make the processing of response
return response
except Unauthorized as err:
# remove update.message.chat_id from conversation list
print(err)
except BadRequest as err:
# handle malformed requests - read more below!
print(err)
except NetworkError as err:
# handle slow connection problems
print(err)
except NetworkError as err:
# handle other connection problems
print(err)
except ChatNotFound as err:
# the chat_id of a group has changed, use e.new_chat_id instead
print(err)
except TelegramAPIError as err:
# handle all other telegram related errors
print(err)
except Exception as err:
print('ERROR: ', err)
async def prepare_photo(self, photo):
# Migrate to aiofile
if isinstance(photo, PurePath):
# is a path, I need to open that image
img = Image.open(r"{}".format(photo))
bio = BytesIO()
bio.name = photo.name
img.save(bio, img.format)
bio.seek(0)
return bio
elif isinstance(photo, str):
# its an URL
return photo
elif isinstance(photo, BytesIO):
# its a binary version of photo
photo.seek(0)
return photo
else:
return None
async def send_photo(self, photo, **kwargs):
image = await self.prepare_photo(photo)
if image:
chat_id = self.get_chat()
try:
response = await self._bot.send_photo(
chat_id, photo=image, **kwargs
)
# print(response) # TODO: make the processing of response
return response
except Unauthorized as err:
# remove update.message.chat_id from conversation list
print(err)
except BadRequest as err:
# handle malformed requests - read more below!
print(err)
except NetworkError as err:
# handle slow connection problems
print(err)
except NetworkError as err:
# handle other connection problems
print(err)
except ChatNotFound as err:
# the chat_id of a group has changed, use e.new_chat_id instead
print(err)
except TelegramAPIError as err:
# handle all other telegram related errors
print(err)
except Exception as err:
print('ERROR: ', err)
async def send_document(self, document, **kwargs):
chat_id = self.get_chat()
try:
response = await self._bot.send_document(
chat_id,
document=open(document, 'rb'),
**kwargs
)
# print(response) # TODO: make the processing of response
return response
except Unauthorized as err:
# remove update.message.chat_id from conversation list
print(err)
except BadRequest as err:
# handle malformed requests - read more below!
print(err)
except NetworkError as err:
# handle slow connection problems
print(err)
except NetworkError as err:
# handle other connection problems
print(err)
except ChatNotFound as err:
# the chat_id of a group has changed, use e.new_chat_id instead
print(err)
except TelegramAPIError as err:
# handle all other telegram related errors
print(err)
except Exception as err:
print('ERROR: ', err)
```
#### File: async-notify/notify/templates.py
```python
import logging
from pathlib import Path
from notify.settings import MEMCACHE_HOST, MEMCACHE_PORT
from asyncdb.providers.mcache import mcache
from typing import (
Dict,
Optional
)
from jinja2 import (
Environment,
FileSystemLoader,
MemcachedBytecodeCache
)
# TODO: implementing a bytecode-cache on redis or memcached
jinja_config = {
'autoescape': True,
'enable_async': False,
'extensions': [
'jinja2.ext.autoescape',
'jinja2.ext.with_',
'jinja2.ext.i18n'
]
}
class TemplateParser(object):
"""
TemplateParser.
This is a wrapper for the Jinja2 template engine.
"""
def __init__(self, directory: Path, **kwargs):
self.template = None
self.cache = mcache(params={"host": MEMCACHE_HOST, "port": MEMCACHE_PORT})
try:
self.cache.connection()
except Exception as err:
logging.error(
'Notify: Error Connecting to Memcached'
)
self.cache = None
self.path = directory.resolve()
if not self.path.exists():
raise RuntimeError(
'Notify: template directory {} does not exist'.format(directory)
)
if 'config' in kwargs:
self.config = {**jinja_config, **kwargs['config']}
else:
self.config = jinja_config
# creating loader:
templateLoader = FileSystemLoader(
searchpath=[str(self.path)]
)
if self.cache.is_connected():
self.config['bytecode_cache'] = MemcachedBytecodeCache(
self.cache,
prefix='notify_template_',
timeout=2,
ignore_memcache_errors=True
)
# initialize the environment
try:
# TODO: check the bug ,encoding='ANSI'
self.env = Environment(loader=templateLoader, **self.config)
#compiled_path = BytesIO()
compiled_path = str(self.path.joinpath('.compiled'))
self.env.compile_templates(target=compiled_path, zip='deflated')
except Exception as err:
raise RuntimeError(
'Notify: Error loading Template Environment: {}'.format(err)
)
def get_template(self, filename: str):
self.template = self.env.get_template(str(filename))
return self.template
@property
def environment(self):
return self.env
def render(self, filename: str, params: Optional[Dict] = {}) -> str:
result = None
try:
self.template = self.env.get_template(str(filename))
result = self.template.render(**params)
except Exception as err:
raise RuntimeError(
'Notify: Error rendering template: {}, error: {}'.format(
filename,
err
)
)
finally:
return result
```
|
{
"source": "jelitox/backendstack",
"score": 2
}
|
#### File: apps/base/models.py
```python
from django.db import models, connection
from apps.authentication.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
""" Academic Level."""
class AcademicLevel(models.Model):
name = models.CharField(primary_key=True, verbose_name=_('Academic Name'), max_length=30, unique=True,
db_index=True)
description = models.CharField(verbose_name=_('Description'), max_length=120, null=True, blank=True)
enabled = models.BooleanField(verbose_name=_('Enabled'), default=True)
def __str__(self):
return '%s' % self.name
class Meta:
app_label = 'base'
db_table = 'base_academic'
verbose_name = _('Academic Level')
verbose_name_plural = _('Academics Levels')
""" Countries."""
class Countries(models.Model):
name = models.CharField(verbose_name=_('Country Name'), max_length=200)
country_code = models.CharField(verbose_name=_('Country Code'), max_length=2, default='US')
def __unicode__(self):
return self.name
class Meta:
app_label = 'base'
db_table = 'base_countries'
verbose_name = _('country')
verbose_name_plural = _('countries')
""" Cities."""
class Cities(models.Model):
name = models.CharField(verbose_name=_('City'), max_length=100, default='')
country = models.ForeignKey(Countries, verbose_name=_('Country'),
on_delete=models.CASCADE)
def __unicode__(self):
return self.city
class Meta:
app_label = 'base'
db_table = 'base_cities'
verbose_name = _('city')
verbose_name_plural = _('cities')
GENDERS = (
('male', 'Male'),
('female', 'Female')
)
""" User Profiles."""
class UserProfile(models.Model):
profile_id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE, related_name='profile')
nickname = models.CharField(_('First Name'), max_length=50, null=True)
first_name = models.CharField(_('First Name'), max_length=50, null=True)
last_name = models.CharField(_('Last Name'), max_length=50, null=True)
display_name = models.CharField(_('Display Name'), max_length=100, null=True)
gender = models.CharField(max_length=6, verbose_name=_('Gender'), choices=GENDERS, null=True, blank=True)
email = models.EmailField(_('Email Address'), unique=True)
last_update = models.DateTimeField(_('Last update'), default=now, blank=True)
date_joined = models.DateTimeField(_('date joined'), default=now, blank=True)
píc = models.ImageField(upload_to='static/images/profiles/', null=True, blank=True)
city = models.ForeignKey(Cities, on_delete=models.CASCADE, null=True, blank=True)
country = models.ForeignKey(Countries, on_delete=models.CASCADE, null=True, blank=True)
address = models.CharField(_('Address'), max_length=120, null=True)
academic_level = models.ForeignKey(AcademicLevel, on_delete=models.CASCADE, null=True, blank=True)
enabled = models.BooleanField(null=False, blank=False, default=True)
birth_date = models.DateField(null=True, blank=True)
description = models.CharField(_('Bio'), max_length=540, null=True)
@property
def is_active(self):
return bool(self.enabled)
@property
def display_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
if self.user.first_name:
full_name = '%s %s' % (self.user.first_name, self.user.last_name)
return full_name.strip()
else:
return str(self.email)
def __unicode__(self): # __str__
return str(self.email)
class Meta:
app_label = 'base'
db_table = 'base_user_profile'
verbose_name = _('User Profile')
verbose_name_plural = _('User Profiles')
```
|
{
"source": "jelitox/django_async",
"score": 3
}
|
#### File: multischema/multischema/routers.py
```python
from django.urls import resolve
from django.apps import apps
from django.conf import settings
from django.db import router, connections
import sys
import threading
from django.http import Http404
request_cfg = threading.local()
DEFAULT_DB_ALIAS = 'default'
USER_APPS = settings.DATABASES.keys()
SYSTEM_APPS = [ 'admin', 'auth', 'contenttypes', 'dashboard', 'sessions', 'sites', 'silk', 'social_django', 'notifications', 'social_django' ]
SYSTEM_TABLES = [ 'auth_user', 'auth_group', 'auth_permission', 'auth_user_groups', 'auth_user_user_permissions', 'social_auth_usersocialauth' ]
class schemaRouter(object):
"""A router to control troc db operations."""
db = None
index = len(USER_APPS)
def __init__(self):
"""Get information about databases."""
self.db = settings.DATABASES
def _multi_db(self, model):
from django.conf import settings
#print(model._meta.db_table)
if hasattr(request_cfg, 'db'):
print(request_cfg.db)
if request_cfg.db in self.db.keys():
return request_cfg.db
else:
raise Http404
else:
return DEFAULT_DB_ALIAS
def db_for_read(self, model, **hints):
"""Point all operations on app1 models to 'db_app1'."""
if model._meta.app_label in SYSTEM_APPS:
return DEFAULT_DB_ALIAS
if model._meta.app_label in self.db.keys():
return model._meta.app_label
else:
return self._multi_db()
return None
def db_for_write(self, model, **hints):
"""Point all operations on app1 models to 'db_app1'."""
if model._meta.app_label in SYSTEM_APPS or model._meta.db_table in SYSTEM_TABLES:
return DEFAULT_DB_ALIAS
if model._meta.app_label in self.db.keys():
#db_table = 'schema\".\"tablename'
try:
readonly = self.db[model._meta.app_label]['PARAMS']['readonly']
if readonly:
# Read Only Database
return False
else:
table = model._meta.db_table
if table.find('.') == -1:
schema = model._meta.app_label
model._meta.db_table = '{}\".\"{}'.format(schema, table)
return self._multi_db(model)
except KeyError:
table = model._meta.db_table
#print(table.find('.'))
if table.find('.') == -1:
schema = model._meta.app_label
model._meta.db_table = '{}\".\"{}'.format(schema, table)
#model._meta.db_table = '{}.{}'.format(schema, table)
return self._multi_db(model)
return None
def allow_relation(self, obj1, obj2, **hints):
"""Allow any relation if a model in app1 is involved."""
if obj1._meta.app_label in [ 'auth' ] or obj2._meta.app_label in [ 'auth' ]:
""" Can made migrations with AUTH model """
return True
if obj1._meta.app_label in self.db.keys() or obj2._meta.app_label in self.db.keys():
try:
db1 = self.db[obj1._meta.app_label]['NAME']
db2 = self.db[obj2._meta.app_label]['NAME']
except KeyError:
return True
if db1 == db2:
""" Both DB are the same """
return True
else:
return False
return None
def allow_migrate(self, db, app_label, model=None, **hints):
"""Make sure the app1 only appears in the 'app1' database."""
if app_label in SYSTEM_APPS:
db == 'default'
return True
if db == 'default':
#print('APP LABEL: %s DB: %s' % (app_label, b))
if app_label in self.db.keys():
# cannot run migration of app models onto default database
db = app_label
return True
elif model and model._meta.app_label in self.db.keys():
db = app_label
return False
else:
return None
if model and app_label in self.db.keys():
try:
readonly = self.db[app_label]['PARAMS']['readonly']
if readonly:
return False
else:
return True
except KeyError:
return True
return None
def ensure_schema(self):
"""
Ensures the table exists and has the correct schema.
"""
if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
return
if router.allow_migrate(self.connection, self.Migration):
with self.connection.schema_editor() as editor:
editor.create_model(self.Migration)
```
|
{
"source": "jelitox/google-photos-wallpaper",
"score": 3
}
|
#### File: google-photos-wallpaper/src/bridge.py
```python
import eel
from src.google_api import GoogleApi
from src.options import Options
from src.scheduler import Scheduler
# These methods are exposed to the Vue app
# They are a bridge between JS and Python code
@eel.expose
def is_authenticated():
# Check if user has valid credentials
return GoogleApi.is_authenicated()
@eel.expose
def sign_in():
# If creds are invalid, send user to sign in flow
GoogleApi.ensure_valid_token()
@eel.expose
def get_favorites():
# Get user's favorited media items
return GoogleApi.get_favorites()
@eel.expose
def get_albums():
# Get user's photo albums
return GoogleApi.get_albums()
@eel.expose
def get_album_media_items(album_id):
# Get media items from a photo album
return GoogleApi.get_album_media_items(album_id)
@eel.expose
def get_media_item(media_item_id):
# Retreive data for a media item
return GoogleApi.get_media_item(media_item_id)
@eel.expose
def set_selected_albums(selected_albums):
# User has changed the album selection
Options.set_selected_albums(selected_albums)
@eel.expose
def get_user_options():
return Options.get_user_options()
@eel.expose
def set_schedule(interval, unit):
Scheduler.start(interval, unit)
@eel.expose
def set_wallpaper(media_item):
Options.set_current_wallpaper(media_item)
return True
@eel.expose
def set_wallpaper_by_direction(direction):
return Options.set_wallpaper_by_direction(direction)
@eel.expose
def set_wallpaper_random():
return Options.set_wallpaper_random()
@eel.expose
def get_current_wallpaper():
# Get current wall from user options
return Options.get_current_wallpaper()
```
#### File: google-photos-wallpaper/src/google_api.py
```python
import pickle
import os
import eel
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import Flow
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from src.resource_path import resource_path
PICKLE_PATH = resource_path('storage/token.pickle')
def deco(cls):
"""
Initialize class with credentials if available, then build API services
This method runs when the GoogleApi class is finished building
"""
# Open Oauth credentials from stored file
creds = None
if os.path.exists(PICKLE_PATH):
with open(PICKLE_PATH, 'rb') as token:
cls.creds = pickle.load(token)
cls.build_services(cls.creds)
return cls
@deco
class GoogleApi():
"""
Class used to get data from the Google API
Attributes:
creds (google.oauth2.credentials.Credentials): The OAuth 2.0 credentials for the user
photos (Resource): Google photos API service - only to use after signing in
"""
creds = None
photos = None
@classmethod
def is_authenicated(cls):
return cls.creds and cls.creds.valid
@classmethod
def ensure_valid_token(cls):
"""
Make sure the current credentials have not expired
If so, new ones will be generated either by user consent or with a refresh token
"""
# If credentials aren't stored or have expired
if not cls.is_authenicated():
# Expired, get new access token
if cls.creds and cls.creds.expired and cls.creds.refresh_token:
cls.creds.refresh(Request())
# Retrieve refresh token and other creds from Oauth flow
else:
flow = InstalledAppFlow.from_client_secrets_file(
resource_path('src/client_secrets.json'),# os.path.abspath(),
scopes = [
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/photoslibrary.readonly'
],
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob:auto'
)
cls.creds = flow.run_local_server(
success_message = 'Signed in sucsessfully, you may close this window.',
)
# Save new credentials
with open(PICKLE_PATH, 'wb') as token:
pickle.dump(cls.creds, token)
cls.build_services(cls.creds)
@classmethod
def build_services(cls, creds):
"""
Rebuild API services for a new set of credentials
"""
cls.photos = build('photoslibrary', 'v1', credentials = creds)
@classmethod
def get_favorites(cls, page_size = None, page_token = None):
cls.ensure_valid_token()
body = {
'filters': {
'featureFilter': {
'includedFeatures': ['FAVORITES']
},
'mediaTypeFilter': {
'mediaTypes': ['PHOTO']
}
},
'pageSize': 100,
'pageToken': page_token
}
try:
return cls.photos.mediaItems().search(body = body).execute()
except:
return cls.get_favorites(page_size, page_token)
@classmethod
def get_all_favorites(cls, page_token = None):
# TODO: This is practically the same code as get_all_album_media_items
# TODO: Consider merging the two methods, as well as get_favorites and get_album_media_items
# TODO: They are operating on the same API endpoint, it makes sense to merge them
print('Get favorites: page token: ' + str(page_token))
page = cls.get_favorites(page_size = 100, page_token = page_token)
media_items = page.get('mediaItems')
next_page_token = page.get('nextPageToken', None)
if next_page_token == None:
return media_items
else:
next_page = cls.get_all_favorites(page_token = next_page_token)
return media_items + next_page
@classmethod
def get_album(cls, album_id):
cls.ensure_valid_token()
try:
return cls.photos.albums().get(albumId = album_id).execute()
except:
# Sometimes returns SSLError. This is a one-off error, try again
return cls.get_album(album_id)
@classmethod
def get_albums(cls):
cls.ensure_valid_token()
body = {
'pageSize': 100
}
try:
return cls.photos.albums().list(pageSize = 50).execute()
except:
return cls.get_albums()
@classmethod
def get_album_media_items(cls, album_id, page_size = None, page_token = None):
print('Getting media items: album: ' + album_id + ' page: ' + str(page_token))
cls.ensure_valid_token()
body = {
'albumId': album_id,
'pageSize': 100,
'pageToken': page_token
}
try:
return cls.photos.mediaItems().search(body = body).execute()
except:
return cls.get_album_media_items(album_id, page_size, page_token)
@classmethod
def get_all_album_media_items(cls, album_id, page_token = None):
# Retreive entire album content recursively
cls.ensure_valid_token()
page = cls.get_album_media_items(album_id, page_size = 100, page_token = page_token)
media_items = page.get('mediaItems')
next_page_token = page.get('nextPageToken', None)
if next_page_token == None:
return media_items
else:
next_page = cls.get_all_album_media_items(album_id, page_token = next_page_token)
return media_items + next_page
@classmethod
def get_media_item(cls, media_item_id):
cls.ensure_valid_token()
try:
return cls.photos.mediaItems().get(mediaItemId = media_item_id).execute()
except:
return cls.get_media_item(media_item_id)
```
|
{
"source": "jelitox/NavConfig",
"score": 2
}
|
#### File: jelitox/NavConfig/setup.py
```python
from os import path
from setuptools import setup, find_packages
def get_path(filename):
return path.join(path.dirname(path.abspath(__file__)), filename)
def readme():
with open(get_path('README.md')) as readme:
return readme.read()
with open(get_path('navconfig/version.py')) as meta:
exec(meta.read())
setup(
name=__title__,
version=__version__,
python_requires=">=3.8.0",
url='https://github.com/phenobarbital/NavConfig',
description=__description__,
long_description=readme(),
long_description_content_type='text/markdown',
license=__license__,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'Environment :: Web Environment',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Framework :: AsyncIO'
],
author='<NAME>',
author_email='<EMAIL>',
packages=find_packages(),
setup_requires=[
'wheel==0.37.0'
],
install_requires=[
'wheel==0.37.0',
'asyncio==3.4.3',
'uvloop==0.16.0',
'python-dotenv==0.15.0',
'configparser==5.0.2',
'PyYAML>=6.0',
'PyDrive==1.3.1',
'pylibmc==1.6.1',
'objectpath==0.6.1',
'iso8601==0.1.13',
'pycparser==2.20',
'redis==3.5.3',
'python-rapidjson==1.5',
'python-logstash-async==2.3.0',
'aiologstash==2.0.0',
'pycryptodomex==3.14.1',
'cryptography==36.0.2',
'aiofiles==0.8.0'
],
project_urls={ # Optional
'Source': 'https://github.com/phenobarbital/NavConfig',
'Funding': 'https://paypal.me/phenobarbital',
'Say Thanks!': 'https://saythanks.io/to/phenobarbital',
},
)
```
|
{
"source": "jelitox/navigator-api",
"score": 3
}
|
#### File: auth/authorizations/allow_hosts.py
```python
import fnmatch
import logging
from .base import BaseAuthzHandler
from navigator.conf import ALLOWED_HOSTS
from aiohttp import web
class authz_allow_hosts(BaseAuthzHandler):
"""
Allowed Hosts.
Check if Origin is on the Allowed Hosts List.
"""
async def check_authorization(self, request: web.Request) -> bool:
origin = request.host if request.host else request.headers["origin"]
for key in ALLOWED_HOSTS:
# print(origin, ALLOWED_HOSTS, key, fnmatch.fnmatch(origin, key))
if fnmatch.fnmatch(origin, key):
return True
return False
```
#### File: auth/session/memcache.py
```python
import asyncio
import rapidjson
from functools import wraps, partial
# memcached
import aiomcache
from aiohttp_session.memcached_storage import MemcachedStorage
from aiohttp_session import setup as setup_session
from .base import AbstractSession
from navigator.conf import (
DOMAIN,
SESSION_URL,
SESSION_TIMEOUT,
MEMCACHE_HOST,
MEMCACHE_PORT
)
class MemcacheSession(AbstractSession):
"""Session Storage based on Memcache."""
_pool = None
async def get_mcache(self, **kwargs):
loop = asyncio.get_event_loop()
return aiomcache.Client(MEMCACHE_HOST, MEMCACHE_PORT, loop=loop)
def configure_session(self, app, **kwargs):
async def _make_mcache():
_encoder = partial(rapidjson.dumps, datetime_mode=rapidjson.DM_ISO8601)
try:
self._pool = await self.get_mcache()
setup_session(
app,
MemcachedStorage(
self._pool,
cookie_name=self.session_name,
encoder=_encoder,
decoder=rapidjson.loads,
max_age=int(SESSION_TIMEOUT)
)
)
except Exception as err:
print(err)
return False
return asyncio.get_event_loop().run_until_complete(
_make_mcache()
)
```
#### File: navigator/libs/cypher.py
```python
import base64
import codecs
import sys
from typing import Any, Callable, List, Literal
from Crypto import Random
from Crypto.Cipher import AES
from rncryptor import DecryptionError, RNCryptor
base64encoded = False
class Cipher(object):
"""Can Encode/Decode a string using AES-256 or RNCryptor."""
key: str = ""
type: str = "AES"
iv: str = ""
BS: int = 16
cipher: Any = None
def __init__(self, key: str, type: str = "AES"):
self.key = key
self.type = type
if type == "AES":
self.iv = Random.new().read(AES.block_size)
self.cipher = AES.new(self.key, AES.MODE_CFB, self.iv)
elif type == "RNC":
self.cipher = RNCryptor()
else:
sys.exit("Not implemented")
def encode(self, message: Any) -> str:
if self.type == "AES":
msg = self.iv + self.cipher.encrypt(message.encode("utf-8"))
elif self.type == "RNC":
msg = self.cipher.encrypt(message, self.key)
if base64encoded:
msg = base64.b64encode(msg)
else:
return ""
if msg:
return codecs.encode(msg, "hex").decode("utf-8")
else:
return ""
def decode(self, passphrase: Any) -> bytes:
msg = codecs.decode(passphrase, "hex")
if self.type == "AES":
try:
return self.cipher.decrypt(msg)[len(self.iv) :].decode("utf-8")
except Exception as e:
print(e)
raise (e)
elif self.type == "RNC":
try:
msg = self.cipher.decrypt(msg, self.key)
if base64encoded:
return base64.b64decode(msg, validate=True)
else:
return msg
except DecryptionError:
raise ValueError("Error decoding message")
except Exception as e:
print(e)
raise (e)
else:
return b""
```
#### File: navigator-api/navigator/middlewares.py
```python
from typing import Any, Awaitable, Callable, Dict, List, Optional
from aiohttp import web
from aiohttp.web import middleware
def check_path(path):
result = True
for r in ["/login", "logout", "/static/", "/signin", "/signout", "/_debugtoolbar/"]:
if path.startswith(r):
result = False
return result
@middleware
async def basic_middleware(
request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]]
):
resp = await handler(request)
return resp
```
#### File: modules/session/django.py
```python
import base64
from typing import Any
from navigator.conf import SESSION_PREFIX
from navigator.modules.session.session import AbstractSession
try:
import ujson as json
except ImportError:
import json
class djangoSession(AbstractSession):
async def decode(self, key: str = None):
try:
result = await self._backend.get("{}:{}".format(SESSION_PREFIX, key))
if result:
data = base64.b64decode(result)
session_data = data.decode("utf-8").split(":", 1)
self._session_key = key
self._session_id = session_data[0]
if session_data:
r = json.loads(session_data[1])
self._parent.set_result(r)
self._parent.id(self._session_id)
return True
else:
return False
except Exception as err:
print(err)
logging.debug("Decoding Error: {}".format(err))
return False
async def encode(self, key, data):
raise NotImplementedError
```
#### File: navigator-api/navigator/resources.py
```python
import asyncio
import json
from functools import wraps
from pathlib import Path
import aiohttp
from aiohttp import WSCloseCode, WSMsgType, web
from aiohttp.http_exceptions import HttpBadRequest
from aiohttp.web import Request, Response
from aiohttp.web_exceptions import HTTPMethodNotAllowed
from aiohttp_swagger import *
from navigator.conf import BASE_DIR
def callback_channel(ws):
def listen(connection, pid, channel, payload):
print("Running Callback Channel for {}: {}".format(channel, payload))
asyncio.ensure_future(ws.send_str(payload))
return listen
async def channel_handler(request):
channel = request.match_info.get("channel", "navigator")
print("Websocket connection starting for channel {}".format(channel))
ws = web.WebSocketResponse()
await ws.prepare(request)
#TODO: connection is not defined, I dont understand this code
socket = {"ws": ws, "conn": connection}
request.app["websockets"].append(socket)
print(socket)
print('Websocket Channel connection ready')
try:
async for msg in ws:
print(msg)
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg.data)
if msg.data == 'close':
await ws.close()
else:
await ws.send_str(msg.data + '/answer')
finally:
request.app["websockets"].remove(socket)
return ws
class WebSocket(web.View):
def __init__(self, *args, **kwargs):
super(WebSocket, self).__init__(*args, **kwargs)
self.app = self.request.app
async def get(self):
# user need a channel:
channel = self.request.match_info.get("channel", "navigator")
print("Websocket connection starting")
ws = web.WebSocketResponse()
await ws.prepare(self.request)
self.request.app["websockets"].append(ws)
print("Websocket connection ready")
# ws.start(request)
# session = await get_session(self.request)
# user = User(self.request.db, {'id': session.get('user')})
# login = await user.get_login()
try:
async for msg in ws:
print(msg)
if msg.type == WSMsgType.TEXT:
print(msg.data)
if msg.data == "close":
await ws.close()
else:
await ws.send_str(msg.data + "/answer")
elif msg.type == WSMsgType.ERROR:
print("ws connection closed with exception %s" % ws.exception())
finally:
self.request.app["websockets"].remove(ws)
print("Websocket connection closed")
return ws
async def ping(request):
"""
---
summary: This end-point allow to test that service is up.
tags:
- Health check
produces:
- text/plain
responses:
"200":
description: successful operation. Return "pong" text
"405":
description: invalid HTTP Method
"""
return web.Response(text="pong")
async def home(request):
"""
---
summary: This end-point is the default "home" for all newly projects
tags:
- Home
- Index
produces:
- text/html
responses:
"200":
description: template "templates/home.html" returned.
"404":
description: Template "templates/home.html" not found.
"""
path = Path(BASE_DIR).joinpath("templates/home.html")
try:
file_path = path
if not file_path.exists():
return web.HTTPNotFound()
return web.FileResponse(file_path)
except Exception as e:
response_obj = {"status": "failed", "reason": str(e)}
return web.Response(
text=json.dumps(response_obj), status=500, content_type="application/json"
)
```
|
{
"source": "jelitox/proxylist",
"score": 3
}
|
#### File: proxylist/proxylists/__init__.py
```python
import asyncio
from .proxies import PROXY_LIST
from .proxies.connections import check_host, check_address
import socket
__all__ = ["PROXY_LIST", "check_host", "check_address"]
async def proxy_list():
proxies = []
for proxy in PROXY_LIST:
p = await proxy().get_list()
proxies = proxies + p
return proxies
def get_proxies():
loop = asyncio.get_event_loop()
return loop.run_until_complete(proxy_list())
```
#### File: proxylists/proxies/freeproxy.py
```python
from .server import ProxyServer
class FreeProxy(ProxyServer):
url = "https://free-proxy-list.net/"
table_attribute: str = 'table table-striped table-bordered'
table_param: str = 'class'
async def get_proxies(self):
proxies = []
try:
path = f'//table[@{self.table_param}="{self.table_attribute}"]'
table = self.parser.xpath(path)[0]
except IndexError as err:
print(err)
return []
for i in table.xpath("//tbody/tr")[:10]:
if i.xpath('.//td[7][contains(text(),"yes")]'):
proxy = ":".join(
[i.xpath(".//td[1]/text()")[0], i.xpath(".//td[2]/text()")[0]]
)
proxies.append(proxy)
return proxies
```
|
{
"source": "jelkink/ucd-prog-2020",
"score": 3
}
|
#### File: jelkink/ucd-prog-2020/simulation.py
```python
from party import Party
from voter import Voter
from tracker import Tracker
from display import Display
from log import Log
from datetime import datetime
#create a simulation class, which creates parties & voters and runs the simulation
#voters,parties,numbers of simulations
class Simulation:
def __init__(self):
self.voters = []
self.parties = []
self.log = Log("simulation.log")
self.tracker = Tracker(self)
self.display = Display(self)
def generate_parties(self, n):
for i in range(n):
name = "P" + format(i, 'd')
self.parties.append(Party(self, name, i))
self.log.write("Created party: " + name)
self.tracker.add_party(name)
def generate_voters(self, n):
for i in range(n):
self.voters.append(Voter(self))
self.log.write("Created {} voters".format(n, "d"))
def get_parties(self):
return self.parties
def get_voters(self):
return self.voters
def set_tracker(self, tracker):
self.tracker = tracker
def run(self, number_of_steps):
self.log.write("Starting simulation for {} loops".format(number_of_steps, "d"))
for i in range(number_of_steps):
print("\nStep {}:".format(i))
for party in self.parties:
party.reset_voters()
for voter in self.voters:
voter.update_vote()
for party in self.parties:
print("Party {} with the {} strategy has {} votes.".format(party.name, party.strategy, party.count_voters()))
party.update_location()
self.display.update_plot()
self.tracker.save_current_state()
self.log.write("Finishing simulation")
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
filename = timestamp + "_party_movement.csv"
self.log.write("Writing CSV file: " + filename)
self.tracker.export_to_csv(filename)
```
|
{
"source": "jelkosz/batuka",
"score": 2
}
|
#### File: jelkosz/batuka/addtoradar.py
```python
import requests
import urllib
import json
import re
import os.path
import logging
import sys
import getopt
sessionId = ''
config = ''
def initialize(kanbanik_pass):
global sessionId
global config
config = load_config()
if kanbanik_pass is not None:
config['kanbanik']['password'] = <PASSWORD>ik_pass
sessionId = execute_kanbanik_command({'commandName': 'login', 'userName': config['kanbanik']['user'], 'password': config['kanbanik']['password']})['sessionId']
def load_config():
with open('/etc/batuka.json') as data_file:
return json.load(data_file)
def execute_kanbanik_command(json_data):
OK_STATUS = 200
ERROR_STATUS= 452
USER_NOT_LOGGED_IN_STATUS = 453
url = config['kanbanik']['url']
headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
resp = requests.post(url, data='command='+json.dumps(json_data), headers=headers)
if resp.status_code == OK_STATUS:
try:
return resp.json()
except TypeError:
return resp.json
return ''
if resp.status_code == ERROR_STATUS or resp.status_code == USER_NOT_LOGGED_IN_STATUS:
logging.error("error while calling kanbanik")
logging.error("response: " + str(resp.status_code))
logging.error("request: " + str(json_data))
return None
def add_bz_pr_tags(task, web_url, api_url):
radar_tag = {'name': 'bzradar', 'description': '', 'onClickUrl': web_url, 'onClickTarget': 1, 'colour': 'orange'}
xgh_tag = {'name': 'xbz:' + api_url, 'description': api_url, 'onClickUrl': web_url, 'onClickTarget': 1, 'colour': 'silver'}
tags = [radar_tag, xgh_tag]
task['taskTags'] = tags
def add_gh_pr_tags(task, web_url, api_url):
radar_tag = {'name': 'ghradar', 'description': '', 'onClickUrl': web_url, 'onClickTarget': 1, 'colour': 'silver'}
xgh_tag = {'name': 'xgh', 'description': api_url, 'onClickUrl': web_url, 'onClickTarget': 1, 'colour': 'silver'}
tags = [radar_tag, xgh_tag]
task['taskTags'] = tags
def create_task_to_add(add_tags, web_url, api_url):
res = {
'commandName': 'createTask',
'name': 'added to radar',
'description': 'd',
'workflowitemId': config['kanbanik']['backlogWorkflowitemId'],
'version': 1,
'projectId': config['bz2kanbanikMappings']['userSpecificMappings']['unknown']['projectId'],
'boardId': config['kanbanik']['boardId'],
'sessionId': sessionId,
'order': 0
}
add_tags(res, web_url, api_url)
res['assignee'] = {'userName': config['bz2kanbanikMappings']['userSpecificMappings']['unknown']['kanbanikName'], 'realName': 'fake', 'pictureUrl': 'fake', 'sessionId': 'fake', 'version': 1}
class_of_service = config['bz2kanbanikMappings']['prioritySeverity2classOfServiceId']['*']
res['classOfService'] = {'id': class_of_service, 'name': 'fake', 'description': 'fake', 'colour': 'fake', 'version': 1}
return res
def process(kanbanik_pass, web_url):
initialize(kanbanik_pass)
try:
if web_url is None:
return
match_obj = re.match(r'https://github.com/(.*)/(.*)/pull/(.*)$', web_url, re.S | re.I)
if match_obj:
# github pull request
api_url = "https://api.github.com/repos/" + match_obj.group(1) + "/" + match_obj.group(2) + "/pulls/" + match_obj.group(3)
to_add = create_task_to_add(
add_gh_pr_tags,
web_url,
api_url)
execute_kanbanik_command(to_add)
if (web_url.startswith("https://bugzilla")):
# bugzilla bug
id_option = web_url.find("?id=")
api_url = None
if id_option != -1:
api_url = web_url[web_url.find("?id=") + 4:]
else:
api_url = web_url[web_url.rfind('/') + 1:]
to_add = create_task_to_add(
add_bz_pr_tags,
web_url,
api_url)
execute_kanbanik_command(to_add)
finally:
execute_kanbanik_command({'commandName': 'logout', 'sessionId': sessionId})
if __name__ == "__main__":
kanbanik_pass = None
url = None
try:
opts, args = getopt.getopt(sys.argv[1:], "hk:u", ["kanbanikpass=", "url="])
except getopt.GetoptError:
print 'addtoradar.py -k <kanbanik password>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'batuka.py -k <kanbanik password>'
sys.exit()
elif opt in ("-k", "--kanbanikpass"):
kanbanik_pass = arg
elif opt in ("-u", "--url"):
url = arg
process(kanbanik_pass, url)
```
|
{
"source": "jelkosz/siall",
"score": 2
}
|
#### File: siall/plugins/gmail.py
```python
from googleapiclient.discovery import build
from common.formatting import formatted_label_from_config
from common.constants import LABEL, TAB, QUERY
from common.googleapi import authenticate_google
def get_config_key():
return 'gmail-filter'
def get_config_params():
return [LABEL, TAB, QUERY]
# takes a list of gmail queries, queries gmail and returns a map of aggregated results
# output: {'tab to which to add the results': ['label', num of messages satisgying the filter, 'link to the gmail satisfying the filter']}
def execute(config):
creds = authenticate_google()
label = formatted_label_from_config(config)
query = config[QUERY]
gmailService = build('gmail', 'v1', credentials=creds, cache_discovery=False)
results = gmailService.users().messages().list(userId='me', q=query, maxResults=100, includeSpamTrash=False).execute()
msgs = results.get('messages', [])
if msgs:
uniqueThreads = len(set([msg['threadId'] for msg in msgs]))
return [label, f'=HYPERLINK(\"https://mail.google.com/mail/u/1/#search/{query}\", \"{uniqueThreads}\")']
else:
return []
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.