Python numpy.in1d() Examples

The following are 30 code examples for showing how to use numpy.in1d(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: models   Author: kipoi   File: dataloader_m.py    License: MIT License 6 votes vote down vote up
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 2
Project: contextualbandits   Author: david-cortes   File: offpolicy.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _fit(self, classif, X, a, r, p, rs):
        obs_take = np.in1d(a, self.tree.node_comparisons[classif][0])
        X_node = X[obs_take, :]
        a_node = a[obs_take]
        r_node = r[obs_take]
        p_node = p[obs_take]
        
        r_more_onehalf = r_node >= .5
        y = (  np.in1d(a_node, self.tree.node_comparisons[classif][2])  ).astype('uint8')
        
        y_node = y.copy()
        y_node[r_more_onehalf] = 1. - y[r_more_onehalf]
        w_node = (.5 - r_node) / p_node
        w_node[r_more_onehalf] = (  (r_node - .5) / p_node  )[r_more_onehalf]
        w_node = w_node * (w_node.shape[0] / np.sum(w_node))
        
        n_pos = y_node.sum()
        if y_node.shape[0] == 0:
            self._oracles[classif] = _RandomPredictor(_check_random_state(rs[classif]))
        elif n_pos == y_node.shape[0]:
            self._oracles[classif] = _OnePredictor()
        elif n_pos == 0:
            self._oracles[classif] = _ZeroPredictor()
        else:
            self._oracles[classif].fit(X_node, y_node, sample_weight = w_node) 
Example 3
Project: NeuroKit   Author: neuropsychology   File: download_mit_arrhythmia.py    License: MIT License 6 votes vote down vote up
def read_file(file, participant):
    """Utility function
    """
    # Get signal
    data = pd.DataFrame({"ECG": wfdb.rdsamp(file[:-4])[0][:, 0]})
    data["Participant"] = "MIT-Arrhythmia_%.2i" %(participant)
    data["Sample"] = range(len(data))
    data["Sampling_Rate"] = 360
    data["Database"] = "MIT-Arrhythmia-x" if "x_mitdb" in file else "MIT-Arrhythmia"

    # getting annotations
    anno = wfdb.rdann(file[:-4], 'atr')
    anno = np.unique(anno.sample[np.in1d(anno.symbol, ['N', 'L', 'R', 'B', 'A', 'a', 'J', 'S', 'V', 'r', 'F', 'e', 'j', 'n', 'E', '/', 'f', 'Q', '?'])])
    anno = pd.DataFrame({"Rpeaks": anno})
    anno["Participant"] = "MIT-Arrhythmia_%.2i" %(participant)
    anno["Sampling_Rate"] = 360
    anno["Database"] = "MIT-Arrhythmia-x" if "x_mitdb" in file else "MIT-Arrhythmia"

    return data, anno 
Example 4
Project: simnibs   Author: simnibs   File: electrode_placement.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _get_roi(center, radius, mesh, mesh_surface=[5, 1005], min_cos=.1):
    ''' Defines the region of interest of a given radius. Around a given center. Only
    node with normals pointing in the given direction are
    considered. Returns a list of triangles with at least 1 element in the ROI'''
    center = np.array(center, dtype=float)
    nodes_in_surface = _get_nodes_in_surface(mesh, mesh_surface)
    if len(nodes_in_surface) == 0:
        raise ValueError('Could not find surface {0} in mesh'.format(mesh_surface))
    distances = np.linalg.norm(center - mesh.nodes[nodes_in_surface], axis=1)
    normals = mesh.nodes_normals()[nodes_in_surface]
    center_normal = normals[np.argmin(distances)]
    in_roi = nodes_in_surface[(distances <= radius) *
                              (center_normal.dot(normals.T) > min_cos)]
    tr_in_roi = np.any(
        np.in1d(mesh.elm[mesh.elm.triangles, :3], in_roi).reshape(-1, 3), axis=1)
    roi_nodes, roi_triangles_reordering = \
        np.unique(mesh.elm[mesh.elm.triangles[tr_in_roi], :3], return_inverse=True)
    return mesh.elm.triangles[tr_in_roi], roi_nodes, roi_triangles_reordering.reshape(-1,
                                                                                      3) 
Example 5
Project: simnibs   Author: simnibs   File: electrode_placement.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _move_point(new_position, to_be_moved, nodes, triangles, min_angle=0.25,
                edge_list=None, kdtree=None):
    '''Moves one point to the new_position. The angle of the patch should not become less
    than min_angle (in radians) '''
    # Certify that the new_position is inside the patch
    tr = _triangle_with_points(np.atleast_2d(new_position), triangles, nodes,
                               edge_list=edge_list, kdtree=kdtree)
    tr_with_node = np.where(np.any(triangles == to_be_moved, axis=1))[0]
    patch = triangles[tr_with_node]
    if not np.in1d(tr, tr_with_node):
        return None, None
    new_nodes = np.copy(nodes)
    position = nodes[to_be_moved]
    d = new_position - position
    # Start from the full move and go back
    for t in np.linspace(0, 1, num=10)[::-1]:
        new_nodes[to_be_moved] = position + t*d
        angle = np.min(_calc_triangle_angles(new_nodes[patch]))
        if angle > min_angle:
            break
    # Return the new node list and the minimum angle in the patch
    return new_nodes, angle 
Example 6
Project: simnibs   Author: simnibs   File: fem.py    License: GNU General Public License v3.0 6 votes vote down vote up
def apply_to_solution(self, x, dof_map):
        ''' Applies the dirichlet BC to a solution
        Parameters:
        -------
        x: numpy array
            Righ-hand side
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b

        Returns:
        ------
        x: numpy array
            Righ-hand side, modified
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b, modified
        '''
        if np.any(np.in1d(self.nodes, dof_map.inverse)):
            raise ValueError('Found DOFs already defined')
        dof_inverse = np.hstack((dof_map.inverse, self.nodes))
        x = np.atleast_2d(x)
        if x.shape[0] < x.shape[1]:
            x = x.T
        x = np.vstack((x, np.tile(self.values, (x.shape[1], 1)).T))
        return x, dofMap(dof_inverse) 
Example 7
Project: simnibs   Author: simnibs   File: test_mesh_io.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_join_mesh_data(self, sphere3_msh):
        m1 = sphere3_msh.crop_mesh([3, 1003])
        m1.nodedata = [mesh_io.NodeData(value=m1.nodes.node_coord)]
        m1.elmdata = [m1.elements_baricenters()]
        m2 = sphere3_msh.crop_mesh([5, 1005])
        m2.nodedata = [mesh_io.NodeData(value=m2.nodes.node_number)]
        m2.elmdata = [mesh_io.ElementData(value=m2.elm.tag1)]
        m = m1.join_mesh(m2)
        assert np.all(np.isclose(m.nodedata[0].value[:m1.nodes.nr],m1.nodes.node_coord))
        assert np.all(np.isnan(m.nodedata[0].value[m1.nodes.nr:]))

        v = m.elmdata[0].value
        ref = m1.elmdata[0].value
        assert np.all(np.isclose(v[np.in1d(m.elm.tag1, [3, 1003])], ref))
        assert np.all(np.isnan(v[~np.in1d(m.elm.tag1, [3, 1003])]))

        assert np.all(np.isclose(m.nodedata[1].value[m1.nodes.nr:],m2.nodes.node_number))
        assert np.all(np.isnan(m.nodedata[1].value[:m1.nodes.nr]))

        v = m.elmdata[1].value
        ref = m2.elmdata[0].value
        assert np.all(np.isclose(v[np.in1d(m.elm.tag1, [5, 1005])], ref))
        assert np.all(np.isnan(v[~np.in1d(m.elm.tag1, [5, 1005])])) 
Example 8
Project: yatsm   Author: ceholden   File: longtermmean.py    License: MIT License 6 votes vote down vote up
def group_years(years, interval=3):
    """ Return integers representing sequential groupings of years

    Note: years specified must be sorted

    Args:
        years (np.ndarray): the year corresponding to each EVI value
        interval (int, optional): number of years to group together
            (default: 3)

    Returns:
        np.ndarray: integers representing sequential year groupings

    """
    n_groups = math.ceil((years.max() - years.min()) / interval)
    if n_groups <= 1:
        return np.zeros_like(years, dtype=np.uint16)
    splits = np.array_split(np.arange(years.min(), years.max() + 1), n_groups)

    groups = np.zeros_like(years, dtype=np.uint16)
    for i, s in enumerate(splits):
        groups[np.in1d(years, s)] = i

    return groups 
Example 9
Project: yatsm   Author: ceholden   File: diagnostics.py    License: MIT License 6 votes vote down vote up
def __iter__(self):
        n = self.n
        n_folds = self.n_folds

        fold_sizes = (n // n_folds) * np.ones(n_folds, dtype=np.int)
        fold_sizes[:n % n_folds] += 1
        current = 0

        for fold_size in fold_sizes:
            start, stop = current, current + fold_size

            test_i = np.in1d(self.indices[:, 0], self.labels[start:stop])
            train_i = np.in1d(self.indices[:, 0], self.labels[stop:])

            yield ((self.indices[test_i, 1], self.indices[test_i, 2]),
                   (self.indices[train_i, 1], self.indices[train_i, 2]))
            current = stop 
Example 10
Project: yatsm   Author: ceholden   File: diagnostics.py    License: MIT License 6 votes vote down vote up
def _label_roi(self):
        """ Internal method to label region of interest image
        """
        labeled, n = scipy.ndimage.label(self.roi)

        labels = np.unique(labeled)
        self.labels = labels[~np.in1d(labels, self.mask_values)]
        self.n = self.labels.size

        n_samples = (~np.in1d(self.roi, self.mask_values)).sum()
        self.indices = np.zeros((n_samples, 3), dtype=np.int)
        _start = 0

        for l in self.labels:
            _n = (labeled == l).sum()
            _row, _col = np.where(labeled == l)
            self.indices[_start:_start + _n, 0] = l
            self.indices[_start:_start + _n, 1] = _row
            self.indices[_start:_start + _n, 2] = _col
            _start += _n

        if self.shuffle:
            self.rng.shuffle(self.labels) 
Example 11
Project: yatsm   Author: ceholden   File: pixel.py    License: MIT License 6 votes vote down vote up
def plot_TS(dates, y, seasons):
    """ Create a standard timeseries plot

    Args:
        dates (iterable): sequence of datetime
        y (np.ndarray): variable to plot
        seasons (bool): Plot seasonal symbology
    """
    # Plot data
    if seasons:
        months = np.array([d.month for d in dates])
        for season_months, color, alpha in SEASONS.values():
            season_idx = np.in1d(months, season_months)
            plt.plot(dates[season_idx], y[season_idx], marker='o',
                     mec=color, mfc=color, alpha=alpha, ls='')
    else:
        plt.scatter(dates, y, c='k', marker='o', edgecolors='none', s=35)
    plt.xlabel('Date') 
Example 12
Project: pylogit   Author: timothyb0912   File: bootstrap_sampler.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ensure_resampled_obs_ids_in_df(resampled_obs_ids, orig_obs_id_array):
    """
    Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
    Raises a helpful ValueError if not.

    Parameters
    ----------
    resampled_obs_ids : 1D ndarray of ints.
        Should contain the observation ids of the observational units that will
        be used in the current bootstrap sample.
    orig_obs_id_array : 1D ndarray of ints.
        Should countain the observation ids of the observational units in the
        original dataframe containing the data for this model.

    Returns
    -------
    None.
    """
    if not np.in1d(resampled_obs_ids, orig_obs_id_array).all():
        msg =\
            "All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`."
        raise ValueError(msg)
    return None 
Example 13
Project: ffn   Author: google   File: segmentation.py    License: Apache License 2.0 6 votes vote down vote up
def clear_dust(data, min_size=10):
  """Removes small objects from a segmentation array.

  Replaces objects smaller than `min_size` with 0 (background).

  Args:
    data: numpy array of segment IDs
    min_size: minimum size in voxels of an object to be retained

  Returns:
    the data array (modified in place)
  """
  ids, sizes = np.unique(data, return_counts=True)
  small = ids[sizes < min_size]
  small_mask = np.in1d(data.flat, small).reshape(data.shape)
  data[small_mask] = 0
  return data 
Example 14
Project: rankeval   Author: hpclab   File: dataset.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def subset(self, query_ids, name=None):
        """
        This method return a subset of the dataset according to the query_ids
        parameter.

        Parameters
        ----------
        query_ids : numpy 1d array of int
            It is a ndarray with the query_ids to select
        name : str
            The name to give to the dataset

        Returns
        -------
        datasets : rankeval.dataset.Dataset
            The resulting dataset with only the query_ids requested
        """
        qid_map = self.get_qids_dataset()
        mask = np.in1d(qid_map, query_ids)

        return Dataset(self.X[mask], self.y[mask],
                       qid_map[mask], name=name) 
Example 15
Project: UWGeodynamics   Author: underworldcode   File: surfaceProcesses.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _update_material_types(self):

        # What do the materials (in air/sediment terms) look like now?
        if self.Model.mesh.dim == 3:
            material_flags = self._determine_particle_state()
        if self.Model.mesh.dim == 2:
            material_flags = self._determine_particle_state_2D()

        # If any materials changed state, update the Underworld material types
        mi = self.Model.materialField.data

        # convert air to sediment
        for air_material in self.airIndex:
            sedimented_mask = np.logical_and(np.in1d(mi, air_material), material_flags)
            mi[sedimented_mask] = self.sedimentIndex

        # convert sediment to air
        for air_material in self.airIndex:
            eroded_mask = np.logical_and(~np.in1d(mi, air_material), ~material_flags)
            mi[eroded_mask] = self.airIndex[0] 
Example 16
Project: TheCannon   Author: annayqho   File: find_all_candidates.py    License: MIT License 6 votes vote down vote up
def get_labels(ids_find):
    """ Labels to make Cannon model spectra """
    a = pyfits.open("%s/lamost_catalog_full.fits" %LAB_DIR)
    data = a[1].data
    a.close()
    id_all = data['lamost_id']
    id_all = np.array(id_all)
    id_all = np.array([val.strip() for val in id_all])
    snr_all = data['cannon_snrg']
    chisq_all = data['cannon_chisq']
    teff = data['cannon_teff']
    logg = data['cannon_logg']
    feh = data['cannon_m_h']
    afe = data['cannon_alpha_m']
    ak = data['cannon_a_k']
    labels = np.vstack((teff,logg,feh,afe,ak))
    choose = np.in1d(id_all, ids_find)
    id_choose = id_all[choose]
    label_choose = labels[:,choose]
    snr_choose = snr_all[choose]
    chisq_choose = chisq_all[choose]
    inds = np.array([np.where(id_choose==val)[0][0] for val in ids_find])
    print(id_choose[inds][100])
    print(ids_find[100])
    return label_choose[:,inds], snr_choose[inds], chisq_choose[inds] 
Example 17
Project: Modeling-Cloth   Author: the3dadvantage   File: UVShape.py    License: MIT License 5 votes vote down vote up
def get_piece_bool(num, dict):
    '''Uses a vertex number to find the right bool array
    as created by divide_garment()'''
    count = 0
    nums = dict['garment_pieces']['numbers_array']    
    for i in nums:
        if np.in1d(num, i):
            return count
        count += 1 
Example 18
Project: Modeling-Cloth   Author: the3dadvantage   File: UVShape.py    License: MIT License 5 votes vote down vote up
def find_linked(ob, vert, per_face='empty'):
    '''Takes a vert and returns an array of linked face indices'''
    the_coffee_is_hot = True
    fidx = np.arange(len(ob.data.polygons))
    eidx = np.arange(len(ob.data.edges))
    f_set = np.array([])
    e_set = np.array([])
    verts = ob.data.vertices
    verts[vert].select = True
    v_p_f_count = [len(p.vertices) for p in ob.data.polygons]
    max_count = np.max(v_p_f_count)
    if per_face == 'empty':    
        per_face = [[i for i in poly.vertices] for poly in ob.data.polygons]
    for i in per_face:
        for j in range(max_count-len(i)):
            i.append(i[0])
    verts_per_face = np.array(per_face)
    vert=np.array([vert])
    
    while the_coffee_is_hot:
        booly = np.any(np.in1d(verts_per_face, vert).reshape(verts_per_face.shape), axis=1)
        f_set = np.append(f_set, fidx[booly])
        new_verts = verts_per_face[booly].ravel()
        if len(new_verts) == 0:
            return np.array(f_set, dtype=np.int64)
            
        cull = np.in1d(new_verts, vert)
        vert = new_verts[~cull]
        verts_per_face = verts_per_face[~booly]
        fidx = fidx[~booly] 
Example 19
Project: Modeling-Cloth   Author: the3dadvantage   File: UVShape.py    License: MIT License 5 votes vote down vote up
def divide_garment(ob, dict):
    '''Creates a set of bool arrays and a set of number arrays
    for indexing a sub set of the uv coords. The nuber arrays can
    be used to look up wich bool array to use based on a vertex number'''
    if ob == 'empty':
        ob = bpy.context.object    
    #-----------------------------------    
    v_count = len(ob.data.vertices)
    idx = np.arange(v_count)
    full_set = np.array([])
    dict['islands'] = []
    v_list = [[i for i in poly.vertices] for poly in ob.data.polygons]
    v_in_faces = np.hstack(v_list)
    dict['v_in_faces'] = v_in_faces
    remaining = [1]
    vert = 0
    while len(remaining) > 0:
        linked = find_linked(ob, vert, v_list)
        selected = np.unique(np.hstack(np.array(v_list)[linked]).ravel())
        dict['islands'].append(selected)
        full_set = np.append(full_set, selected)
        remain_bool = np.in1d(idx, full_set, invert=True)
        remaining = idx[remain_bool] 
        if len(remaining) == 0:
            break
        vert = remaining[0]
################################# 
Example 20
Project: DeepLung   Author: uci-cbcl   File: prepare.py    License: GNU General Public License v3.0 5 votes vote down vote up
def binarize_per_slice(image, spacing, intensity_th=-600, sigma=1, area_th=30, eccen_th=0.99, bg_patch_size=10):
    bw = np.zeros(image.shape, dtype=bool)
    
    # prepare a mask, with all corner values set to nan
    image_size = image.shape[1]
    grid_axis = np.linspace(-image_size/2+0.5, image_size/2-0.5, image_size)
    x, y = np.meshgrid(grid_axis, grid_axis)
    d = (x**2+y**2)**0.5
    nan_mask = (d<image_size/2).astype(float)
    nan_mask[nan_mask == 0] = np.nan
    for i in range(image.shape[0]):
        # Check if corner pixels are identical, if so the slice  before Gaussian filtering
        if len(np.unique(image[i, 0:bg_patch_size, 0:bg_patch_size])) == 1:
            current_bw = scipy.ndimage.filters.gaussian_filter(np.multiply(image[i].astype('float32'), nan_mask), sigma, truncate=2.0) < intensity_th
        else:
            current_bw = scipy.ndimage.filters.gaussian_filter(image[i].astype('float32'), sigma, truncate=2.0) < intensity_th
        
        # select proper components
        label = measure.label(current_bw)
        properties = measure.regionprops(label)
        valid_label = set()
        for prop in properties:
            if prop.area * spacing[1] * spacing[2] > area_th and prop.eccentricity < eccen_th:
                valid_label.add(prop.label)
        current_bw = np.in1d(label, list(valid_label)).reshape(label.shape)
        bw[i] = current_bw
        
    return bw 
Example 21
Project: DeepLung   Author: uci-cbcl   File: prepare.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fill_hole(bw):
    # fill 3d holes
    label = measure.label(~bw)
    # idendify corner components
    bg_label = set([label[0, 0, 0], label[0, 0, -1], label[0, -1, 0], label[0, -1, -1], \
                    label[-1, 0, 0], label[-1, 0, -1], label[-1, -1, 0], label[-1, -1, -1]])
    bw = ~np.in1d(label, list(bg_label)).reshape(label.shape)
    
    return bw 
Example 22
Project: simnibs   Author: simnibs   File: electrode_placement.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_nodes_in_surface(mesh, surface_tags):
    tr_of_interest = (mesh.elm.elm_type == 2) * (np.in1d(mesh.elm.tag1, surface_tags))
    nodes_in_surface = np.unique(mesh.elm.node_number_list[tr_of_interest, :3])
    return nodes_in_surface 
Example 23
Project: simnibs   Author: simnibs   File: fem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def apply(self, A, b, dof_map):
        ''' Applies the dirichlet BC to the system
        Parameters:
        -------
        A: scipy.sparse.csr
            Sparse matrix
        b: numpy array or None
            Righ-hand side. if None, it will return None
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b
        Returns:
        ------
        A: scipy.sparse.csr
            Sparse matrix, modified
        b: numpy array
            Righ-hand side, modified
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b, modified
        '''
        if np.any(~np.in1d(self.nodes, dof_map.inverse)):
            raise ValueError('BC node indices not found in dof_map')
        stay = np.ones(A.shape[0], dtype=bool)
        stay[dof_map[self.nodes]] = False
        if b is not None:
            b, _ = self.apply_to_rhs(A, b, dof_map)
        A, dof_map = self.apply_to_matrix(A, dof_map)
        return A, b, dof_map 
Example 24
Project: simnibs   Author: simnibs   File: fem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def apply_to_rhs(self, A, b, dof_map):
        ''' Applies the dirichlet BC to the system
        Parameters:
        -------
        A: scipy.sparse.csr
            Sparse matrix
        b: numpy array or None
            Righ-hand side. if None, it will return None
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b
        Returns:
        ------
        b: numpy array
            Righ-hand side, modified
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b, modified
        '''
        if np.any(~np.in1d(self.nodes, dof_map.inverse)):
            raise ValueError('BC node indices not found in dof_map')
        stay = np.ones(b.shape[0], dtype=bool)
        stay[dof_map[self.nodes]] = False
        b = np.atleast_2d(b)
        if b.shape[0] < b.shape[1]:
            b = b.T
        A = A.tocsc()
        s = A[:, dof_map[self.nodes]].dot(self.values)
        s = np.atleast_2d(s)
        if s.shape[0] < s.shape[1]:
            s = s.T
        b = b - s
        b = b[stay]
        dof_map = dofMap(dof_map.inverse[stay])
        return b, dof_map 
Example 25
Project: simnibs   Author: simnibs   File: mesh_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def elm_node_coords(self, elm_nr=None, tag=None, elm_type=None):
        """ Returns the position of each of the element's nodes

        Arguments
        -----------------------------
        elm_nr: (optional) array of ints
            Elements to return, default: Return all elements
        tag: (optional) array of ints
            Only return elements with specified tag. default: all tags
        elm_type: (optional) array of ints
            Only return elements of specified type. default: all

        Returns
        -----------------------------
        Nx4x3 ndarray
            Array with node position of every element
            For triangles, the fourth coordinates are 0,0,0
        """
        elements_to_return = np.ones((self.elm.nr, ), dtype=bool)

        if elm_nr is not None:
            elements_to_return[elm_nr] = True

        if elm_type is not None:
            elements_to_return = np.logical_and(
                elements_to_return,
                np.in1d(self.elm.elm_type, elm_type))

        if tag is not None:
            elements_to_return = np.logical_and(
                elements_to_return,
                np.in1d(self.elm.tag1, tag))

        tmp_node_coord = np.vstack((self.nodes.node_coord, [0, 0, 0]))

        elm_node_coords = \
            tmp_node_coord[self.elm.node_number_list[elements_to_return, :] - 1]

        return elm_node_coords 
Example 26
Project: simnibs   Author: simnibs   File: test_mesh_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_get_faces(self, sphere3_msh):
        elm = sphere3_msh.elm
        faces, th_faces, adjacency_list = elm.get_faces()
        th = elm[elm.tetrahedra]
        faces_th = th[:, [[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]]]
        assert np.all(faces_th[0] == faces[th_faces[0]])
        assert np.sum(np.in1d(th[adjacency_list[0, 0]], th[adjacency_list[0, 1]])) == 3
        assert np.any(np.in1d(th_faces[0], th_faces[adjacency_list[th_faces[0, 0], 1]]))

        # Here I don't care about order because it might be flipped
        assert np.all(np.unique(faces_th[-1]) == np.unique(faces[th_faces[-1]]))
        assert np.sum(np.in1d(th[adjacency_list[-1, 0]], th[adjacency_list[-1, 1]])) == 3
        assert np.any(np.in1d(th_faces[-1], th_faces[adjacency_list[th_faces[-1, 0], 1]])) 
Example 27
Project: simnibs   Author: simnibs   File: test_mesh_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_crop_mesh_nodes(self, sphere3_msh):
        target = range(1, 11)
        w_node = np.any(np.in1d(sphere3_msh.elm.node_number_list,
                                target).reshape(-1,4), axis=1)
        neighbours = np.unique(sphere3_msh.elm.node_number_list[w_node].T)[1:]
        orig_coords = sphere3_msh.nodes[neighbours]
        cropped_mesh = sphere3_msh.crop_mesh(nodes=range(1, 11))
        assert np.allclose(orig_coords, cropped_mesh.nodes.node_coord) 
Example 28
Project: simnibs   Author: simnibs   File: test_mesh_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_reconstruct_surfaces_tag(self, sphere3_msh):
        m = sphere3_msh.crop_mesh(elm_type=4)
        m.reconstruct_surfaces(tags=[4])
        assert ~np.any(np.in1d(m.elm.tag1, [1003, 1005])) 
Example 29
Project: hgru4rec   Author: mquad   File: hgru4rec.py    License: MIT License 5 votes vote down vote up
def set_item_embeddings(self, E, values):
        if isinstance(values, dict):
            keys, values = values.keys(), np.vstack(list(values.values()))
        elif isinstance(values, np.ndarray):
            # use item ids ranging from 0 to the number of rows in values
            keys, values = np.arange(values.shape[0]), values
        else:
            raise NotImplementedError('Unsupported type')
        # map item ids to the internal indices
        mask = np.in1d(keys, self.itemidmap.index, assume_unique=True)
        idx = self.itemidmap[keys].dropna().values.astype(np.int)
        emb = E.get_value()
        emb[idx] = values[mask]
        E.set_value(emb) 
Example 30
Project: yatsm   Author: ceholden   File: ccdc.py    License: MIT License 5 votes vote down vote up
def time_ccdcesque1(self, setup):
        """ Bench with 'defaults' defined in setup with most tests turned off
        """
        kwargs = version_kwargs(setup['kwargs'])
        model = CCDCesque(**kwargs)
        for col in range(setup['Y'].shape[-1]):
            _Y, _X, _dates = setup['Y'][..., col], setup['X'], setup['dates']
            mask = np.in1d(_Y[-1, :], [0, 1])
            model.fit(_X[mask, :], _Y[:, mask], _dates[mask])