Here are the examples of the python api numpy.argwhere taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
588 Examples
3
Source : Filters.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def adjustXPositions(self, pts, data):
"""Return a list of Point() where the x position is set to the nearest x value in *data* for each point in *pts*."""
points = []
timeIndices = []
for p in pts:
x = np.argwhere(abs(data - p.x()) == abs(data - p.x()).min())
points.append(Point(data[x], p.y()))
timeIndices.append(x)
return points, timeIndices
class AdaptiveDetrend(CtrlNode):
3
Source : env.py
with MIT License
from activatedgeek
with MIT License
from activatedgeek
def _sample_tile_locations(self, board, count=1):
"""Sample grid locations with no tile."""
zero_locs = np.argwhere(board == 0)
zero_indices = self.np_random.choice(
len(zero_locs), size=count)
zero_pos = zero_locs[zero_indices]
zero_pos = list(zip(*zero_pos))
return zero_pos
def _place_random_tiles(self, board, count=1):
3
Source : data_utils.py
with Apache License 2.0
from adrian9631
with Apache License 2.0
from adrian9631
def value2pos(abstract, value, vocab):
poss = []
unk_id = vocab.word2id(UNKNOWN_TOKEN)
for sent in abstract:
pos=[]
for i in sent:
if i in value:
pos.append(np.argwhere(value==i)[0])
else:
pos.append(np.argwhere(value==unk_id)[0])
poss.append(np.array(pos))
return np.array(poss)
def article2ids(article, vocab):
3
Source : gym_utils.py
with MIT License
from akzaidi
with MIT License
from akzaidi
def find_ball(obs, default=None):
ball_area = obs[37:193, :, 0]
res = np.argwhere(ball_area == 236)
if not res:
return default
else:
x, y = res[0]
x += 37
return x, y
def wrapped_pong_factory(warm_up_examples=0, action_space_reduction=False,
3
Source : gym_utils.py
with MIT License
from akzaidi
with MIT License
from akzaidi
def find_ball(ob, default=None):
off_x = 63
clipped_ob = ob[off_x:-21, :, 0]
pos = np.argwhere(clipped_ob == 200)
if not pos.size:
return default
x = off_x + pos[0][0]
y = 0 + pos[0][1]
return x, y
def process_observation(self, obs):
3
Source : _proximity_forest.py
with BSD 3-Clause "New" or "Revised" License
from alan-turing-institute
with BSD 3-Clause "New" or "Revised" License
from alan-turing-institute
def grow(self):
"""Grow the stump, creating branches for each exemplar."""
n_exemplars = len(self.y_exemplar)
indices = self.find_closest_exemplar_indices(self.X)
self.X_branches = [None] * n_exemplars
self.y_branches = [None] * n_exemplars
for index in range(n_exemplars):
instance_indices = np.argwhere(indices == index)
instance_indices = np.ravel(instance_indices)
self.X_branches[index] = self.X.iloc[instance_indices, :]
y = np.take(self.y, instance_indices)
self.y_branches[index] = y
self.entropy = self.get_gain(self.y, self.y_branches)
return self
def _predict(self, X):
3
Source : presnet.py
with MIT License
from alecwangcq
with MIT License
from alecwangcq
def forward(self, input_tensor):
"""
Parameter
---------
input_tensor: (N,C,H,W). It should be the output of BatchNorm2d layer.
"""
selected_index = np.squeeze(np.argwhere(self.indexes.data.cpu().numpy()))
if selected_index.size == 1:
selected_index = np.resize(selected_index, (1,))
output = input_tensor[:, selected_index, :, :]
return output
class Bottleneck(nn.Module):
3
Source : dataTools.py
with GNU General Public License v3.0
from alelab-upenn
with GNU General Public License v3.0
from alelab-upenn
def remove_encoded_images(self, freq=1e3):
widx = self.vocab.index('ax')
wc = self.data[:,widx].toarray().squeeze()
idx = np.argwhere(wc < freq).squeeze()
self.keep_documents(idx)
class Text20News(TextDataset):
3
Source : tree_attention.py
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
def _get_unpadded_matrix_for_example(input_matrix, idx, mask) -> str:
input_matrix_for_example = input_matrix.data.cpu().numpy()[idx]
mask_for_example = mask.data.cpu().numpy()[idx]
if mask_for_example.shape != input_matrix_for_example.shape:
raise ValueError("Different shapes for mask and input: {} vs {}".format(
mask_for_example.shape, input_matrix_for_example.shape))
if mask_for_example.ndim != 2:
raise ValueError("Cannot handle more than two dimensions. Found {}".format(
mask_for_example.shape))
# Find the max rows and columns to print
zero_rows = numpy.argwhere(mask_for_example[:, 0] == 0)
max_rows = numpy.min(zero_rows) if zero_rows.size != 0 else mask_for_example.shape[0]
zero_cols = numpy.argwhere(mask_for_example[0, :] == 0)
max_cols = numpy.min(zero_cols) if zero_cols.size != 0 else mask_for_example.shape[1]
return array2string(input_matrix_for_example[:max_rows, :max_cols],
precision=4, suppress_small=True)
@staticmethod
3
Source : positioning.py
with MIT License
from axelbr
with MIT License
from axelbr
def get_pose(self, agent_index: int) -> Pose:
center_corridor = np.argwhere(self._obstacles.map > self._obstacle_margin)
delta_progress_next_pos = 0.025
if self._alternate_direction and random.random() < 0.5:
delta_progress_next_pos = -delta_progress_next_pos
x, y, angle = self._random_position(self._progress, center_corridor, delta_progress_next_pos)
return (x, y, 0.05), (0, 0, angle)
def _random_position(self, progress_map, sampling_map, delta_progress_next_pos=0.025):
3
Source : _crystal_dataset.py
with MIT License
from BaratiLab
with MIT License
from BaratiLab
def _updated_train_cifs(self, train_idx, num_transform):
'''
When doing k-fold CV. This function adds the augmented cif names to the train_idx
'''
updated_train_idx = []
for idx in train_idx:
num_idx = int(np.argwhere(self.id_prop_augment[:,0] == idx[0])[0][0])
for jdx in range(num_transform+1):
updated_train_idx.append(self.id_prop_augment_all[(num_transform+1)*num_idx+jdx])
return np.array(updated_train_idx)
def _k_fold_cross_validation(self):
3
Source : _crystal_dataset.py
with MIT License
from BaratiLab
with MIT License
from BaratiLab
def _match_idx(self, cif_idxs):
'''
Match function that converts cif idxs to the index it appears at in id_prop_augment
'''
idxs = []
for i in cif_idxs:
idxs.append(self.id_prop_augment[np.argwhere(self.id_prop_augment == \
str(int(i[0])))[0][0]])
return np.array(idxs)
def _get_split_idxs(self, target=None, transform=None, fold=None):
3
Source : supervised.py
with Apache License 2.0
from beringresearch
with Apache License 2.0
from beringresearch
def __init__(self, labels):
"""Constructs a LabeledNeighbourMap instance from a list of labels.
:param labels list: List of labels for each data-point. One label per data-point."""
self.class_indicies = {label: np.argwhere(labels == label).ravel()
for label in np.unique(labels)}
self.labels = labels
def __len__(self):
3
Source : test_neighbour_matrix.py
with Apache License 2.0
from beringresearch
with Apache License 2.0
from beringresearch
def test_custom_ndarray_neighbour_matrix():
iris = datasets.load_iris()
x = iris.data
y = iris.target
class_indicies = {label: np.argwhere(y == label).ravel() for label in np.unique(y)}
neighbour_matrix = np.array([class_indicies[label] for label in y])
ivis_iris = Ivis(epochs=5, neighbour_matrix=neighbour_matrix)
ivis_iris.k = 15
ivis_iris.batch_size = 16
y_pred_iris = ivis_iris.fit_transform(x)
3
Source : rect_histogram.py
with BSD 3-Clause "New" or "Revised" License
from BGT-M
with BSD 3-Clause "New" or "Revised" License
from BGT-M
def find_peak_rect(self, binx: tuple, biny: tuple):
'''
binx: the range of max bin along the x axis.
biny: the range of max bin along the y axis.
return coordinate pairs in the max bin
'''
xs = self.xs
ys = self.ys
(binxst, binxend) = binx
(binyst, binyend) = biny
xcoords = set(np.argwhere(xs >= binxst).T[0]) & set(np.argwhere(xs < = binxend).T[0])
ycoords = set(np.argwhere(ys >= binyst).T[0]) & set(np.argwhere(ys < = binyend).T[0])
pairids = list(xcoords & ycoords)
coordpairs = list(zip(xs[pairids], ys[pairids]))
return coordpairs
3
Source : patch_samplers.py
with MIT License
from biomedia-mira
with MIT License
from biomedia-mira
def sample_patch_center(self, target, mask):
sampling_mask = self.get_sampling_mask(target, mask)
points = np.argwhere(sampling_mask)
center = points[np.random.choice(len(points))]
return center
class RandomPatchSampler(StochasticPatchSampler):
3
Source : fvutils.py
with GNU General Public License v3.0
from BjornNyberg
with GNU General Public License v3.0
from BjornNyberg
def _exclude_matrix(self, ids):
"""
creates an exclusion matrix. This is a mapping from sub-faces to
all sub-faces except those given by ids.
Example:
ids = [0, 2]
self.num_subfno = 4
print(sef._exclude_matrix(ids))
[[0, 1, 0, 0],
[0, 0, 0, 1]]
"""
col = np.argwhere([not it for it in ids])
row = np.arange(col.size)
return sps.coo_matrix(
(np.ones(row.size, dtype=np.bool), (row, col.ravel("C"))),
shape=(row.size, self.num_subfno),
).tocsr()
def _exclude_matrix_xyz(self, ids):
3
Source : drapes.py
with MIT License
from braemt
with MIT License
from braemt
def _whole_pattern_position(self, character, error_name):
"""Find the absolute location of `character` in game world ASCII art."""
pos = list(np.argwhere(self._whole_pattern_art == ord(character)))
if not pos: raise RuntimeError(
'{} found no instances of {} in the pattern art used to build this '
'PatternInfo object.'.format(error_name, repr(character)))
if len(pos) > 1: raise RuntimeError(
'{} found multiple instances of {} in the pattern art used to build '
'this PatternInfo object.'.format(error_name, repr(character)))
return tuple(pos[0])
def __init__(self, curtain, character, board_shape,
3
Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from brainglobe
with BSD 3-Clause "New" or "Revised" License
from brainglobe
def create_KDTree_from_image(image, value=0):
"""
Create a KDTree of points equalling a given value
:param image: Image to be converted to points
:param value: Value of image to be used
:return: scipy.spatial.cKDTree object
"""
list_points = np.argwhere((image == value))
return cKDTree(list_points)
3
Source : utils.py
with MIT License
from BYU-PCCL
with MIT License
from BYU-PCCL
def naive_centroid_expansion(self, source_words, epsilon=0.25, distance_metric='cosine', k=None):
source_words = self.validate(source_words)
source_vectors = np.array([self.vectors[np.squeeze(np.argwhere(self.tokens == w))] for w in source_words])
centroid = np.atleast_2d(np.mean(source_vectors, axis=0))
distances = spatial.distance.cdist(self.vectors, centroid, distance_metric)[:, 0]
if k is not None:
# find the k nearest
inds = np.argsort( distances )
return np.array( self.tokens[ inds[0:k] ] )
else:
# find anything within radius epsilon (scaled by mean distance)
epsilon = epsilon * np.mean(distances)
return np.squeeze(self.tokens[np.argwhere(distances < = epsilon)])
def bounding_box(self, source_words):
3
Source : util.py
with MIT License
from byungsook
with MIT License
from byungsook
def draw_voxel(d):
vox = np.argwhere(d>0)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(vox)
c = d[d>0]
c = np.stack([c]*3, axis=-1)
pcd.colors = o3d.utility.Vector3dVector(c)
# vol = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, 1)
o3d.visualization.draw_geometries([pcd])
def npz2vdb(d, vdb_exe, d_path):
3
Source : LeniaF.py
with MIT License
from Chakazul
with MIT License
from Chakazul
def crop(self):
#vmin = np.amin(self.cells)
coords_list = [np.argwhere(self.cells[c] > ALIVE_THRESHOLD) for c in CHANNEL]
coords = np.concatenate(coords_list)
if coords.size == 0:
self.cells = [np.zeros([1]*DIM) for c in CHANNEL]
else:
min_point = coords.min(axis=0)
max_point = coords.max(axis=0) + 1
slices = [slice(x1, x2) for x1, x2 in zip(min_point, max_point)]
for c in CHANNEL:
self.cells[c] = self.cells[c][tuple(slices)]
return self
def restore_to(self, dest):
3
Source : LeniaND.py
with MIT License
from Chakazul
with MIT License
from Chakazul
def crop(self):
#vmin = np.amin(self.cells)
coords = np.argwhere(self.cells > EPSILON)
if coords.size == 0:
self.cells = np.zeros([1]*DIM)
else:
min_point = coords.min(axis=0)
max_point = coords.max(axis=0) + 1
slices = [slice(x1, x2) for x1, x2 in zip(min_point, max_point)]
self.cells = self.cells[tuple(slices)]
return self
def restore_to(self, dest):
3
Source : LeniaNDKC.py
with MIT License
from Chakazul
with MIT License
from Chakazul
def crop(self):
#vmin = np.amin(self.cells)
coords_list = [np.argwhere(self.cells[c] > EPSILON) for c in CHANNEL]
coords = np.concatenate(coords_list)
if coords.size == 0:
self.cells = [np.zeros([1]*DIM) for c in CHANNEL]
else:
min_point = coords.min(axis=0)
max_point = coords.max(axis=0) + 1
slices = [slice(x1, x2) for x1, x2 in zip(min_point, max_point)]
for c in CHANNEL:
self.cells[c] = self.cells[c][tuple(slices)]
return self
def restore_to(self, dest):
3
Source : evaluation.py
with MIT License
from chao1224
with MIT License
from chao1224
def roc_auc_single(actual, predicted, sample_weight=None):
actual = reshape_data_into_2_dim(actual)
predicted = reshape_data_into_2_dim(predicted)
if sample_weight is not None:
non_missing_indices = np.argwhere(sample_weight == 1)[:, 0]
actual = actual[non_missing_indices]
predicted = predicted[non_missing_indices]
return roc_auc_score(actual, predicted)
def precision_auc_multi(y_true, y_pred, sample_weight, eval_indices, eval_mean_or_median):
3
Source : evaluation.py
with MIT License
from chao1224
with MIT License
from chao1224
def precision_auc_single(actual, predicted, sample_weight=None):
actual = reshape_data_into_2_dim(actual)
predicted = reshape_data_into_2_dim(predicted)
if sample_weight is not None:
non_missing_indices = np.argwhere(sample_weight == 1)[:, 0]
actual = actual[non_missing_indices]
predicted = predicted[non_missing_indices]
prec_auc = average_precision_score(actual, predicted)
return prec_auc
def enrichment_factor_single(labels_arr, scores_arr, percentile, sample_weight):
3
Source : face_swap.py
with Apache License 2.0
from chenqianhe
with Apache License 2.0
from chenqianhe
def get_mask_center_point(image_mask):
"""
获取掩模的中心点坐标
:param image_mask: 掩模图片
:return: 掩模中心
"""
image_mask_index = np.argwhere(image_mask > 0)
miny, minx = np.min(image_mask_index, axis=0)
maxy, maxx = np.max(image_mask_index, axis=0)
center_point = ((maxx + minx) // 2, (maxy + miny) // 2)
return center_point
def get_mask_union(mask1, mask2):
3
Source : check_multi_comp.py
with MIT License
from CHPGenetics
with MIT License
from CHPGenetics
def get_HTO_cell_idx(high_array, threshold):
high_idx = np.argwhere(high_array > threshold)
return high_idx
def compute_confidence(high_array, low_array, high_ary_idx, all_ary_idx):
3
Source : check_multi_comp.py
with MIT License
from CHPGenetics
with MIT License
from CHPGenetics
def get_shared_cell_idx(high_array, low_array, high_ary_idx, all_ary_idx, threshold):
product = compute_confidence(high_array, low_array, high_ary_idx, all_ary_idx)
residual_idx = np.argwhere(product > threshold)
return residual_idx
def get_HTO_cell_num(high_array, threshold):
3
Source : program_env.py
with MIT License
from clvrai
with MIT License
from clvrai
def _modify(self, action):
# Ignore everything after end-of-program token
null_token_idx = np.argwhere(action == (self.num_program_tokens-1))
if null_token_idx.shape[0] > 0:
action = action[:null_token_idx[0].squeeze()]
# remap prl tokens to dsl tokens if we are using simplified DSL
action = self._prl_to_dsl(action) if self.config.use_simplified_dsl else action
return action
def step(self, action):
3
Source : channel_selection.py
with Apache License 2.0
from Culturenotes
with Apache License 2.0
from Culturenotes
def forward(self, input_tensor):
"""
Parameter
---------
input_tensor: (N,C,H,W). It should be the output of BatchNorm2d layer.
"""
selected_index = np.squeeze(np.argwhere(self.indexes.data.cpu().numpy()))
if selected_index.size == 1:
selected_index = np.resize(selected_index, (1,))
output = input_tensor[:, selected_index, :, :]
return output
3
Source : metric.py
with GNU General Public License v3.0
from dair-iitd
with GNU General Public License v3.0
from dair-iitd
def post_process(coords, is_quote):
new_coords = {}
offsets = np.delete(is_quote.cumsum(), np.argwhere(is_quote))
for cc, coord in coords.items():
cc = cc + offsets[cc]
if coord is not None:
conjuncts = [(b + offsets[b], e + offsets[e])
for (b, e) in coord.conjuncts]
seps = [s + offsets[s] for s in coord.seps]
coord = Coordination(cc, conjuncts, seps, coord.label)
new_coords[cc] = coord
return new_coords
class Counter(object):
3
Source : customer.py
with Apache License 2.0
from deepair-io
with Apache License 2.0
from deepair-io
def _dist_from_edge(self, img):
"""Calculate the distance to nearest occupied seat."""
interior = binary_erosion(img, border_value=1) # Interior mask
C = img - interior # Contour mask
# Setup o/p and assign cityblock distances
out = C.astype(int)
try:
out[interior] = cdist(np.argwhere(C), np.argwhere(
interior), 'cityblock').min(0) + 1
return out / np.max(out)
except:
return out
def _pick_preferred_seat(self, avail, preference, no_buy):
3
Source : stochastic_gradient_estimators_test.py
with Apache License 2.0
from deepmind
with Apache License 2.0
from deepmind
def _assert_equal(actual, expected, rtol=1e-2, atol=1e-2):
"""Asserts that arrays are equal."""
# Note: assert_allclose does not check shapes
chex.assert_equal_shape((actual, expected))
# We get around the bug https://github.com/numpy/numpy/issues/13801
zero_indices = np.argwhere(expected == 0)
if not np.all(np.abs(actual[zero_indices]) < = atol):
raise AssertionError(f'Larger than {atol} diff in {actual[zero_indices]}')
non_zero_indices = np.argwhere(expected != 0)
np.testing.assert_allclose(
np.asarray(actual)[non_zero_indices],
expected[non_zero_indices], rtol, atol)
def _estimator_variant(variant, estimator):
3
Source : autoregressive.py
with MIT License
from deeprob-org
with MIT License
from deeprob-org
def apply_forward(self, u: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# Initialize arbitrarily
x = torch.zeros_like(u)
log_det_jacobian = torch.zeros_like(u)
# This requires D iterations where D is the number of features
# Get the parameters and apply the affine transformation (forward mode)
for i in range(self.in_features):
z = self.network(x)
t, s = torch.chunk(z, chunks=2, dim=1)
s = self.scale_act(s)
idx = np.argwhere(self.ordering == i).item()
x[:, idx] = u[:, idx] * torch.exp(s[:, idx]) + t[:, idx]
log_det_jacobian[:, idx] = s[:, idx]
log_det_jacobian = torch.sum(log_det_jacobian, dim=1)
return x, log_det_jacobian
def build_degrees_sequential(self, depth: int, units: int, reverse: bool) -> List[np.ndarray]:
3
Source : transformer.py
with GNU General Public License v3.0
from dessertlab
with GNU General Public License v3.0
from dessertlab
def output_and_loss(self, h_block, concat_t_block):
concat_logit_block = self.output_affine(h_block, reconstruct_shape=False)
bool_array = concat_t_block != 0
indexes = np.argwhere(bool_array).ravel()
concat_logit_block = dy.pick_batch_elems(concat_logit_block, indexes)
concat_t_block = concat_t_block[bool_array]
loss = dy.pickneglogsoftmax_batch(concat_logit_block, concat_t_block)
return loss
def output(self, h_block):
3
Source : eval_validity_utils.py
with GNU General Public License v3.0
from divelab
with GNU General Public License v3.0
from divelab
def check_connected(AC):
seen, queue = {0}, collections.deque([0])
while queue:
vertex = queue.popleft()
for node in np.argwhere(AC[vertex] > 0).flatten():
if node not in seen:
seen.add(node)
queue.append(node)
# if the seen nodes do not include all nodes, there are disconnected
# parts and the molecule is invalid
if seen != {*range(len(AC))}:
return False
return True
def AC2BO(AC, atoms, use_graph=True):
3
Source : plots.py
with GNU General Public License v3.0
from donatolab
with GNU General Public License v3.0
from donatolab
def add_events(self, events, f_trace):
x = np.argwhere(events)
y = f_trace[x]
pos = np.hstack((x, y))
if len(pos) > 0:
self._events_plot = pg.ScatterPlotItem(pos=pos)
else:
self._events_plot = pg.ScatterPlotItem()
self._plot.addItem(self._events_plot)
def update_vline(self, new_pos):
3
Source : lidar_dataset.py
with Apache License 2.0
from dotchen
with Apache License 2.0
from dotchen
def preprocess(self, lidar_xyzr, lidar_painted=None):
idx = (lidar_xyzr[:,0] > -2.4)&(lidar_xyzr[:,0] < 0)&(lidar_xyzr[:,1]>-0.8)&(lidar_xyzr[:,1] < 0.8)&(lidar_xyzr[:,2]>-1.5)&(lidar_xyzr[:,2] < -1)
idx = np.argwhere(idx)
if lidar_painted is None:
return np.delete(lidar_xyzr, idx, axis=0)
else:
return np.delete(lidar_xyzr, idx, axis=0), np.delete(lidar_painted, idx, axis=0)
def __getitem__(self, idx):
3
Source : lav_agent.py
with Apache License 2.0
from dotchen
with Apache License 2.0
from dotchen
def preprocess(self, lidar_xyzr, lidar_painted=None):
idx = (lidar_xyzr[:,0] > -2.4)&(lidar_xyzr[:,0] < 0)&(lidar_xyzr[:,1]>-0.8)&(lidar_xyzr[:,1] < 0.8)&(lidar_xyzr[:,2]>-1.5)&(lidar_xyzr[:,2] < -1)
idx = np.argwhere(idx)
if lidar_painted is None:
return np.delete(lidar_xyzr, idx, axis=0)
else:
return np.delete(lidar_xyzr, idx, axis=0), np.delete(lidar_painted, idx, axis=0)
def _rotate(x, y, theta):
3
Source : rule_based_channel_reweight.py
with MIT License
from Dsqvival
with MIT License
from Dsqvival
def get_channel_bass_property(piano_roll):
result=np.argwhere(piano_roll>0)[:,1]
if(len(result)==0):
return 0.0,1.0
return result.mean(),min(1.,len(result)/len(piano_roll))
def midi_to_thickness_weights(midi):
3
Source : utils.py
with MIT License
from EagleW
with MIT License
from EagleW
def mean_rank(triples, sorted_idx, correct, loc):
reordered_triples = triples[sorted_idx]
rank = np.argwhere(reordered_triples[:, loc] == correct[loc])[0][0]
# print("rank is",rank)
return rank
def convert_idx2name(triples, id2ent, ent2name, id2rel):
3
Source : npe_generate_taxa_tree.py
with Apache License 2.0
from ehsanasgari
with Apache License 2.0
from ehsanasgari
def redundant_columns_indentification(self):
#self.list_of_pairs=np.argwhere(distances < np.percentile(flatten_distances, 5, axis=0)).tolist()
if self.remove_redundants:
distances=get_sym_kl_rows(self.update_matrix)
flatten_distances=distances.flatten()
self.list_of_pairs=np.argwhere(distances==0).tolist()
self.equiv_classes=NPEMarkerAnlaysis.find_equiv_classes(self.list_of_pairs)
else:
self.list_of_pairs=[(i,i) for i in range(self.update_matrix.shape[0])]
self.equiv_classes=NPEMarkerAnlaysis.find_equiv_classes(self.list_of_pairs)
def align_markers(self,p_value_threshold):
3
Source : distributions.py
with MIT License
from eifuentes
with MIT License
from eifuentes
def rand_ring2d(batch_size):
""" This function generates 2D samples from a hollowed-cirlce distribution in a 2-dimensional space.
Args:
batch_size (int): number of batch samples
Return:
torch.Tensor: tensor of size (batch_size, 2)
"""
circles = make_circles(2 * batch_size, noise=.01)
z = np.squeeze(circles[0][np.argwhere(circles[1] == 0), :])
return torch.from_numpy(z).type(torch.FloatTensor)
def rand_uniform2d(batch_size):
3
Source : channel_selection.py
with MIT License
from Eric-mingjie
with MIT License
from Eric-mingjie
def forward(self, input_tensor):
"""
Parameter
---------
input_tensor: (N,C,H,W). It should be the output of BatchNorm2d layer.
"""
selected_index = np.squeeze(np.argwhere(self.indexes.data.cpu().numpy()))
if selected_index.size == 1:
selected_index = np.resize(selected_index, (1,))
output = input_tensor[:, selected_index, :, :]
return output
3
Source : vis.py
with BSD 3-Clause "New" or "Revised" License
from ethz-asl
with BSD 3-Clause "New" or "Revised" License
from ethz-asl
def _create_vol_msg(vol, voxel_size, threshold):
vol = vol.squeeze()
points = np.argwhere(vol > threshold) * voxel_size
values = np.expand_dims(vol[vol > threshold], 1)
return ros_utils.to_cloud_msg(points, values, frame="task")
def _create_grasp_marker_msg(grasp, score, finger_depth):
3
Source : residue.py
with MIT License
from ExcitedStates
with MIT License
from ExcitedStates
def reorder(self):
for idx,atom2 in enumerate(self._rotamers['atoms']+self._rotamers['hydrogens']):
if self.name[idx] != atom2:
idx2 = np.argwhere(self.name == atom2)[0]
index = np.ndarray((1,),dtype='int')
index[0,]=np.array(self.__dict__['_selection'][0],dtype='int')
for attr in ["record", "name", "b", "q", "coor", "resn", "resi","icode", "e", "charge", "chain", "altloc"]:
self.__dict__['_'+attr][index+idx],self.__dict__['_'+attr][index+idx2]=self.__dict__['_'+attr][index+idx2],self.__dict__['_'+attr][index+idx]
3
Source : game.py
with MIT License
from faameunier
with MIT License
from faameunier
def set_state(self, state):
self.board = state[0]
self.position = state[1]
self.t = 0
self.score = 0
coords = np.argwhere(self.position == 1)[0]
self.x = coords[0]
self.y = coords[1]
def get_state(self, state):
3
Source : reinforcement_learning_partitioner.py
with MIT License
from Francesco-Sovrano
with MIT License
from Francesco-Sovrano
def get_state_partition(self, state, concat=None, internal_state=None):
action_batch, value_batch, policy_batch, new_internal_state = self.get_model(0).predict_action(states=[state], concats=[concat], internal_state=internal_state)
id = np.argwhere(action_batch[0]==1)[0][0]+1
self.add_to_statistics(id)
return id, action_batch[0], value_batch[0], policy_batch[0], new_internal_state
def query_partitioner(self, step):
3
Source : dihedrals.py
with GNU Lesser General Public License v3.0
from gph82
with GNU Lesser General Public License v3.0
from gph82
def _dih_idxs_for_residue(res_idxs, geom):
quads = _get_dih_idxs(geom)
quad_idxs_2_res_idxs = {key:_angle_quadruplet2residx(val, geom.top, max_residues_per_quad=2) for key, val in quads.items()}
dict_out = {}
for ii in res_idxs:
quad_idx = {key:_np.argwhere(val==ii).squeeze() for key, val in quad_idxs_2_res_idxs.items()}
dict_out[ii] = {key:quads[key][val] for key, val in quad_idx.items() if _np.size(val)>0}
return dict_out
See More Examples