How do I translate an atom using Biopython? The transform method is throwing error - biopython

I am trying to transform the coordinates of atom but when I am using random vector; I am getting this error -
rotation = rotmat(pi, Vector(np.random.rand(3,1)))
File "/home/sanu/.local/lib/python3.8/site-packages/Bio/PDB/vectors.py", line 204, in rotmat
rot = numpy.dot(refmat(q, -p), refmat(p, -p))
File "/home/sanu/.local/lib/python3.8/site-packages/Bio/PDB/vectors.py", line 167, in refmat
q = q.normalized()
AttributeError: 'float' object has no attribute 'normalized'
for model in simulation_pdb:
for chain in model:
if chain.get_id() == "Y":
for residue in chain:
for atom in residue:
#translation = np.random.rand(3,1)
#rotation = rotmat(pi, Vector(np.random.rand(3,1)))
translation = array((np.random.rand(3,1)), 'f')
rotation = rotmat(np.pi, array(np.random.rand(3,1)))
atom.transform(rotation, translation)
print(atom, atom.get_vector())
In case of the above code (as it is, no random vector), I am getting this error -
rotation = rotmat(np.pi, array(np.random.rand(3,1)))
File "/home/sanu/.local/lib/python3.8/site-packages/Bio/PDB/vectors.py", line 204, in rotmat
rot = numpy.dot(refmat(q, -p), refmat(p, -p))
File "/home/sanu/.local/lib/python3.8/site-packages/Bio/PDB/vectors.py", line 166, in refmat
p = p.normalized()
AttributeError: 'numpy.ndarray' object has no attribute 'normalized'
What am I doing wrong here? Seems like the transform function is expecting some other datatype; which I don't know.
Edit1 - from Biopython's documentation -
def transform(self, rot, tran):
"""Apply rotation and translation to the atomic coordinates.
:param rot: A right multiplying rotation matrix
:type rot: 3x3 Numeric array
:param tran: the translation vector
:type tran: size 3 Numeric array
Examples
--------
This is an incomplete but illustrative example::
from numpy import pi, array
from Bio.PDB.vectors import Vector, rotmat
rotation = rotmat(pi, Vector(1, 0, 0))
translation = array((0, 0, 1), 'f')
atom.transform(rotation, translation)
"""
self.coord = np.dot(self.coord, rot) + tran

Related

Concat tensors in tensorflow TF 2.0

I have two tensors os shapes [2,1,30] and [2,181,30]. I would like to append them to be of shape [2,182,30]. Any ideas how to achieve that?
I couldn't use either tf.concat or tf.stack as they both result in error
tensorflow.python.framework.errors_impl.InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [2,1,30] vs. shape[1] = [2,181,30]
[[{{node concat}}]]
You probably didn't specify the axis for tf.concat
a = tf.random.normal(shape=[2,1,30])
b = tf.random.normal(shape=[2, 181, 30])
c = tf.concat([a,b], axis=1)

ValueError: "input_length" is 47, but received input has shape (None, 47, 18704)

input = Input(shape=(47,vocab_length))
print(input.shape)
X = Embedding(input_dim=vocab_length,output_dim = embedding_size,input_length=47)(input)
print(X.shape)
X = Reshape([47,embedding_size,1])(X)
Above given is the part of my code, here I am getting an error in Embedding layer, as shown-
ValueError: "input_length" is 47, but received input has shape (None, 47, 18704)
Note here that vocab_length and embedding_size are integers.
Please help me out!
Thanks
So, further I tried making my own customed layer similar to the Embedding layer. But in it I am getting some error as described below.
'''
from keras import backend as K
from keras.engine.topology import Layer
class MyLayer(Layer):
def __init__(self,shape_0=1,shape_1=1):
super(MyLayer, self).__init__()
self.w = self.add_weight(
shape=(shape_0,shape_1), initializer="random_normal", trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w)
embedding_size = 300
vocab_length = 18704
input = Input(shape=(47,vocab_length))
X = MyLayer(vocab_length,embedding_size)(input)
X = Reshape([47,embedding_size,1])(X)
'''
Here it gives error in Reshape layer saying the target length should be same as the original length of the input. But it is same i.e. input shape = [47,embedding_size] and target size = [47,embedding_size,1]
'''
ValueError: total size of new array must be unchanged
'''

Tensorflow dynamic_rnn TypeError: 'Tensor' object is not iterable

