numpy.c_

Here are the examples of the python api numpy.c_ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

151 Examples 7

Example 51

Project: tracer
Source File: test_tracer_engine.py
View license
    def setUp(self):

        self.x = 1/(math.sqrt(2))
        dir = N.c_[[0,-self.x,self.x],[0,0,-1]]
        position = N.c_ [[0,2,1],[0,2,1]]
        self._bund = RayBundle(position, dir, energy=N.ones(2))
        
        rot1 = general_axis_rotation([1,0,0],N.pi/4)
        surf1 = Surface(FlatGeometryManager(), opt.perfect_mirror, rotation=rot1)
        surf2 = Surface(FlatGeometryManager(), opt.perfect_mirror)
        assembly = Assembly()
        object = AssembledObject()
        object.add_surface(surf1)
        object.add_surface(surf2)
        assembly.add_object(object)
        
        self.engine = TracerEngine(assembly)

Example 52

Project: tracer
Source File: test_tracer_engine.py
View license
    def test_paraxial_ray(self):
        """A paraxial ray in reflected correctly"""
        bund = RayBundle()
        bund.set_vertices(N.c_[[0.01, 0., 2.]])
        bund.set_directions(N.c_[[0., 0., -1.]])
        bund.set_energy(N.r_[100.])
        bund.set_ref_index(N.r_[1])
        
        self.engine.ray_tracer(bund, 15, 10.)
        non_degenerate = self.engine.tree[-1].get_energy() > 10
        v = self.engine.tree[-1].get_vertices()[:,non_degenerate]
        d = self.engine.tree[-1].get_directions()[:,non_degenerate]
        # Not high equality demanded, because of spherical aberration.
        N.testing.assert_array_almost_equal(v, N.c_[[-0.01, 0., 1.5]], 2)
        N.testing.assert_array_almost_equal(d, N.c_[[0., 0., 1.]], 2)

Example 53

Project: tracer
Source File: test_tracer_tree.py
View license
    def test_tree1(self):
        """Tests that the tracing tree works, with three rays"""
        x = 1./(math.sqrt(2))
        dir = N.c_[[0,x,x],[0,-x,x],[0,0,1.]]
        position = N.c_[[0,0,2.],[0,0,2.],[0,0.,2.]]
        bund = RayBundle(position, dir, energy=N.ones(3))

        self.engine = TracerEngine(self.assembly)

        self.engine.ray_tracer(bund,3,.05)[0]
        params = self.engine.tree.ordered_parents()
        correct_params = [N.r_[0,1,2],N.r_[1,2],N.r_[0]]
        N.testing.assert_equal(params, correct_params)

Example 54

Project: tracer
Source File: test_tracer_tree.py
View license
    def test_tree2(self):
        """Tests that the tracing tree works, with a new set of rays"""
        x = 1./(math.sqrt(2))
        position = N.c_[[0,0.,-5.],[0,0.,2.],[0,2.,-5.],[0,0.,0],[0,0,2.]]
        dir = N.c_[[0,0,1.],[0,x,-x],[0,0,-1.],[0,0,1.],[0,-x,x]]
        bund = RayBundle(position, dir, energy=N.ones(5))

        self.engine = TracerEngine(self.assembly)
        self.engine.ray_tracer(bund,3,.05)[0]
        
        params = self.engine.tree.ordered_parents()
        correct_params = [N.r_[0,1,3,4],N.r_[2,3,1],N.r_[2,1]]
        N.testing.assert_equal(params, correct_params)

Example 55

Project: tracer
Source File: boundary_shape.py
View license
    def transform_frame(self, transform):
        """ 
        Transforms the center of the boundary shape into the global coordinates; this occurs
        when the assembly or object containing the surface is transformed
        """
        self._temp_loc = N.dot(transform, N.append(self._loc, N.c_[[1]]))

Example 56

Project: tracer
Source File: flat_surface.py
View license
    def __init__(self, width, height):
        """
        Arguments:
        width - the extent along the x axis in the local frame (sets self._w)
        height - the extent along the y axis in the local frame (sets self._h)
        """
        if width <= 0:
            raise ValueError("Width must be positive")
        if height <= 0:
            raise ValueError("Height must be positive")
        
        self._half_dims = N.c_[[width, height]]/2.
        FiniteFlatGM.__init__(self)

Example 57

Project: APGL
Source File: PySparseGraph.py
View license
    def getAllDirEdges(self):
        """
        Returns the set of directed edges of the current graph as a matrix in which each
        row corresponds to an edge. For an undirected graph, there is an edge from
        v1 to v2 and from v2 to v1 if v2!=v1.

        :returns: A matrix with 2 columns, and each row corresponding to an edge.
        """
        (rows, cols) = PySparseUtils.nonzero(self.W)
        edges = numpy.c_[rows, cols]

        return edges

Example 58

Project: gpustats
Source File: pdfs.py
View license
def normpdf_multi(x, means, std, logged=True, get=True):
    if logged:
        cu_func = cu_module.get_function('log_pdf_normal')
    else:
        cu_func = cu_module.get_function('pdf_normal')

    packed_params = np.c_[means, std]

    if not isinstance(x, GPUArray):
        x = util.prep_ndarray(x)

    return _univariate_pdf_call(cu_func, x, packed_params, get)

Example 59

