Python numpy.abs() Examples
The following are 30
code examples of numpy.abs().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: minitaur_gym_env.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def _reward(self): current_base_position = self.minitaur.GetBasePosition() forward_reward = current_base_position[0] - self._last_base_position[0] drift_reward = -abs(current_base_position[1] - self._last_base_position[1]) shake_reward = -abs(current_base_position[2] - self._last_base_position[2]) self._last_base_position = current_base_position energy_reward = np.abs( np.dot(self.minitaur.GetMotorTorques(), self.minitaur.GetMotorVelocities())) * self._time_step reward = ( self._distance_weight * forward_reward - self._energy_weight * energy_reward + self._drift_weight * drift_reward + self._shake_weight * shake_reward) self._objectives.append( [forward_reward, energy_reward, drift_reward, shake_reward]) return reward
Example #2
Source File: LWS.py From Griffin_lim with MIT License | 6 votes |
def main(): data_foler = "data" wavs = [os.path.join(data_foler, file[:-4]) for file in os.listdir(data_foler) if file.endswith(".wav")] outputs_lws = [file + ".lws.gen.wav" for file in wavs] wavs = [audio.load_wav(wav_path + ".wav", hparams.sample_rate) for wav_path in wavs] lws_processor = lws.lws(512, 128, mode="speech") # 512: window length; 128: window shift i = 0 for x in wavs: X = lws_processor.stft(x) # where x is a single-channel waveform X0 = np.abs(X) # Magnitude spectrogram print('{:6}: {:5.2f} dB'.format('Abs(X)', lws_processor.get_consistency(X0))) X1 = lws_processor.run_lws( X0) # reconstruction from magnitude (in general, one can reconstruct from an initial complex spectrogram) print(X1.shape) print('{:6}: {:5.2f} dB'.format('LWS', lws_processor.get_consistency(X1))) print(X1.shape) wav = lws_processor.istft(X1).astype(np.float32) audio.save_wav(wav, outputs_lws[i]) i += 1
Example #3
Source File: gla_util.py From Deep_VoiceChanger with MIT License | 6 votes |
def __init__(self, wave_len=254, wave_dif=64, buffer_size=5, loop_num=5, window=np.hanning(254)): self.wave_len = wave_len self.wave_dif = wave_dif self.buffer_size = buffer_size self.loop_num = loop_num self.window = window self.wave_buf = np.zeros(wave_len+wave_dif, dtype=float) self.overwrap_buf = np.zeros(wave_dif*buffer_size+(wave_len-wave_dif), dtype=float) self.spectrum_buffer = np.ones((self.buffer_size, self.wave_len), dtype=complex) self.absolute_buffer = np.ones((self.buffer_size, self.wave_len), dtype=complex) self.phase = np.zeros(self.wave_len, dtype=complex) self.phase += np.random.random(self.wave_len)-0.5 + np.random.random(self.wave_len)*1j - 0.5j self.phase[self.phase == 0] = 1 self.phase /= np.abs(self.phase)
Example #4
Source File: gla_gpu.py From Deep_VoiceChanger with MIT License | 6 votes |
def __init__(self, parallel, wave_len=254, wave_dif=64, buffer_size=5, loop_num=5, window=np.hanning(254)): self.wave_len = wave_len self.wave_dif = wave_dif self.buffer_size = buffer_size self.loop_num = loop_num self.parallel = parallel self.window = cp.array([window for _ in range(parallel)]) self.wave_buf = cp.zeros((parallel, wave_len+wave_dif), dtype=float) self.overwrap_buf = cp.zeros((parallel, wave_dif*buffer_size+(wave_len-wave_dif)), dtype=float) self.spectrum_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex) self.absolute_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex) self.phase = cp.zeros((parallel, self.wave_len), dtype=complex) self.phase += cp.random.random((parallel, self.wave_len))-0.5 + cp.random.random((parallel, self.wave_len))*1j - 0.5j self.phase[self.phase == 0] = 1 self.phase /= cp.abs(self.phase)
Example #5
Source File: dataset.py From Deep_VoiceChanger with MIT License | 6 votes |
def wave2input_image(wave, window, pos=0, pad=0): wave_image = np.hstack([wave[pos+i*sride:pos+(i+pad*2)*sride+dif].reshape(height+pad*2, sride) for i in range(256//sride)])[:,:254] wave_image *= window spectrum_image = np.fft.fft(wave_image, axis=1) input_image = np.abs(spectrum_image[:,:128].reshape(1, height+pad*2, 128), dtype=np.float32) np.clip(input_image, 1000, None, out=input_image) np.log(input_image, out=input_image) input_image += bias input_image /= scale if np.max(input_image) > 0.95: print('input image max bigger than 0.95', np.max(input_image)) if np.min(input_image) < 0.05: print('input image min smaller than 0.05', np.min(input_image)) return input_image
Example #6
Source File: mel_features.py From sklearn-audio-transfer-learning with ISC License | 6 votes |
def stft_magnitude(signal, fft_length, hop_length=None, window_length=None): """Calculate the short-time Fourier transform magnitude. Args: signal: 1D np.array of the input time-domain signal. fft_length: Size of the FFT to apply. hop_length: Advance (in samples) between each frame passed to FFT. window_length: Length of each block of samples to pass to FFT. Returns: 2D np.array where each row contains the magnitudes of the fft_length/2+1 unique values of the FFT for the corresponding frame of input samples. """ frames = frame(signal, window_length, hop_length) # Apply frame window to each frame. We use a periodic Hann (cosine of period # window_length) instead of the symmetric Hann of np.hanning (period # window_length-1). window = periodic_hann(window_length) windowed_frames = frames * window return np.abs(np.fft.rfft(windowed_frames, int(fft_length))) # Mel spectrum constants and functions.
Example #7
Source File: test_quantization.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def test_quantize_float32_to_int8(): shape = rand_shape_nd(4) data = rand_ndarray(shape, 'default', dtype='float32') min_range = mx.nd.min(data) max_range = mx.nd.max(data) qdata, min_val, max_val = mx.nd.contrib.quantize(data, min_range, max_range, out_type='int8') data_np = data.asnumpy() min_range = min_range.asscalar() max_range = max_range.asscalar() real_range = np.maximum(np.abs(min_range), np.abs(max_range)) quantized_range = 127.0 scale = quantized_range / real_range assert qdata.dtype == np.int8 assert min_val.dtype == np.float32 assert max_val.dtype == np.float32 assert same(min_val.asscalar(), -real_range) assert same(max_val.asscalar(), real_range) qdata_np = (np.sign(data_np) * np.minimum(np.abs(data_np) * scale + 0.5, quantized_range)).astype(np.int8) assert_almost_equal(qdata.asnumpy(), qdata_np, atol = 1)
Example #8
Source File: dataloader.py From models with MIT License | 6 votes |
def _extract(self, intervals, out, **kwargs): def find_closest(ldm, interval, use_strand=True): """Uses """ # subset the positions to the appropriate strand # and extract the positions ldm_positions = ldm.loc[interval.chrom] if use_strand and interval.strand != ".": ldm_positions = ldm_positions.loc[interval.strand] ldm_positions = ldm_positions.position.values int_midpoint = (interval.end + interval.start) // 2 dist = (ldm_positions - 1) - int_midpoint # -1 for 0, 1 indexed positions if use_strand and interval.strand == "-": dist = - dist return dist[np.argmin(np.abs(dist))] out[:] = np.array([[find_closest(self.landmarks[ldm_name], interval, self.use_strand) for ldm_name in self.columns] for interval in intervals], dtype=float) return out
Example #9
Source File: metric.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def update(self, labels, preds): """Updates the internal evaluation result. Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. """ labels, preds = check_label_shapes(labels, preds, True) for label, pred in zip(labels, preds): label = label.asnumpy() pred = pred.asnumpy() if len(label.shape) == 1: label = label.reshape(label.shape[0], 1) if len(pred.shape) == 1: pred = pred.reshape(pred.shape[0], 1) self.sum_metric += numpy.abs(label - pred).mean() self.num_inst += 1 # numpy.prod(label.shape)
Example #10
Source File: minitaur_gym_env.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def _reward(self): current_base_position = self.minitaur.GetBasePosition() forward_reward = current_base_position[0] - self._last_base_position[0] # Cap the forward reward if a cap is set. forward_reward = min(forward_reward, self._forward_reward_cap) # Penalty for sideways translation. drift_reward = -abs(current_base_position[1] - self._last_base_position[1]) # Penalty for sideways rotation of the body. orientation = self.minitaur.GetBaseOrientation() rot_matrix = pybullet.getMatrixFromQuaternion(orientation) local_up_vec = rot_matrix[6:] shake_reward = -abs(np.dot(np.asarray([1, 1, 0]), np.asarray(local_up_vec))) energy_reward = -np.abs( np.dot(self.minitaur.GetMotorTorques(), self.minitaur.GetMotorVelocities())) * self._time_step objectives = [forward_reward, energy_reward, drift_reward, shake_reward] weighted_objectives = [ o * w for o, w in zip(objectives, self._objective_weights) ] reward = sum(weighted_objectives) self._objectives.append(objectives) return reward
Example #11
Source File: system_eq.py From BiblioPixelAnimations with MIT License | 6 votes |
def get_audio_data(self): frames = self.rec.get_frames() result = [0] * self.bins if len(frames) > 0: # keeps only the last frame current_frame = frames[-1] # plots the time signal # self.line_top.set_data(self.time_vect, current_frame) # computes and plots the fft signal fft_frame = np.fft.rfft(current_frame) if self.auto_gain: fft_frame /= np.abs(fft_frame).max() else: fft_frame *= (1 + self.gain) / 5000000. fft_frame = np.abs(fft_frame) if self.log_scale: fft_frame = np.log10(np.add(1, np.multiply(10, fft_frame))) result = [min(int(max(i, 0.) * 1023), 1023) for i in fft_frame][0:self.bins] return result
Example #12
Source File: system_eq.py From BiblioPixelAnimations with MIT License | 6 votes |
def get_audio_data(self): frames = self.rec.get_frames() result = [0] * self.bins if len(frames) > 0: # keeps only the last frame current_frame = frames[-1] # plots the time signal # self.line_top.set_data(self.time_vect, current_frame) # computes and plots the fft signal fft_frame = np.fft.rfft(current_frame) if self.auto_gain: fft_frame /= np.abs(fft_frame).max() else: fft_frame *= (1 + self.gain) / 5000000. fft_frame = np.abs(fft_frame) if self.log_scale: fft_frame = np.log10(np.add(1, np.multiply(10, fft_frame))) result = [min(int(max(i, 0.) * 1023), 1023) for i in fft_frame][0:self.bins] return result
Example #13
Source File: minitaur_duck_gym_env.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def _reward(self): current_base_position = self.minitaur.GetBasePosition() forward_reward = current_base_position[0] - self._last_base_position[0] drift_reward = -abs(current_base_position[1] - self._last_base_position[1]) shake_reward = -abs(current_base_position[2] - self._last_base_position[2]) self._last_base_position = current_base_position energy_reward = np.abs( np.dot(self.minitaur.GetMotorTorques(), self.minitaur.GetMotorVelocities())) * self._time_step reward = ( self._distance_weight * forward_reward - self._energy_weight * energy_reward + self._drift_weight * drift_reward + self._shake_weight * shake_reward) self._objectives.append( [forward_reward, energy_reward, drift_reward, shake_reward]) return reward
Example #14
Source File: test_train.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 6 votes |
def _project_im_rois(im_rois, scales): """Project image RoIs into the image pyramid built by _get_image_blob. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates scales (list): scale factors as returned by _get_image_blob Returns: rois (ndarray): R x 4 matrix of projected RoI coordinates levels (list): image pyramid levels used by each projected RoI """ im_rois = im_rois.astype(np.float, copy=False) if len(scales) > 1: widths = im_rois[:, 2] - im_rois[:, 0] + 1 heights = im_rois[:, 3] - im_rois[:, 1] + 1 areas = widths * heights scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1)[:, np.newaxis] else: levels = np.zeros((im_rois.shape[0], 1), dtype=np.int) rois = im_rois * scales[levels] return rois, levels
Example #15
Source File: test.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 6 votes |
def _project_im_rois(im_rois, scales): """Project image RoIs into the image pyramid built by _get_image_blob. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates scales (list): scale factors as returned by _get_image_blob Returns: rois (ndarray): R x 4 matrix of projected RoI coordinates levels (list): image pyramid levels used by each projected RoI """ im_rois = im_rois.astype(np.float, copy=False) if len(scales) > 1: widths = im_rois[:, 2] - im_rois[:, 0] + 1 heights = im_rois[:, 3] - im_rois[:, 1] + 1 areas = widths * heights scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1)[:, np.newaxis] else: levels = np.zeros((im_rois.shape[0], 1), dtype=np.int) rois = im_rois * scales[levels] return rois, levels
Example #16
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 6 votes |
def is_integer(number, precision=10e-10): """ Check if number is convertible to integer. :Parameters: #. number (str, number): Input number. #. precision (number): To avoid floating errors, a precision should be given. :Returns: #. result (bool): True if convertible, False otherwise. """ if isinstance(number, (int, long)): return True try: number = float(number) except: return False else: if np.abs(number-int(number)) < precision: return True else: return False
Example #17
Source File: gym_manipulator_envs.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
def _step(self, a): assert (not self.scene.multiplayer) self.robot.apply_action(a) self.scene.global_step() state = self.robot.calc_state() # sets self.to_target_vec potential_old = self.potential self.potential = self.robot.calc_potential() electricity_cost = ( -0.10 * (np.abs(a[0] * self.robot.theta_dot) + np.abs(a[1] * self.robot.gamma_dot)) # work torque*angular_velocity - 0.01 * (np.abs(a[0]) + np.abs(a[1])) # stall torque require some energy ) stuck_joint_cost = -0.1 if np.abs(np.abs(self.robot.gamma) - 1) < 0.01 else 0.0 self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)] self.HUD(state, a, False) return state, sum(self.rewards), False, {}
Example #18
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def jacobian(self, p, into=None): # transpose to be 3 x 2 x n p = np.transpose(np.reshape(p, (-1, 3, 2)), (1,2,0)) # First, get the two legs... (dx_ab, dy_ab) = p[1] - p[0] (dx_ac, dy_ac) = p[2] - p[0] (dx_bc, dy_bc) = p[2] - p[1] # now, the area is half the z-value of the cross-product... sarea0 = 0.5 * (dx_ab*dy_ac - dx_ac*dy_ab) # but we want to abs it dsarea0 = np.sign(sarea0) z = np.transpose([[-dy_bc,dx_bc], [dy_ac,-dx_ac], [-dy_ab,dx_ab]], (2,0,1)) z = times(0.5*dsarea0, z) m = numel(p) n = p.shape[2] ii = (np.arange(n) * np.ones([6, n])).T.flatten() z = sps.csr_matrix((z.flatten(), (ii, np.arange(len(ii)))), shape=(n, m)) return safe_into(into, z)
Example #19
Source File: robot_locomotors.py From soccer-matlab with BSD 2-Clause "Simplified" License | 5 votes |
def calc_state(self): j = np.array([j.current_relative_position() for j in self.ordered_joints], dtype=np.float32).flatten() # even elements [0::2] position, scaled to -1..+1 between limits # odd elements [1::2] angular speed, scaled to show -1..+1 self.joint_speeds = j[1::2] self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99) body_pose = self.robot_body.pose() parts_xyz = np.array([p.pose().xyz() for p in self.parts.values()]).flatten() self.body_xyz = ( parts_xyz[0::3].mean(), parts_xyz[1::3].mean(), body_pose.xyz()[2]) # torso z is more informative than mean z self.body_rpy = body_pose.rpy() z = self.body_xyz[2] if self.initial_z == None: self.initial_z = z r, p, yaw = self.body_rpy self.walk_target_theta = np.arctan2(self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]) self.walk_target_dist = np.linalg.norm( [self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]]) angle_to_target = self.walk_target_theta - yaw rot_speed = np.array( [[np.cos(-yaw), -np.sin(-yaw), 0], [np.sin(-yaw), np.cos(-yaw), 0], [ 0, 0, 1]] ) vx, vy, vz = np.dot(rot_speed, self.robot_body.speed()) # rotate speed back to body point of view more = np.array([ z-self.initial_z, np.sin(angle_to_target), np.cos(angle_to_target), 0.3* vx , 0.3* vy , 0.3* vz , # 0.3 is just scaling typical speed into -1..+1, no physical sense here r, p], dtype=np.float32) return np.clip( np.concatenate([more] + [j] + [self.feet_contact]), -5, +5)
Example #20
Source File: plot_lfads.py From DOTA_models with Apache License 2.0 | 5 votes |
def _plot_item(W, name, full_name, nspaces): plt.figure() if W.shape == (): print(name, ": ", W) elif W.shape[0] == 1: plt.stem(W.T) plt.title(full_name) elif W.shape[1] == 1: plt.stem(W) plt.title(full_name) else: plt.imshow(np.abs(W), interpolation='nearest', cmap='jet'); plt.colorbar() plt.title(full_name)
Example #21
Source File: replay_buffer.py From DOTA_models with Apache License 2.0 | 5 votes |
def update_last_batch(self, delta): """Update last batch idxs with new priority.""" self.priorities[self.last_batch] = np.abs(delta) self.priorities[0:self.init_length] = np.max( self.priorities[self.init_length:])
Example #22
Source File: utils.py From GST-Tacotron with MIT License | 5 votes |
def griffin_lim(spectrogram): '''Applies Griffin-Lim's raw. ''' X_best = copy.deepcopy(spectrogram) for i in range(hp.n_iter): X_t = invert_spectrogram(X_best) est = librosa.stft(X_t, hp.n_fft, hp.hop_length, win_length=hp.win_length) phase = est / np.maximum(1e-8, np.abs(est)) X_best = spectrogram * phase X_t = invert_spectrogram(X_best) y = np.real(X_t) return y
Example #23
Source File: metric.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def create(metric, *args, **kwargs): """Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. - A list, each element of which is a metric or a metric name. - An evaluation function that computes custom metric for a given batch of labels and predictions. *args : list Additional arguments to metric constructor. Only used when metric is str. **kwargs : dict Additional arguments to metric constructor. Only used when metric is str Examples -------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label - pred)) ... >>> metric1 = mx.metric.create('acc') >>> metric2 = mx.metric.create(custom_metric) >>> metric3 = mx.metric.create([metric1, metric2, 'rmse']) """ if callable(metric): return CustomMetric(metric, *args, **kwargs) elif isinstance(metric, list): composite_metric = CompositeEvalMetric() for child_metric in metric: composite_metric.add(create(child_metric, *args, **kwargs)) return composite_metric return _create(metric, *args, **kwargs)
Example #24
Source File: profiler_ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def test_ndarray_copy(): c = mx.nd.array(np.random.uniform(-10, 10, (10, 10))) d = c.copyto(mx.Context('cpu', 0)) assert np.sum(np.abs(c.asnumpy() != d.asnumpy())) == 0.0
Example #25
Source File: profiler_ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def reldiff(a, b): diff = np.abs(a - b) norm = np.abs(a) reldiff = np.max(diff / (norm + 1e-7)) return reldiff
Example #26
Source File: PairDistributionConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def check_experimental_data(self, experimentalData): """ Check whether experimental data is correct. :Parameters: #. experimentalData (object): Experimental data to check. :Returns: #. result (boolean): Whether it is correct or not. #. message (str): Checking message that explains whats's wrong with the given data. """ if not isinstance(experimentalData, np.ndarray): return False, "experimentalData must be a numpy.ndarray" if experimentalData.dtype.type is not FLOAT_TYPE: return False, "experimentalData type must be %s"%FLOAT_TYPE if len(experimentalData.shape) !=2: return False, "experimentalData must be of dimension 2" if experimentalData.shape[1] !=2: return False, "experimentalData must have only 2 columns" # check distances order inOrder = (np.array(sorted(experimentalData[:,0]), dtype=FLOAT_TYPE)-experimentalData[:,0])<=PRECISION if not np.all(inOrder): return False, "experimentalData distances are not sorted in order" if experimentalData[0][0]<0: return False, "experimentalData distances min value is found negative" bin = experimentalData[1,0] -experimentalData[0,0] bins = experimentalData[1:,0]-experimentalData[0:-1,0] for b in bins: if np.abs(b-bin)>PRECISION: return False, "experimentalData distances bins are found not coherent" # data format is correct return True, ""
Example #27
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def find_extrema(x, max = True, min = True, strict = False, withend = False): """ Get a vector extrema indexes and values. :Parameters: #. max (boolean): Whether to index the maxima. #. min (boolean): Whether to index the minima. #. strict (boolean): Whether not to index changes to zero gradient. #. withend (boolean): Whether to always include x[0] and x[-1]. :Returns: #. indexes (numpy.ndarray): Extrema indexes. #. values (numpy.ndarray): Extrema values. """ # This is the gradient dx = np.empty(len(x)) dx[1:] = np.diff(x) dx[0] = dx[1] # Clean up the gradient in order to pick out any change of sign dx = np.sign(dx) # define the threshold for whether to pick out changes to zero gradient threshold = 0 if strict: threshold = 1 # Second order diff to pick out the spikes d2x = np.diff(dx) if max and min: d2x = abs(d2x) elif max: d2x = -d2x # Take care of the two ends if withend: d2x[0] = 2 d2x[-1] = 2 # Sift out the list of extremas ind = np.nonzero(d2x > threshold)[0] return ind, x[ind]
Example #28
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def orient(xyzArray, arrayAxis, alignToAxis): """ Rotates xyzArray using the rotation matrix that rotates and aligns arrayAxis to alignToAXis. :Parameters: #. xyzArray (numpy.ndarray): The xyz (N,3) array to rotate. #. arrayAxis (list, tuple, numpy.ndarray): xyzArray axis. #. alignToAxis (list, tuple, numpy.ndarray): The axis to align to. """ # normalize alignToAxis alignToAxisNorm = np.linalg.norm(alignToAxis) assert alignToAxisNorm>0, LOGGER.error("alignToAxis returned 0 norm") alignToAxis = np.array(alignToAxis, dtype=FLOAT_TYPE)/alignToAxisNorm # normalize arrayAxis arrayAxisNorm = np.linalg.norm(arrayAxis) assert arrayAxisNorm>0, LOGGER.error("arrayAxis returned 0 norm") arrayAxis = np.array(arrayAxis, dtype=FLOAT_TYPE)/arrayAxisNorm # calculate rotationAngle dotProduct = np.dot(arrayAxis, alignToAxis) if np.abs(dotProduct-1) <= PRECISION : rotationAngle = 0 elif np.abs(dotProduct+1) <= PRECISION : rotationAngle = PI else: rotationAngle = np.arccos( dotProduct ) if np.isnan(rotationAngle) or np.abs(rotationAngle) <= PRECISION : return xyzArray # calculate rotation axis. if np.abs(rotationAngle-PI) <= PRECISION: rotationAxis = get_random_perpendicular_vector(arrayAxis) else: rotationAxis = np.cross(alignToAxis, arrayAxis) #rotationAxis /= np.linalg.norm(rotationAxis) # calculate rotation matrix rotationMatrix = get_rotation_matrix(rotationAxis, rotationAngle) # rotate and return return rotate(xyzArray , rotationMatrix)
Example #29
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def get_orientation_matrix(arrayAxis, alignToAxis): """ Get the rotation matrix that aligns arrayAxis to alignToAxis :Parameters: #. arrayAxis (list, tuple, numpy.ndarray): xyzArray axis. #. alignToAxis (list, tuple, numpy.ndarray): The axis to align to. """ # normalize alignToAxis alignToAxisNorm = np.linalg.norm(alignToAxis) assert alignToAxisNorm>0, LOGGER.error("alignToAxis returned 0 norm") alignToAxis = np.array(alignToAxis, dtype=FLOAT_TYPE)/alignToAxisNorm # normalize arrayAxis arrayAxisNorm = np.linalg.norm(arrayAxis) assert arrayAxisNorm>0, LOGGER.error("arrayAxis returned 0 norm") arrayAxis = np.array(arrayAxis, dtype=FLOAT_TYPE)/arrayAxisNorm # calculate rotationAngle dotProduct = np.dot(arrayAxis, alignToAxis) if np.abs(dotProduct-1) <= PRECISION : rotationAngle = 0 elif np.abs(dotProduct+1) <= PRECISION : rotationAngle = PI else: rotationAngle = np.arccos( dotProduct ) if np.isnan(rotationAngle) or np.abs(rotationAngle) <= PRECISION : return np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]]).astype(FLOAT_TYPE) # calculate rotation axis. if np.abs(rotationAngle-PI) <= PRECISION: rotationAxis = get_random_perpendicular_vector(arrayAxis) else: rotationAxis = np.cross(alignToAxis, arrayAxis) #rotationAxis /= np.linalg.norm(rotationAxis) # calculate rotation matrix return get_rotation_matrix(rotationAxis, rotationAngle)
Example #30
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def get_random_perpendicular_vector(vector): """ Get random normalized perpendicular vector to a given vector. :Parameters: #. vector (numpy.ndarray, list, set, tuple): Given vector to compute a random perpendicular vector to it. :Returns: #. perpVector (numpy.ndarray): Perpendicular vector of type fullrmc.Globals.FLOAT_TYPE """ vectorNorm = np.linalg.norm(vector) assert vectorNorm, LOGGER.error("vector returned 0 norm") # easy cases if np.abs(vector[0])<PRECISION: return np.array([1,0,0], dtype=FLOAT_TYPE) elif np.abs(vector[1])<PRECISION: return np.array([0,1,0], dtype=FLOAT_TYPE) elif np.abs(vector[2])<PRECISION: return np.array([0,0,1], dtype=FLOAT_TYPE) # generate random vector randVect = 1-2*np.random.random(3) randvect = np.array([vector[idx]*randVect[idx] for idx in range(3)]) # get perpendicular vector perpVector = np.cross(randvect,vector) # normalize, coerce and return return np.array(perpVector/np.linalg.norm(perpVector), dtype=FLOAT_TYPE)