Python numpy.all() Examples
The following are 30
code examples of numpy.all().
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: test_region.py From aospy with Apache License 2.0 | 6 votes |
def test_region_init(): region = Region( name='test', description='region description', west_bound=0., east_bound=5, south_bound=0, north_bound=90., do_land_mask=True ) assert region.name == 'test' assert region.description == 'region description' assert isinstance(region.mask_bounds, tuple) assert len(region.mask_bounds) == 1 assert isinstance(region.mask_bounds[0], BoundsRect) assert np.all(region.mask_bounds[0] == (Longitude(0.), Longitude(5), 0, 90.)) assert region.do_land_mask is True
Example #2
Source File: test_bayestar.py From dustmaps with GNU General Public License v2.0 | 6 votes |
def test_bounds(self): """ Test that out-of-bounds coordinates return NaN reddening, and that in-bounds coordinates do not return NaN reddening. """ for mode in (['random_sample', 'random_sample_per_pix', 'median', 'samples', 'mean']): # Draw random coordinates, both above and below dec = -30 degree line n_pix = 1000 ra = -180. + 360.*np.random.random(n_pix) dec = -75. + 90.*np.random.random(n_pix) # 45 degrees above/below c = coords.SkyCoord(ra, dec, frame='icrs', unit='deg') ebv_calc = self._bayestar(c, mode=mode) nan_below = np.isnan(ebv_calc[dec < -35.]) nan_above = np.isnan(ebv_calc[dec > -25.]) pct_nan_above = np.sum(nan_above) / float(nan_above.size) # print r'{:s}: {:.5f}% nan above dec=-25 deg.'.format(mode, 100.*pct_nan_above) self.assertTrue(np.all(nan_below)) self.assertTrue(pct_nan_above < 0.05)
Example #3
Source File: test_module.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def test_module_input_grads(): a = mx.sym.Variable('a', __layout__='NC') b = mx.sym.Variable('b', __layout__='NC') c = mx.sym.Variable('c', __layout__='NC') c = a + 2 * b + 3 * c net = mx.mod.Module(c, data_names=['b', 'c', 'a'], label_names=None, context=[mx.cpu(0), mx.cpu(1)]) net.bind(data_shapes=[['b', (5, 5)], ['c', (5, 5)], ['a', (5, 5)]], label_shapes=None, inputs_need_grad=True) net.init_params() net.forward(data_batch=mx.io.DataBatch(data=[nd.ones((5, 5)), nd.ones((5, 5)), nd.ones((5, 5))])) net.backward(out_grads=[nd.ones((5, 5))]) input_grads = net.get_input_grads() b_grad = input_grads[0].asnumpy() c_grad = input_grads[1].asnumpy() a_grad = input_grads[2].asnumpy() assert np.all(a_grad == 1), a_grad assert np.all(b_grad == 2), b_grad assert np.all(c_grad == 3), c_grad
Example #4
Source File: coco.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id']] h, w = t['height'], t['width'] segm = ann['segmentation'] if type(segm) == list: # polygon -- a single object might consist of multiple parts # we merge all parts into one mask rle code # rles = maskUtils.frPyObjects(segm, h, w) # rle = maskUtils.merge(rles) raise NotImplementedError("maskUtils disabled!") elif type(segm['counts']) == list: # uncompressed RLE # rle = maskUtils.frPyObjects(segm, h, w) raise NotImplementedError("maskUtils disabled!") else: # rle rle = ann['segmentation'] return rle
Example #5
Source File: metrics.py From DDPAE-video-prediction with MIT License | 6 votes |
def find_match(self, pred, gt): ''' Match component to balls. ''' batch_size, n_frames_input, n_components, _ = pred.shape diff = pred.reshape(batch_size, n_frames_input, n_components, 1, 2) - \ gt.reshape(batch_size, n_frames_input, 1, n_components, 2) diff = np.sum(np.sum(diff ** 2, axis=-1), axis=1) # Direct indices indices = np.argmin(diff, axis=2) ambiguous = np.zeros(batch_size, dtype=np.int8) for i in range(batch_size): _, counts = np.unique(indices[i], return_counts=True) if not np.all(counts == 1): ambiguous[i] = 1 return indices, ambiguous
Example #6
Source File: coco.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' imgIds = imgIds if type(imgIds) == list else [imgIds] catIds = catIds if type(catIds) == list else [catIds] if len(imgIds) == len(catIds) == 0: ids = self.imgs.keys() else: ids = set(imgIds) for i, catId in enumerate(catIds): if i == 0 and len(ids) == 0: ids = set(self.catToImgs[catId]) else: ids &= set(self.catToImgs[catId]) return list(ids)
Example #7
Source File: test_sparse_ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def test_sparse_nd_setitem(): def check_sparse_nd_setitem(stype, shape, dst): x = mx.nd.zeros(shape=shape, stype=stype) x[:] = dst dst_nd = mx.nd.array(dst) if isinstance(dst, (np.ndarray, np.generic)) else dst assert np.all(x.asnumpy() == dst_nd.asnumpy() if isinstance(dst_nd, NDArray) else dst) shape = rand_shape_2d() for stype in ['row_sparse', 'csr']: # ndarray assignment check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, 'default')) check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, stype)) # numpy assignment check_sparse_nd_setitem(stype, shape, np.ones(shape)) # scalar assigned to row_sparse NDArray check_sparse_nd_setitem('row_sparse', shape, 2)
Example #8
Source File: test_module.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def test_module_reshape(): data = mx.sym.Variable('data') sym = mx.sym.FullyConnected(data, num_hidden=20, name='fc') dshape = (7, 20) mod = mx.mod.Module(sym, ('data',), None, context=[mx.cpu(0), mx.cpu(1)]) mod.bind(data_shapes=[('data', dshape)]) mod.init_params() mod.init_optimizer(optimizer_params={'learning_rate': 1}) mod.forward(mx.io.DataBatch(data=[mx.nd.ones(dshape)], label=None)) mod.backward([mx.nd.ones(dshape)]) mod.update() assert mod.get_outputs()[0].shape == dshape assert (mod.get_params()[0]['fc_bias'].asnumpy() == -1).all() dshape = (14, 20) mod.reshape(data_shapes=[('data', dshape)]) mod.forward(mx.io.DataBatch(data=[mx.nd.ones(dshape)], label=None)) mod.backward([mx.nd.ones(dshape)]) mod.update() assert mod.get_outputs()[0].shape == dshape assert (mod.get_params()[0]['fc_bias'].asnumpy() == -3).all()
Example #9
Source File: dataloader_m.py From models with MIT License | 6 votes |
def map_values(values, pos, target_pos, dtype=None, nan=dat.CPG_NAN): """Maps `values` array at positions `pos` to `target_pos`. Inserts `nan` for uncovered positions. """ assert len(values) == len(pos) assert np.all(pos == np.sort(pos)) assert np.all(target_pos == np.sort(target_pos)) values = values.ravel() pos = pos.ravel() target_pos = target_pos.ravel() idx = np.in1d(pos, target_pos) pos = pos[idx] values = values[idx] if not dtype: dtype = values.dtype target_values = np.empty(len(target_pos), dtype=dtype) target_values.fill(nan) idx = np.in1d(target_pos, pos).nonzero()[0] assert len(idx) == len(values) assert np.all(target_pos[idx] == pos) target_values[idx] = values return target_values
Example #10
Source File: StructureFactorConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 6 votes |
def get_constraint_value(self, applyMultiframePrior=True): """ Compute all partial Structure Factor (SQs). :Parameters: #. applyMultiframePrior (boolean): Whether to apply subframe weight and prior to the total. This will only have an effect when used frame is a subframe and in case subframe weight and prior is defined. :Returns: #. SQs (dictionary): The SQs dictionnary, where keys are the element wise intra and inter molecular SQs and values are the computed SQs. """ if self.data is None: LOGGER.warn("data must be computed first using 'compute_data' method.") return {} return self._get_constraint_value(self.data, applyMultiframePrior=applyMultiframePrior)
Example #11
Source File: map_utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def _project_to_map(map, vertex, wt=None, ignore_points_outside_map=False): """Projects points to map, returns how many points are present at each location.""" num_points = np.zeros((map.size[1], map.size[0])) vertex_ = vertex[:, :2] - map.origin vertex_ = np.round(vertex_ / map.resolution).astype(np.int) if ignore_points_outside_map: good_ind = np.all(np.array([vertex_[:,1] >= 0, vertex_[:,1] < map.size[1], vertex_[:,0] >= 0, vertex_[:,0] < map.size[0]]), axis=0) vertex_ = vertex_[good_ind, :] if wt is not None: wt = wt[good_ind, :] if wt is None: np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), 1) else: assert(wt.shape[0] == vertex.shape[0]), \ 'number of weights should be same as vertices.' np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), wt) return num_points
Example #12
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 6 votes |
def raw_valid_fn_vec(self, xyt): """Returns if the given set of nodes is valid or not.""" height = self.traversible.shape[0] width = self.traversible.shape[1] x = np.round(xyt[:,[0]]).astype(np.int32) y = np.round(xyt[:,[1]]).astype(np.int32) is_inside = np.all(np.concatenate((x >= 0, y >= 0, x < width, y < height), axis=1), axis=1) x = np.minimum(np.maximum(x, 0), width-1) y = np.minimum(np.maximum(y, 0), height-1) ind = np.ravel_multi_index((y,x), self.traversible.shape) is_traversible = self.traversible.ravel()[ind] is_valid = np.all(np.concatenate((is_inside[:,np.newaxis], is_traversible), axis=1), axis=1) return is_valid
Example #13
Source File: test_util.py From libTLDA with MIT License | 6 votes |
def test_one_hot(): """Check if one_hot returns correct label matrices.""" # Generate label vector y = np.hstack((np.ones((10,))*0, np.ones((10,))*1, np.ones((10,))*2)) # Map to matrix Y, labels = one_hot(y) # Check for only 0's and 1's assert len(np.setdiff1d(np.unique(Y), [0, 1])) == 0 # Check for correct labels assert np.all(labels == np.unique(y)) # Check correct shape of matrix assert Y.shape[0] == y.shape[0] assert Y.shape[1] == len(labels)
Example #14
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 6 votes |
def valid_fn_vec(self, pqr): """Returns if the given set of nodes is valid or not.""" xyt = self.to_actual_xyt_vec(np.array(pqr)) height = self.traversible.shape[0] width = self.traversible.shape[1] x = np.round(xyt[:,[0]]).astype(np.int32) y = np.round(xyt[:,[1]]).astype(np.int32) is_inside = np.all(np.concatenate((x >= 0, y >= 0, x < width, y < height), axis=1), axis=1) x = np.minimum(np.maximum(x, 0), width-1) y = np.minimum(np.maximum(y, 0), height-1) ind = np.ravel_multi_index((y,x), self.traversible.shape) is_traversible = self.traversible.ravel()[ind] is_valid = np.all(np.concatenate((is_inside[:,np.newaxis], is_traversible), axis=1), axis=1) return is_valid
Example #15
Source File: suba.py From libTLDA with MIT License | 6 votes |
def is_pos_def(self, A): """ Check for positive definiteness. Parameters --------- A : array square symmetric matrix. Returns ------- bool whether matrix is positive-definite. Warning! Returns false for arrays containing inf or NaN. """ # Check for valid numbers if np.any(np.isnan(A)) or np.any(np.isinf(A)): return False else: return np.all(np.real(np.linalg.eigvals(A)) > 0)
Example #16
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 6 votes |
def image_to_cortex(self, image, surface='midgray', hemi=None, affine=Ellipsis, method=None, fill=0, dtype=None, weights=None): ''' sub.image_to_cortex(image) is equivalent to the tuple (sub.lh.from_image(image), sub.rh.from_image(image)). sub.image_to_cortex(image, surface) uses the given surface (see also cortex.surface). ''' if hemi is None: hemi = 'both' hemi = hemi.lower() if hemi in ['both', 'lr', 'all', 'auto']: return tuple( [self.image_to_cortex(image, surface=surface, hemi=h, affine=affine, method=method, fill=fill, dtype=dtype, weights=weights) for h in ['lh', 'rh']]) else: hemi = getattr(self, hemi) return hemi.from_image(image, surface=surface, affine=affine, method=method, fill=fill, dtype=dtype, weights=weights)
Example #17
Source File: graph_utils.py From DOTA_models with Apache License 2.0 | 5 votes |
def add_diagonal_edges(g, nodes, sz_x, sz_y, edge_len): offset = [sz_x+1, sz_x-1] for o in offset: s = np.arange(nodes.shape[0]-o-1) t = s + o ind = np.all(np.abs(nodes[s,:] - nodes[t,:]) == np.array([[1,1]]), axis=1) s = s[ind][:,np.newaxis] t = t[ind][:,np.newaxis] st = np.concatenate((s,t), axis=1) for i in range(st.shape[0]): e = g.add_edge(st[i,0], st[i,1], add_missing=False) g.ep['wts'][e] = edge_len
Example #18
Source File: model_test.py From DOTA_models with Apache License 2.0 | 5 votes |
def test_predicted_scores_are_within_range(self): ocr_model = self.create_model() _, _, scores = ocr_model.char_predictions(self.fake_logits) with self.test_session() as sess: scores_np = sess.run(scores) values_in_range = (scores_np >= 0.0) & (scores_np <= 1.0) self.assertTrue( np.all(values_in_range), msg=('Scores contains out of the range values %s' % scores_np[np.logical_not(values_in_range)]))
Example #19
Source File: tf_utils.py From DOTA_models with Apache License 2.0 | 5 votes |
def simple_summaries(summarize_ops, summarize_names, mode, to_aggregate=False, scope_name='summary'): if type(to_aggregate) != list: to_aggregate = [to_aggregate for _ in summarize_ops] summary_key = '{:s}_summaries'.format(mode) print_summary_key = '{:s}_print_summaries'.format(mode) prefix=' [{:s}]: '.format(mode) # Default ops for things that dont need to be aggregated. if not np.all(to_aggregate): for op, name, to_agg in zip(summarize_ops, summarize_names, to_aggregate): if not to_agg: add_scalar_summary_op(op, name, summary_key, print_summary_key, prefix) summary_ops = tf.summary.merge_all(summary_key) print_summary_ops = tf.summary.merge_all(print_summary_key) else: summary_ops = tf.no_op() print_summary_ops = tf.no_op() # Default ops for things that dont need to be aggregated. if np.any(to_aggregate): additional_return_ops = [[summarize_ops[i] for i, x in enumerate(to_aggregate )if x]] arop_summary_iters = [-1] s_names = ['{:s}/{:s}'.format(scope_name, summarize_names[i]) for i, x in enumerate(to_aggregate) if x] fn = lambda outputs, global_step, output_dir, metric_summary, N: \ accum_val_ops(outputs, s_names, global_step, output_dir, metric_summary, N) arop_eval_fns = [fn] else: additional_return_ops = [] arop_summary_iters = [] arop_eval_fns = [] return summary_ops, print_summary_ops, additional_return_ops, \ arop_summary_iters, arop_eval_fns
Example #20
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 5 votes |
def _label_nodes_with_room_id(xyt, room_dims): # Label the room with the ID into things. node_room_id = -1*np.ones((xyt.shape[0], 1)) dims = room_dims['dims'] for x, name in enumerate(room_dims['names']): all_ = np.concatenate((xyt[:,[0]] >= dims[x,0], xyt[:,[0]] <= dims[x,3], xyt[:,[1]] >= dims[x,1], xyt[:,[1]] <= dims[x,4]), axis=1) node_room_id[np.all(all_, axis=1), 0] = x return node_room_id
Example #21
Source File: graph_utils.py From DOTA_models with Apache License 2.0 | 5 votes |
def rng_target_dist_field(batch_size, gtG, rng, max_dist, max_dist_to_compute, nodes=None, compute_path=False): # Sample a single node, compute distance to all nodes less than max_dist, # sample nodes which are a particular distance away. dists = []; pred_maps = []; paths = []; start_node_ids = [] end_node_ids = rng.choice(gtG.num_vertices(), size=(batch_size,), replace=False).tolist() for i in range(batch_size): dist, pred_map = gt.topology.shortest_distance( gt.GraphView(gtG, reversed=True), source=gtG.vertex(end_node_ids[i]), target=None, max_dist=max_dist_to_compute, pred_map=True) dist = np.array(dist.get_array()) pred_map = np.array(pred_map.get_array()) dists.append(dist) pred_maps.append(pred_map) # Randomly sample nodes which are withing max_dist near_ids = np.where(dist <= max_dist)[0] start_node_id = rng.choice(near_ids, size=(1,), replace=False)[0] start_node_ids.append(start_node_id) path = None if compute_path: path = get_path_ids(start_node_ids[i], end_node_ids[i], pred_map) paths.append(path) return start_node_ids, end_node_ids, dists, pred_maps, paths
Example #22
Source File: test_sparse_ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def test_sparse_nd_greater_equal(): for stype in ['row_sparse', 'csr']: shape = rand_shape_2d() x = mx.nd.zeros(shape=shape, stype=stype) y = sparse_nd_ones(shape, stype) z = x >= y assert (z.asnumpy() == np.zeros(shape)).all() z = y >= 0 assert (z.asnumpy() == np.ones(shape)).all() z = 0 >= y assert (z.asnumpy() == np.zeros(shape)).all() z = y >= 1 assert (z.asnumpy() == np.ones(shape)).all()
Example #23
Source File: test_module.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def test_save_load(): def dict_equ(a, b): assert set(a) == set(b) for k in a: assert (a[k].asnumpy() == b[k].asnumpy()).all() sym = mx.sym.Variable('data') sym = mx.sym.FullyConnected(sym, num_hidden=100) # single device mod = mx.mod.Module(sym, ('data',)) mod.bind(data_shapes=[('data', (10, 10))]) mod.init_params() mod.init_optimizer(optimizer_params={'learning_rate':0.1, 'momentum':0.9}) mod.update() mod.save_checkpoint('test', 0, save_optimizer_states=True) mod2 = mx.mod.Module.load('test', 0, load_optimizer_states=True, data_names=('data',)) mod2.bind(data_shapes=[('data', (10, 10))]) mod2.init_optimizer(optimizer_params={'learning_rate':0.1, 'momentum':0.9}) assert mod._symbol.tojson() == mod2._symbol.tojson() dict_equ(mod.get_params()[0], mod2.get_params()[0]) dict_equ(mod._updater.states, mod2._updater.states) # multi device mod = mx.mod.Module(sym, ('data',), context=[mx.cpu(0), mx.cpu(1)]) mod.bind(data_shapes=[('data', (10, 10))]) mod.init_params() mod.init_optimizer(optimizer_params={'learning_rate':0.1, 'momentum':0.9}) mod.update() mod.save_checkpoint('test', 0, save_optimizer_states=True) mod2 = mx.mod.Module.load('test', 0, load_optimizer_states=True, data_names=('data',)) mod2.bind(data_shapes=[('data', (10, 10))]) mod2.init_optimizer(optimizer_params={'learning_rate':0.1, 'momentum':0.9}) assert mod._symbol.tojson() == mod2._symbol.tojson() dict_equ(mod.get_params()[0], mod2.get_params()[0]) dict_equ(mod._kvstore._updater.states, mod2._updater.states)
Example #24
Source File: PairDistributionConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def get_constraint_original_value(self): """ Compute all partial Pair Distribution Functions (PDFs). :Returns: #. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs. """ if self.originalData is None: LOGGER.warn("originalData must be computed first using 'compute_data' method.") return {} return self._get_constraint_value(self.originalData)
Example #25
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 #26
Source File: PairDistributionConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def set_window_function(self, windowFunction, frame=None): """ Set convolution window function. :Parameters: #. windowFunction (None, numpy.ndarray): The window function to convolute with the computed pair distribution function of the system prior to comparing it with the experimental data. In general, the experimental pair distribution function G(r) shows artificial wrinkles, among others the main reason is because G(r) is computed by applying a sine Fourier transform to the experimental structure factor S(q). Therefore window function is used to best imitate the numerical artefacts in the experimental data. #. frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, all other multiframe subframes will be targeted. """ if windowFunction is not None: assert isinstance(windowFunction, np.ndarray), LOGGER.error("windowFunction must be a numpy.ndarray") assert windowFunction.dtype.type is FLOAT_TYPE, LOGGER.error("windowFunction type must be %s"%FLOAT_TYPE) assert len(windowFunction.shape) == 1, LOGGER.error("windowFunction must be of dimension 1") assert len(windowFunction) <= self.experimentalData.shape[0], LOGGER.error("windowFunction length must be smaller than experimental data") # normalize window function windowFunction /= np.sum(windowFunction) # check window size # set windowFunction self.__windowFunction = windowFunction # dump to repository usedIncluded, frame, allFrames = get_caller_frames(engine=self.engine, frame=frame, subframeToAll=True, caller="%s.%s"%(self.__class__.__name__,inspect.stack()[0][3]) ) if usedIncluded: self.__windowFunction = windowFunction for frm in allFrames: self._dump_to_repository({'_PairDistributionConstraint__windowFunction': self.__windowFunction}, frame=frm)
Example #27
Source File: StructureFactorConstraints.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def get_constraint_original_value(self): """ Compute all partial Pair Distribution Functions (PDFs). :Returns: #. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs. """ if self.originalData is None: LOGGER.warn("originalData must be computed first using 'compute_data' method.") return {} return self._get_constraint_value(self.originalData)
Example #28
Source File: StructureFactorConstraints.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): The 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" # data format is correct return True, ""
Example #29
Source File: images.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def image_clear(img, fill=0): ''' image_clear(img) yields a duplicate of the given image img but with all voxel values set to 0. image_clear(img, fill) sets all voxels to the given fill value. ''' img = image_copy(img) img.dataobj[...] = fill return img
Example #30
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def unaddress(self, data, surface=0.5): ''' cortex.unaddress(address) yields the (3 x n) coordinate matrix of the given addresses (or, if address is singular, the 3D vector) in the given cortex. If the address is a 2D instead of a 3D address, then the mid-gray position is returned by default. The following options may be given: * surface (default: 0.5) specifies the surface to use for 2D addresses; this should be either 'white', 'pial', 'midgray', or a real number in the range [0,1] where 0 is the white surface and 1 is the pial surface. ''' (faces, coords) = address_data(data, 3, surface=surface) (bc, ds) = (coords[:2], coords[2]) faces = self.tess.index(faces) (wx, px) = (self.white_surface.coordinates, self.pial_surface.coordinates) if all(len(np.shape(x)) > 1 for x in (faces, coords)): (wtx, ptx) = [ np.transpose([sx[:,ff] if ff[0] >= 0 else null for ff in faces.T], (2,1,0)) for null in [np.full((3, wx.shape[0]), np.nan)] for sx in (wx, px)] elif faces == -1: return np.full(selfx.shape[0], np.nan) else: (wtx, ptx) = [sx[:,faces].T for sx in (wx, px)] (wu, pu) = [geo.barycentric_to_cartesian(tx, bc) for tx in (wtx, ptx)] return wu*ds + pu*(1 - ds)