Project: dolo
Source File: smolyak.py
View license
def smolyak_grids(d,l):

    ret,incr = build_basic_grids(l)
    tab =  build_indices_levels(l)

    eee =  [ [ tab[i] for i in e] for e in enum( d, l) ]
    smolyak_indices = []
    for ee in eee:
        smolyak_indices.extend( [e for e in product( *ee ) ] )

    fff =  [ [ incr[i] for i in e] for e in enum( d, l) ]
    smolyak_points = []
    for ff in fff:
        smolyak_points.extend( [f for f in product( *ff ) ] )

    smolyak_points = numpy.c_[smolyak_points]

    return [smolyak_points, smolyak_indices]

Example 60

Project: rayopt
Source File: paraxial_trace.py
View license
    def print_trace(self):
        c = np.c_[self.path, self.n, self.y[:, 0], self.u[:, 0],
                  self.y[:, 1], self.u[:, 1]]
        return self.print_coeffs(
            c, "path/n/axial y/axial nu/chief y/chief nu".split("/"),
            sum=False)

Example 61

Project: rayopt
Source File: paraxial_trace.py
View license
    def print_trace(self):
        c = np.c_[self.path, self.n, self.y[:, 0], self.u[:, 0],
                  self.y[:, 1], self.u[:, 1]]
        return self.print_coeffs(
            c, "path/n/axial y/axial nu/chief y/chief nu".split("/"),
            sum=False)

Example 62

Project: krypy
Source File: deflation.py
View license
    def _apply_projection(self, Av):
        '''Apply the projection and store inner product.

        :param v: the vector resulting from an application of :math:`M_lAM_r`
          to the current Arnoldi vector. (CG needs special treatment, here).
        '''
        PAv, UAv = self.projection.apply_complement(Av, return_Ya=True)
        self.C = numpy.c_[self.C, UAv]
        return PAv

Example 63

Project: krypy
Source File: deflation.py
View license
    def _apply_projection(self, Av):
        '''Apply the projection and store inner product.

        :param v: the vector resulting from an application of :math:`M_lAM_r`
          to the current Arnoldi vector. (CG needs special treatment, here).
        '''
        PAv, UAv = self.projection.apply_complement(Av, return_Ya=True)
        self.C = numpy.c_[self.C, UAv]
        return PAv

Example 64

Project: krypy
Source File: deflation.py
View license
    def get_vectors(self, indices=None):
        '''Compute Ritz vectors.'''
        H_ = self._deflated_solver.H
        (n_, n) = H_.shape
        coeffs = self.coeffs if indices is None else self.coeffs[:, indices]
        return numpy.c_[self._deflated_solver.V[:, :n],
                        self._deflated_solver.projection.U].dot(coeffs)

Example 65

Project: krypy
Source File: deflation.py
View license
    def get_vectors(self, indices=None):
        '''Compute Ritz vectors.'''
        H_ = self._deflated_solver.H
        (n_, n) = H_.shape
        coeffs = self.coeffs if indices is None else self.coeffs[:, indices]
        return numpy.c_[self._deflated_solver.V[:, :n],
                        self._deflated_solver.projection.U].dot(coeffs)

Example 66

Project: phy
Source File: visuals.py
View license
    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        if data.data_bounds is not None:
            self.data_range.from_bounds = data.data_bounds
            pos_tr = self.transforms.apply(data.pos)
        else:
            pos_tr = data.pos
        pos_tr = np.c_[pos_tr, data.depth]
        self.program['a_position'] = pos_tr.astype(np.float32)
        self.program['a_size'] = data.size.astype(np.float32)
        self.program['a_color'] = data.color.astype(np.float32)

Example 67

Project: phy
Source File: visuals.py
View license
    def set_data(self, *args, **kwargs):
        data = self.validate(*args, **kwargs)
        if data.data_bounds is not None:
            self.data_range.from_bounds = data.data_bounds
            pos_tr = self.transforms.apply(data.pos)
        else:
            pos_tr = data.pos
        pos_tr = np.c_[pos_tr, data.depth]
        self.program['a_position'] = pos_tr.astype(np.float32)
        self.program['a_size'] = data.size.astype(np.float32)
        self.program['a_color'] = data.color.astype(np.float32)

Example 68

View license
    def test_one(self):
        '''
        Lock in results on arbitrary data -- because meaningful runs take too long to run.
        '''
        fn = "one.txt"
        logging.info(fn)
        tmpOutfile = self.file_name(fn)

        half = self.pheno_whole.read().val
        pheno = SnpData(iid=self.pheno_whole.iid,sid=["pheno0","pheno1"],val=np.c_[half,half])

        spatial_coor = [[i,-i] for i in xrange(self.snpreader_whole.iid_count)]
        alpha_list = alpha_list_big=[int(v) for v in np.logspace(2,np.log10(4000), 2)]
        dataframe = heritability_spatial_correction(self.snpreader_whole,spatial_coor,self.snpreader_whole.iid,alpha_list,2,pheno,jackknife_count=2,permute_plus_count=1,permute_times_count=1,just_testing=True)

        dataframe.to_csv(tmpOutfile,sep="\t",index=False)
        referenceOutfile = TestFeatureSelection.reference_file("heritability_spatial_correction/"+fn)
        out,msg=ut.compare_files(tmpOutfile, referenceOutfile, tolerance)                
        self.assertTrue(out, "msg='{0}', ref='{1}', tmp='{2}'".format(msg, referenceOutfile, tmpOutfile))