I'm trying to get a basic LSTM working in TensorFlow. I'm receiving the following error:
TypeError: 'Tensor' object is not iterable.
The offending line is:
rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, x, sequence_length=seqlen,
initial_state=init_state,)`
I'm using version 1.0.1 on windows 7. My inputs and label have the following shapes
x_shape = (50, 40, 18), y_shape = (50, 40)
Where:
batch size = 50
sequence length = 40
input vector length at each step = 18
I'm building my graph as follows
def build_graph(learn_rate, seq_len, state_size=32, batch_size=5):
# use a fixed sequence length
seqlen = tf.constant(seq_len, shape=[batch_size],dtype=tf.int32)
# Placeholders
x = tf.placeholder(tf.float32, [batch_size, None, 18])
y = tf.placeholder(tf.float32, [batch_size, None])
keep_prob = tf.constant(1.0)
# RNN
cell = tf.contrib.rnn.LSTMCell(state_size)
init_state = tf.get_variable('init_state', [1, state_size],
initializer=tf.constant_initializer(0.0))
init_state = tf.tile(init_state, [batch_size, 1])
rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, x, sequence_length=seqlen,
initial_state=init_state,)
# Add dropout, as the model otherwise quickly overfits
rnn_outputs = tf.nn.dropout(rnn_outputs, keep_prob)
# Prediction layer
with tf.variable_scope('prediction'):
W = tf.get_variable('W', [state_size, num_classes])
b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(0.0))
preds = tf.tanh(tf.matmul(rnn_outputs, W) + b)
# MSE
loss = tf.square(tf.subtract(y, preds))
# loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits, y))
train_step = tf.train.AdamOptimizer(learn_rate).minimize(loss)
Can anyone tell me what I am missing?
Sequence length should be iterable e.g. a list or tensor, not a scalar. In your case specifically, you need to replace sequence length = 40 with a list of the lengths of each input. For instance, if your first sequence has 10 steps, the second 13 and the third 18, you would pass in [10, 13, 18]. This lets TensorFlow's dynamic RNN know how many steps to unroll for (I believe it uses a while loop internally).

ValueError: could not broadcast input array from shape (700,227,3) into shape (0,227,3)

Please help me to rectify the errors. This is an Opencv feature extraction code.
from __future__ import division
import numpy as np
import cv2
ESC=27
camera = cv2.VideoCapture(0)
orb = cv2.ORB()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
imgTrainColor=cv2.imread('train.jpg')
imgTrainGray = cv2.cvtColor(imgTrainColor, cv2.COLOR_BGR2GRAY)
kpTrain = orb.detect(imgTrainGray,None)
kpTrain, desTrain = orb.compute(imgTrainGray, kpTrain)
firsttime=True
while True:
ret, imgCamColor = camera.read()
imgCamGray = cv2.cvtColor(imgCamColor, cv2.COLOR_BGR2GRAY)
kpCam = orb.detect(imgCamGray,None)
kpCam, desCam = orb.compute(imgCamGray, kpCam)
matches = bf.match(desCam,desTrain)
dist = [m.distance for m in matches]
thres_dist = (sum(dist) / len(dist)) * 0.5
matches = [m for m in matches if m.distance < thres_dist]
if firsttime==True:
h1, w1 = imgCamColor.shape[:2]
h2, w2 = imgTrainColor.shape[:2]
nWidth = w1+w2
nHeight = max(h1, h2)
hdif = (h1-h2)/2
firsttime=False
result = np.zeros((nHeight, nWidth, 3), np.uint8)
result[hdif:hdif+h2, :w2] = imgTrainColor
result[:h1, w2:w1+w2] = imgCamColor
for i in range(len(matches)):
pt_a=(int(kpTrain[matches[i].trainIdx].pt[0]), int(kpTrain[matches[i].trainIdx].pt[1]+hdif))
pt_b=(int(kpCam[matches[i].queryIdx].pt[0]+w2), int(kpCam[matches[i].queryIdx].pt[1]))
cv2.line(result, pt_a, pt_b, (255, 0, 0))
cv2.imshow('Camara', result)
key = cv2.waitKey(30)
if key == ESC:
break
cv2.destroyAllWindows()
camera.release()
ERRORS APPEARING:
Traceback (most recent call last):
File "sift.py", line 39, in
result[hdif:hdif+h2, :w2] = imgTrainColor
ValueError: could not broadcast input array from shape (700,227,3) into shape (0,227,3)
Without digging through your code in detail
result[hdif:hdif+h2, :w2] = imgTrainColor
... from shape (700,227,3) into shape (0,227,3)
I duduce that imgTrainColor is 3d with shape (700,227,3).
result must has (3,) last dimension; the :w2 must be slicing 227 vales. But the hdif:hdif+h2 is slicing 0, probably because h2 is 0.
In other words, you are trying to put the imgTrainColor values into a block of result that is too small.
Can I leave to you to figure out why h2 is wrong? Another possibility is the hdif is too large (>700). You may need to print those indexing values just before this error.
Oh, and clean up the indentation.

OpenCV 2.4 estimateAffine3D in Python

I'm trying to use the method cv2.estimateAffine3D but without success. Here is my code sample :
import numpy as np
import cv2
shape = (1, 4, 3)
source = np.zeros(shape, np.float32)
# [x, y, z]
source[0][0] = [857, 120, 854]
source[0][1] = [254, 120, 855]
source[0][2] = [256, 120, 255]
source[0][3] = [858, 120, 255]
target = source * 10
retval, M, inliers = cv2.estimateAffine3D(source, target)
When I try to run this sample, I obtain the same error as this other post here.
I'm using OpenCV 2.4.3 and Python 2.7.3
Please help me!
This is a known bug that is fixed in 2.4.4.
http://code.opencv.org/issues/2375
If you just need rigid (rotation + translation) alignment, here's the standard method:
def get_rigid(src, dst): # Assumes both or Nx3 matrices
src_mean = src.mean(0)
dst_mean = dst.mean(0)
# Compute covariance
H = reduce(lambda s, (a,b) : s + np.outer(a, b), zip(src - src_mean, dst - dst_mean), np.zeros((3,3)))
u, s, v = np.linalg.svd(H)
R = v.T.dot(u.T) # Rotation
T = - R.dot(src_mean) + dst_mean # Translation
return np.hstack((R, T[:, np.newaxis]))
Change covariance toH = reduce(lambda s, a: s + np.outer(a[0], a[1]), zip(src - src_mean, dst - dst_mean), np.zeros((3,3)))
for python3 in previous post. Can't comment bacause of reputation score.

Resources