Example 69

View license
    def test_one(self):
        '''
        Lock in results on arbitrary data -- because meaningful runs take too long to run.
        '''
        fn = "one.txt"
        logging.info(fn)
        tmpOutfile = self.file_name(fn)

        half = self.pheno_whole.read().val
        pheno = SnpData(iid=self.pheno_whole.iid,sid=["pheno0","pheno1"],val=np.c_[half,half])

        spatial_coor = [[i,-i] for i in xrange(self.snpreader_whole.iid_count)]
        alpha_list = alpha_list_big=[int(v) for v in np.logspace(2,np.log10(4000), 2)]
        dataframe = heritability_spatial_correction(self.snpreader_whole,spatial_coor,self.snpreader_whole.iid,alpha_list,2,pheno,jackknife_count=2,permute_plus_count=1,permute_times_count=1,just_testing=True)

        dataframe.to_csv(tmpOutfile,sep="\t",index=False)
        referenceOutfile = TestFeatureSelection.reference_file("heritability_spatial_correction/"+fn)
        out,msg=ut.compare_files(tmpOutfile, referenceOutfile, tolerance)                
        self.assertTrue(out, "msg='{0}', ref='{1}', tmp='{2}'".format(msg, referenceOutfile, tmpOutfile))

Example 70

View license
def test_rfe_set_params():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target
    clf = SVC(kernel="linear")
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    y_pred = rfe.fit(X, y).predict(X)

    clf = SVC()
    with warnings.catch_warnings(record=True):
        # estimator_params is deprecated
        rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1,
                  estimator_params={'kernel': 'linear'})
        y_pred2 = rfe.fit(X, y).predict(X)
    assert_array_equal(y_pred, y_pred2)

Example 71

View license
def test_rfe_features_importance():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target

    clf = RandomForestClassifier(n_estimators=20,
                                 random_state=generator, max_depth=2)
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    rfe.fit(X, y)
    assert_equal(len(rfe.ranking_), X.shape[1])

    clf_svc = SVC(kernel="linear")
    rfe_svc = RFE(estimator=clf_svc, n_features_to_select=4, step=0.1)
    rfe_svc.fit(X, y)

    # Check if the supports are equal
    assert_array_equal(rfe.get_support(), rfe_svc.get_support())

Example 72

View license
def test_rfe_mockclassifier():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target

    # dense model
    clf = MockClassifier()
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    rfe.fit(X, y)
    X_r = rfe.transform(X)
    clf.fit(X_r, y)
    assert_equal(len(rfe.ranking_), X.shape[1])
    assert_equal(X_r.shape, iris.data.shape)

Example 73

View license
def test_rfecv_mockclassifier():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = list(iris.target)   # regression test: list should be supported

    # Test using the score function
    rfecv = RFECV(estimator=MockClassifier(), step=1, cv=5)
    rfecv.fit(X, y)
    # non-regression test for missing worst feature:
    assert_equal(len(rfecv.grid_scores_), X.shape[1])
    assert_equal(len(rfecv.ranking_), X.shape[1])

Example 74

View license
def test_multi_task_lasso_and_enet():
    X, y, X_test, y_test = build_dataset()
    Y = np.c_[y, y]
    # Y_test = np.c_[y_test, y_test]
    clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
    assert_true(0 < clf.dual_gap_ < 1e-5)
    assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

    clf = MultiTaskElasticNet(alpha=1, tol=1e-8).fit(X, Y)
    assert_true(0 < clf.dual_gap_ < 1e-5)
    assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

Example 75

View license
def test_multi_task_lasso_readonly_data():
    X, y, X_test, y_test = build_dataset()
    Y = np.c_[y, y]
    with TempMemmap((X, Y)) as (X, Y):
        Y = np.c_[y, y]
        clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
        assert_true(0 < clf.dual_gap_ < 1e-5)
        assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

Example 76

View license
def test_rfe_set_params():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target
    clf = SVC(kernel="linear")
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    y_pred = rfe.fit(X, y).predict(X)

    clf = SVC()
    with warnings.catch_warnings(record=True):
        # estimator_params is deprecated
        rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1,
                  estimator_params={'kernel': 'linear'})
        y_pred2 = rfe.fit(X, y).predict(X)
    assert_array_equal(y_pred, y_pred2)

Example 77

View license
def test_rfe_features_importance():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target

    clf = RandomForestClassifier(n_estimators=20,
                                 random_state=generator, max_depth=2)
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    rfe.fit(X, y)
    assert_equal(len(rfe.ranking_), X.shape[1])

    clf_svc = SVC(kernel="linear")
    rfe_svc = RFE(estimator=clf_svc, n_features_to_select=4, step=0.1)
    rfe_svc.fit(X, y)

    # Check if the supports are equal
    assert_array_equal(rfe.get_support(), rfe_svc.get_support())

Example 78

View license
def test_rfe_mockclassifier():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = iris.target

    # dense model
    clf = MockClassifier()
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    rfe.fit(X, y)
    X_r = rfe.transform(X)
    clf.fit(X_r, y)
    assert_equal(len(rfe.ranking_), X.shape[1])
    assert_equal(X_r.shape, iris.data.shape)

Example 79

View license
def test_rfecv_mockclassifier():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = list(iris.target)   # regression test: list should be supported

    # Test using the score function
    rfecv = RFECV(estimator=MockClassifier(), step=1, cv=5)
    rfecv.fit(X, y)
    # non-regression test for missing worst feature:
    assert_equal(len(rfecv.grid_scores_), X.shape[1])
    assert_equal(len(rfecv.ranking_), X.shape[1])

Example 80

View license
def test_multi_task_lasso_and_enet():
    X, y, X_test, y_test = build_dataset()
    Y = np.c_[y, y]
    # Y_test = np.c_[y_test, y_test]
    clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
    assert_true(0 < clf.dual_gap_ < 1e-5)
    assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

    clf = MultiTaskElasticNet(alpha=1, tol=1e-8).fit(X, Y)
    assert_true(0 < clf.dual_gap_ < 1e-5)
    assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

Example 81

View license
def test_multi_task_lasso_readonly_data():
    X, y, X_test, y_test = build_dataset()
    Y = np.c_[y, y]
    with TempMemmap((X, Y)) as (X, Y):
        Y = np.c_[y, y]
        clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
        assert_true(0 < clf.dual_gap_ < 1e-5)
        assert_array_almost_equal(clf.coef_[0], clf.coef_[1])

Example 82

Project: popupcad
Source File: getjoints.py
View license
def getjoints(geoms,roundvalue):
    from popupcad.geometry.vertex import ShapeVertex
    from popupcad.filetypes.genericshapes import GenericLine
    
    tolerance = 10**(-roundvalue)

    lines = []

    for geom in geoms:
        p = geom.exteriorpoints()
        lines.extend(zip(p, p[1:] + p[:1]))
        for interior in geom.interiorpoints():
            lines.extend(zip(interior, interior[1:] + interior[:1]))

    l3 = popupcad.algorithms.points.distance_of_lines(lines, [0, 0])
    l4 = popupcad.algorithms.points.distance_of_lines(lines, [10 * tolerance, 0])
    l5 = popupcad.algorithms.points.distance_of_lines(lines, [10 * tolerance, 10 * tolerance])
    l6 = popupcad.algorithms.points.distance_of_lines(lines, [0, 10 * tolerance])
    l7 = popupcad.algorithms.points.distance_of_lines(lines, [10 * tolerance, 20 * tolerance])
    
    m = numpy.c_[l3, l4, l5, l6, l7]
    m = m.round(roundvalue)
    m2 = [tuple(items) for items in m.tolist()]
    m3 = list(set(m2))
#    jj = numpy.searchsorted(m3,m2)
    index_to_unique = [m3.index(item) for item in m2]
    indeces_to_orig = [[] for item in m3]
    [indeces_to_orig[item].append(ii) for ii, item in enumerate(index_to_unique)]

    newsegments = []
    for segments in indeces_to_orig:
        if len(segments) > 1:
            a = [lines[ii] for ii in segments]
            vertices = []
            [vertices.extend(item) for item in a[1:]]
            ordered_vertices = popupcad.algorithms.points.order_vertices(vertices,a[0],tolerance=tolerance)
            segs = list(zip(ordered_vertices[:-1], ordered_vertices[1:]))
            midpoints = popupcad.algorithms.points.segment_midpoints(segs)
            count = [0 for item in midpoints]
            for ii in segments:
                for jj, point in enumerate(midpoints):
                    if popupcad.algorithms.points.point_within_line(point,lines[ii],tolerance=tolerance):
                        count[jj] += 1
            newsegments.extend([seg for count_ii, seg in zip(count, segs) if count_ii > 1])

    generic_lines = [GenericLine([ShapeVertex(v1), ShapeVertex(v2)], []) for v1, v2 in newsegments]
    generic_lines = [item for item in generic_lines if len(item.get_exterior()) == 2]
    return generic_lines

Example 83

Project: popupcad
Source File: tetrahedron.py
View license
    def variable_list(self,density,point):
        points = numpy.c_[self.points.T,point]
        points = points.flatten().tolist()
        return [density]+points

Example 84

Project: lfd
Source File: demonstration.py
View license
    def __init__(self, full_cloud, id=None, full_color=None, downsample_size=0):
        """Inits SceneState
        
        Args:
            full_cloud: full (i.e. not downsampled) cloud
            id: unique id for this SceneState
            full_color: colors for the respective points of full_cloud. Should have the same dimensions as full_cloud
            downsample_size: if downsample_size is positive, the full cloud and color are downsampled to a voxel size of downsample_size, else they are not downsampled
        """
        self.full_cloud = full_cloud
        self.full_color = full_color
        if downsample_size > 0:
            global clouds
            from lfd.rapprentice import clouds
            if full_color is not None:
                cloud_color = clouds.downsample(np.c_[full_cloud, full_color], downsample_size)
                self.cloud = cloud_color[:,:3]
                self.color = cloud_color[:,3:]
            else:
                self.cloud = clouds.downsample(full_cloud, downsample_size)
                self.color = None
        else:
            self.cloud = full_cloud
            self.color = full_color
        if id is None:
            self.id = SceneState.get_unique_id()
        else:
            self.id = id

Example 85

Project: lfd
Source File: features.py
View license
    def features(self, state, **kwargs):
        self.tgt_cld = state.cloud
        self.tgt_ctx.set_cld(self.tgt_cld)
        self.costs = batch_tps_rpm_bij(self.src_ctx, self.tgt_ctx)
        return np.c_[self.costs, self.indicators]

Example 86

Project: lfd
Source File: features.py
View license
    def features(self, state, **kwargs):
        self.tgt_cld = state.cloud
        self.tgt_ctx.set_cld(self.tgt_cld)
        self.costs = batch_tps_rpm_bij(self.src_ctx, self.tgt_ctx, component_cost=True)
        return np.c_[self.costs, self.indicators]

Example 87

Project: lfd
Source File: features.py
View license
    def features(self, state, **kwargs):
        self.tgt_cld = state.cloud
        self.tgt_ctx.set_cld(self.tgt_cld)
        self.costs = batch_tps_rpm_bij(self.src_ctx, self.tgt_ctx, component_cost=True)[:, :SimpleMulFeats.N_costs]
        return np.c_[self.costs, self.indicators]

Example 88

Project: lfd
Source File: math_utils.py
View license
def invertHmat(hmat):
    R = hmat[:3,:3]
    t = hmat[:3,3]
    hmat_inv = np.r_[np.c_[R.T, -R.T.dot(t)], hmat[3,:][None,:]]
    return hmat_inv

Example 89

Project: scikit-beam
Source File: save_powder_output.py
View license
def save_output(tth, intensity, output_name, q_or_2theta, ext='.chi',
                err=None, dir_path=None):
    """
    Save output diffraction intensities into .chi, .dat or .xye file formats.
    If the extension(ext) of the output file is not selected it will be
    saved as a .chi file

    Parameters
    ----------
    tth : ndarray
        twotheta values (degrees) or Q values (Angstroms)
        shape (N, ) array

    intensity : ndarray
        intensity values (N, ) array

    output_name : str
        name for the saved output diffraction intensities

    q_or_2theta : {'Q', '2theta'}
        twotheta (degrees) or Q (Angstroms) values

    ext : {'.chi', '.dat', '.xye'}, optional
        save output diffraction intensities into .chi, .dat  or
        .xye file formats. (If the extension of output file is not
        selected it will be saved as a .chi file)

    err : ndarray, optional
        error value of intensity shape(N, ) array

    dir_path : str, optional
        new directory path to save the output data files
        eg: /Volumes/Data/experiments/data/
    """

    if q_or_2theta not in set(['Q', '2theta']):
        raise ValueError("It is expected to provide whether the data is"
                         " Q values(enter Q) or two theta values"
                         " (enter 2theta)")

    if q_or_2theta == "Q":
        des = ("""First column represents Q values (Angstroms) and second
        column represents intensities and if there is a third
        column it represents the error values of intensities.""")
    else:
        des = ("""First column represents two theta values (degrees) and
        second column represents intensities and if there is
        a third column it represents the error values of intensities.""")

    _validate_input(tth, intensity, err, ext)

    file_path = _create_file_path(dir_path, output_name, ext)

    with open(file_path, 'wb') as f:
        _HEADER = """{out_name}
        This file contains integrated powder x-ray diffraction
        intensities.
        {des}
        Number of data points in the file : {n_pts}
        ######################################################"""
        _encoding_writer(f, _HEADER.format(n_pts=len(tth),
                                           out_name=output_name,
                                           des=des))
        new_line = "\n"
        _encoding_writer(f, new_line)
        if (err is None):
            np.savetxt(f, np.c_[tth, intensity])
        else:
            np.savetxt(f, np.c_[tth, intensity, err])

Example 90

Project: scikit-learn
Source File: plot_pca_3d.py
View license
def plot_figs(fig_num, elev, azim):
    fig = plt.figure(fig_num, figsize=(4, 3))
    plt.clf()
    ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim)

    ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker='+', alpha=.4)
    Y = np.c_[a, b, c]

    # Using SciPy's SVD, this would be:
    # _, pca_score, V = scipy.linalg.svd(Y, full_matrices=False)

    pca = PCA(n_components=3)
    pca.fit(Y)
    pca_score = pca.explained_variance_ratio_
    V = pca.components_

    x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min()

    x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
    x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]]
    y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]]
    z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]]
    x_pca_plane.shape = (2, 2)
    y_pca_plane.shape = (2, 2)
    z_pca_plane.shape = (2, 2)
    ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane)
    ax.w_xaxis.set_ticklabels([])
    ax.w_yaxis.set_ticklabels([])
    ax.w_zaxis.set_ticklabels([])

Example 91

Project: scikit-learn
Source File: test_rfe.py
View license
def test_rfe():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    X_sparse = sparse.csr_matrix(X)
    y = iris.target

    # dense model
    clf = SVC(kernel="linear")
    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
    rfe.fit(X, y)
    X_r = rfe.transform(X)
    clf.fit(X_r, y)
    assert_equal(len(rfe.ranking_), X.shape[1])

    # sparse model
    clf_sparse = SVC(kernel="linear")
    rfe_sparse = RFE(estimator=clf_sparse, n_features_to_select=4, step=0.1)
    rfe_sparse.fit(X_sparse, y)
    X_r_sparse = rfe_sparse.transform(X_sparse)

    assert_equal(X_r.shape, iris.data.shape)
    assert_array_almost_equal(X_r[:10], iris.data[:10])

    assert_array_almost_equal(rfe.predict(X), clf.predict(iris.data))
    assert_equal(rfe.score(X, y), clf.score(iris.data, iris.target))
    assert_array_almost_equal(X_r, X_r_sparse.toarray())

Example 92

Project: scikit-learn
Source File: test_rfe.py
View license
def test_rfecv():
    generator = check_random_state(0)
    iris = load_iris()
    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
    y = list(iris.target)   # regression test: list should be supported

    # Test using the score function
    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5)
    rfecv.fit(X, y)
    # non-regression test for missing worst feature:
    assert_equal(len(rfecv.grid_scores_), X.shape[1])
    assert_equal(len(rfecv.ranking_), X.shape[1])
    X_r = rfecv.transform(X)

    # All the noisy variable were filtered out
    assert_array_equal(X_r, iris.data)

    # same in sparse
    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5)
    X_sparse = sparse.csr_matrix(X)
    rfecv_sparse.fit(X_sparse, y)
    X_r_sparse = rfecv_sparse.transform(X_sparse)
    assert_array_equal(X_r_sparse.toarray(), iris.data)

    # Test using a customized loss function
    scoring = make_scorer(zero_one_loss, greater_is_better=False)
    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5,
                  scoring=scoring)
    ignore_warnings(rfecv.fit)(X, y)
    X_r = rfecv.transform(X)
    assert_array_equal(X_r, iris.data)

    # Test using a scorer
    scorer = get_scorer('accuracy')
    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5,
                  scoring=scorer)
    rfecv.fit(X, y)
    X_r = rfecv.transform(X)
    assert_array_equal(X_r, iris.data)

    # Test fix on grid_scores
    def test_scorer(estimator, X, y):
        return 1.0
    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, cv=5,
                  scoring=test_scorer)
    rfecv.fit(X, y)
    assert_array_equal(rfecv.grid_scores_, np.ones(len(rfecv.grid_scores_)))

    # Same as the first two tests, but with step=2
    rfecv = RFECV(estimator=SVC(kernel="linear"), step=2, cv=5)
    rfecv.fit(X, y)
    assert_equal(len(rfecv.grid_scores_), 6)
    assert_equal(len(rfecv.ranking_), X.shape[1])
    X_r = rfecv.transform(X)
    assert_array_equal(X_r, iris.data)

    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=2, cv=5)
    X_sparse = sparse.csr_matrix(X)
    rfecv_sparse.fit(X_sparse, y)
    X_r_sparse = rfecv_sparse.transform(X_sparse)
    assert_array_equal(X_r_sparse.toarray(), iris.data)

    # Verifying that steps < 1 don't blow up.
    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=.2, cv=5)
    X_sparse = sparse.csr_matrix(X)
    rfecv_sparse.fit(X_sparse, y)
    X_r_sparse = rfecv_sparse.transform(X_sparse)
    assert_array_equal(X_r_sparse.toarray(), iris.data)

Example 93

Project: scipy
Source File: test_bsplines.py
View license
    def test_splrep(self):
        x, y = self.xx, self.yy
        # test that "new" splrep is equivalent to _impl.splrep
        tck = splrep(x, y)
        t, c, k = _impl.splrep(x, y)
        assert_allclose(tck[0], t, atol=1e-15)
        assert_allclose(tck[1], c, atol=1e-15)
        assert_equal(tck[2], k)

        # also cover the `full_output=True` branch
        tck_f, _, _, _ = splrep(x, y, full_output=True)
        assert_allclose(tck_f[0], t, atol=1e-15)
        assert_allclose(tck_f[1], c, atol=1e-15)
        assert_equal(tck_f[2], k)

        # test that the result of splrep roundtrips with splev:
        # evaluate the spline on the original `x` points
        yy = splev(x, tck)
        assert_allclose(y, yy, atol=1e-15)

        # ... and also it roundtrips if wrapped in a BSpline
        b = BSpline(*tck)
        assert_allclose(y, b(x), atol=1e-15)

        # test that both "old" and "new" splrep raise for an n-D ``y`` array
        # with n > 1
        y2 = np.c_[y, y]
        assert_raises(Exception, splrep, x, y2)
        assert_raises(Exception, _impl.splrep, x, y2)

Example 94

Project: sfepy
Source File: ioutils.py
View license
def read_sparse_matrix_hdf5(filename, output_format=None):
    import scipy.sparse as sp
    constructors = {'csr' : sp.csr_matrix, 'csc' : sp.csc_matrix}

    fd = pt.open_file(filename, mode='r')
    info = fd.root.info
    data = fd.root.data

    format = dec(info.format.read())
    dtype = dec(info.dtype.read())

    if output_format is None:
        constructor = constructors[format]
    else:
        constructor = constructors[output_format]

    if format in ['csc', 'csr']:
        mtx = constructor((data.data.read(),
                           data.indices.read(), data.indptr.read()),
                          shape=info.shape.read(), dtype=dtype)
    elif format == 'coo':
        mtx = constructor((data.data.read(),
                           nm.c_[data.rows.read(), data.cols.read()].T),
                          shape=info.shape.read(), dtype=dtype)
    else:
        print(format)
        raise ValueError
    fd.close()

    if output_format in ['csc', 'csr']:
        mtx.sort_indices()

    return mtx

Example 95

Project: GPy
Source File: plot_util.py
View license
def x_frame2D(X,plot_limits=None,resolution=None):
    """
    Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
    """
    assert X.shape[1]==2, "x_frame2D is defined for two-dimensional inputs"
    if plot_limits is None:
        xmin, xmax = X.min(0), X.max(0)
        xmin, xmax = xmin-0.075*(xmax-xmin), xmax+0.075*(xmax-xmin)
    elif len(plot_limits) == 2:
        xmin, xmax = plot_limits
        try:
            xmin = xmin[0], xmin[1]
        except:
            # only one limit given, copy over to other lim
            xmin = [plot_limits[0], plot_limits[0]]
            xmax = [plot_limits[1], plot_limits[1]]
    elif len(plot_limits) == 4:
        xmin, xmax = (plot_limits[0], plot_limits[2]), (plot_limits[1], plot_limits[3])
    else:
        raise ValueError("Bad limits for plotting")

    resolution = resolution or 50
    xx, yy = np.mgrid[xmin[0]:xmax[0]:1j*resolution,xmin[1]:xmax[1]:1j*resolution]
    Xnew = np.c_[xx.flat, yy.flat]
    return Xnew, xx, yy, xmin, xmax

Example 96

Project: simpeg
Source File: DC.py
View license
def DCAnalyticSphere(txloc, rxloc, xc, radius, sigma, sigma1, \
                 field_type = "secondary", order=12, halfspace=False):
# def DCSpherePointCurrent(txloc, rxloc, xc, radius, rho, rho1, \
#                  field_type = "secondary", order=12):
    """

        Parameters:

            :param array txloc: A (+) current electrode location (x,y,z)
            :param array xc: x center of depressed sphere
            :param array rxloc: M(+) electrode locations / (Nx3 array, # of electrodes)

            :param float radius: radius (float): radius of the sphere (m)
            :param float rho: resistivity of the background (ohm-m)
            :param float rho1: resistivity of the sphere
            :param string field_type: : "secondary", "total", "primary"
                  (default="secondary")
                  "secondary": secondary potential only due to sphere
                  "primary": primary potential from the point source
                  "total": "secondary"+"primary"
            :param float order: maximum order of Legendre polynomial (default=12)

        Written by Seogi Kang ([email protected])
        Ph.D. Candidate of University of British Columbia, Canada

    """

    Pleg = []
    # Compute Legendre Polynomial
    for i in range(order):
        Pleg.append(special.legendre(i, monic=0))


    rho = 1./sigma
    rho1 = 1./sigma1

    # Center of the sphere should be aligned in txloc in y-direction
    yc = txloc[1]
    xyz = np.c_[rxloc[:,0]-xc, rxloc[:,1]-yc, rxloc[:,2]]
    r = np.sqrt( (xyz**2).sum(axis=1) )

    x0 = abs(txloc[0]-xc)

    costheta = xyz[:,0]/r * (txloc[0]-xc)/x0
    phi = np.zeros_like(r)
    R = (r**2+x0**2.-2.*r*x0*costheta)**0.5
    # primary potential in a whole space
    prim = rho*1./(4*np.pi*R)

    if field_type =="primary":
        return prim

    sphind = r < radius
    out = np.zeros_like(r)
    for n in range(order):
        An, Bn = AnBnfun(n, radius, x0, rho, rho1)
        dumout = An*r[~sphind]**(-n-1.)*Pleg[n](costheta[~sphind])
        out[~sphind] += dumout
        dumin = Bn*r[sphind]**(n)*Pleg[n](costheta[sphind])
        out[sphind] += dumin

    out[~sphind] += prim[~sphind]

    if halfspace:
        scale = 2
    else:
        scale = 1

    if field_type == "secondary":
        return scale*(out-prim)
    elif field_type == "total":
        return scale*out

Example 97

Project: simpeg
Source File: View.py
View license
    def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None):
        if self.dim == 3:
            raise NotImplementedError('This is not yet done!')

        import matplotlib.pyplot as plt
        import matplotlib
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.colors as colors
        import matplotlib.cm as cmx

        if ax is None: ax = plt.subplot(111)
        jet = cm = plt.get_cmap('jet')
        cNorm  = colors.Normalize(
            vmin=I.min() if clim is None else clim[0],
            vmax=I.max() if clim is None else clim[1])

        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
        # ax.set_xlim((self.x0[0], self.h[0].sum()))
        # ax.set_ylim((self.x0[1], self.h[1].sum()))

        Nx = self.r(self.gridN[:,0],'N','N','M')
        Ny = self.r(self.gridN[:,1],'N','N','M')
        cell = self.r(I,'CC','CC','M')

        for ii in range(self.nCx):
            for jj in range(self.nCy):
                I = [ii,ii+1,ii+1,ii]
                J = [jj,jj,jj+1,jj+1]
                ax.add_patch(plt.Polygon(np.c_[Nx[I,J],Ny[I,J]], facecolor=scalarMap.to_rgba(cell[ii,jj]), edgecolor='k' if grid else 'none'))

        scalarMap._A = []  # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        if showIt:
            plt.show()
        return [scalarMap]

Example 98

Project: simpeg
Source File: test_innerProduct.py
View license
    def getError(self):

        call = lambda fun, xyz: fun(xyz[:, 0], xyz[:, 1], xyz[:, 2])

        ex = lambda x, y, z: x**2+y*z
        ey = lambda x, y, z: (z**2)*x+y*z
        ez = lambda x, y, z: y**2+x*z

        sigma1 = lambda x, y, z: x*y+1
        sigma2 = lambda x, y, z: x*z+2
        sigma3 = lambda x, y, z: 3+z*y
        sigma4 = lambda x, y, z: 0.1*x*y*z
        sigma5 = lambda x, y, z: 0.2*x*y
        sigma6 = lambda x, y, z: 0.1*z

        Gc = self.M.gridCC
        if self.sigmaTest == 1:
            sigma = np.c_[call(sigma1, Gc)]
            analytic = 647./360  # Found using sympy.
        elif self.sigmaTest == 3:
            sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)]
            analytic = 37./12  # Found using sympy.
        elif self.sigmaTest == 6:
            sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc),
                          call(sigma4, Gc), call(sigma5, Gc), call(sigma6, Gc)]
            analytic = 69881./21600  # Found using sympy.

        if self.location == 'edges':
            cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)]
            Ec = np.vstack((cart(self.M.gridEx),
                            cart(self.M.gridEy),
                            cart(self.M.gridEz)))
            E = self.M.projectEdgeVector(Ec)

            if self.invProp:
                A = self.M.getEdgeInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getEdgeInnerProduct(sigma)
            numeric = E.T.dot(A.dot(E))
        elif self.location == 'faces':
            cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)]
            Fc = np.vstack((cart(self.M.gridFx),
                            cart(self.M.gridFy),
                            cart(self.M.gridFz)))
            F = self.M.projectFaceVector(Fc)

            if self.invProp:
                A = self.M.getFaceInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getFaceInnerProduct(sigma)
            numeric = F.T.dot(A.dot(F))

        err = np.abs(numeric - analytic)
        return err

Example 99

Project: simpeg
Source File: test_innerProduct.py
View license
    def getError(self):

        z = 5  # Because 5 is just such a great number.

        call = lambda fun, xy: fun(xy[:, 0], xy[:, 1])

        ex = lambda x, y: x**2+y*z
        ey = lambda x, y: (z**2)*x+y*z

        sigma1 = lambda x, y: x*y+1
        sigma2 = lambda x, y: x*z+2
        sigma3 = lambda x, y: 3+z*y

        Gc = self.M.gridCC
        if self.sigmaTest == 1:
            sigma = np.c_[call(sigma1, Gc)]
            analytic = 144877./360  # Found using sympy. z=5
        elif self.sigmaTest == 2:
            sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc)]
            analytic = 189959./120  # Found using sympy. z=5
        elif self.sigmaTest == 3:
            sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)]
            analytic = 781427./360  # Found using sympy. z=5

        if self.location == 'edges':
            cart = lambda g: np.c_[call(ex, g), call(ey, g)]
            Ec = np.vstack((cart(self.M.gridEx),
                            cart(self.M.gridEy)))
            E = self.M.projectEdgeVector(Ec)
            if self.invProp:
                A = self.M.getEdgeInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getEdgeInnerProduct(sigma)
            numeric = E.T.dot(A.dot(E))
        elif self.location == 'faces':
            cart = lambda g: np.c_[call(ex, g), call(ey, g)]
            Fc = np.vstack((cart(self.M.gridFx),
                            cart(self.M.gridFy)))
            F = self.M.projectFaceVector(Fc)

            if self.invProp:
                A = self.M.getFaceInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getFaceInnerProduct(sigma)
            numeric = F.T.dot(A.dot(F))

        err = np.abs(numeric - analytic)
        return err

Example 100

Project: simpeg
Source File: test_TreeOperators.py
View license
    def getError(self):

        call = lambda fun, xyz: fun(xyz[:, 0], xyz[:, 1], xyz[:, 2])

        ex = lambda x, y, z: x**2+y*z
        ey = lambda x, y, z: (z**2)*x+y*z
        ez = lambda x, y, z: y**2+x*z

        sigma1 = lambda x, y, z: x*y+1
        sigma2 = lambda x, y, z: x*z+2
        sigma3 = lambda x, y, z: 3+z*y
        sigma4 = lambda x, y, z: 0.1*x*y*z
        sigma5 = lambda x, y, z: 0.2*x*y
        sigma6 = lambda x, y, z: 0.1*z

        Gc = self.M.gridCC
        if self.sigmaTest == 1:
            sigma = np.c_[call(sigma1, Gc)]
            analytic = 647./360  # Found using sympy.
        elif self.sigmaTest == 3:
            sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)]
            analytic = 37./12  # Found using sympy.
        elif self.sigmaTest == 6:
            sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc),
                          call(sigma4, Gc), call(sigma5, Gc), call(sigma6, Gc)]
            analytic = 69881./21600  # Found using sympy.

        if self.location == 'edges':
            cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)]
            Ec = np.vstack((cart(self.M.gridEx),
                            cart(self.M.gridEy),
                            cart(self.M.gridEz)))
            E = self.M.projectEdgeVector(Ec)

            if self.invProp:
                A = self.M.getEdgeInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getEdgeInnerProduct(sigma)
            numeric = E.T.dot(A.dot(E))
        elif self.location == 'faces':
            cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)]
            Fc = np.vstack((cart(self.M.gridFx),
                            cart(self.M.gridFy),
                            cart(self.M.gridFz)))
            F = self.M.projectFaceVector(Fc)

            if self.invProp:
                A = self.M.getFaceInnerProduct(Utils.invPropertyTensor(self.M, sigma), invProp=True)
            else:
                A = self.M.getFaceInnerProduct(sigma)
            numeric = F.T.dot(A.dot(F))

        err = np.abs(numeric - analytic)
        return err