Beispiel #1
0
 def test_absolute_threshold(self):
     image = np.zeros((5, 5), dtype=np.uint8)
     image[1, 1] = 10
     image[3, 3] = 20
     peaks = peak.peak_local_max(image, min_distance=1, threshold_abs=10)
     assert len(peaks) == 1
     assert_close(peaks, [(3, 3)])
Beispiel #2
0
def test_rgb():
    image = np.ones((1, 3))
    label = np.arange(3).reshape(1, -1)
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    # Set alphas just in case the defaults change
    rgb = label2rgb(label, image=image, colors=colors, alpha=1, image_alpha=1)
    assert_close(rgb, [colors])
def test_pad_input():
    """Test `match_template` when `pad_input=True`.

    This test places two full templates (one with values lower than the image
    mean, the other higher) and two half templates, which are on the edges of
    the image. The two full templates should score the top (positive and
    negative) matches and the centers of the half templates should score 2nd.
    """
    # Float prefactors ensure that image range is between 0 and 1
    template = 0.5 * diamond(2)
    image = 0.5 * np.ones((9, 19))
    mid = slice(2, 7)
    image[mid, :3] -= template[:, -3:]  # half min template centered at 0
    image[mid, 4:9] += template         # full max template centered at 6
    image[mid, -9:-4] -= template       # full min template centered at 12
    image[mid, -3:] += template[:, :3]  # half max template centered at 18

    result = match_template(image, template, pad_input=True)

    # get the max and min results.
    sorted_result = np.argsort(result.flat)
    i, j = np.unravel_index(sorted_result[:2], result.shape)
    assert_close(j, (12, 0))
    i, j = np.unravel_index(sorted_result[-2:], result.shape)
    assert_close(j, (18, 6))
Beispiel #4
0
 def test_absolute_threshold(self):
     image = np.zeros((5, 5), dtype=np.uint8)
     image[1, 1] = 10
     image[3, 3] = 20
     peaks = peak.peak_local_max(image, min_distance=1, threshold_abs=10)
     assert len(peaks) == 1
     assert_close(peaks, [(3, 3)])
Beispiel #5
0
def test_ohmi_envelope(engine, lattices):
    py_lattice, ml_lattice, _ = lattices
    fields = [('beam66', 'r66'), ('beam44', 'r44'), ('emit66', 'emitXYZ'),
              ('emit44', 'emitXY')]
    nelems = len(py_lattice)
    refpts = range(nelems + 1)

    # Python call
    py_lattice = py_lattice.radiation_on(copy=True)
    py_emit0, py_beamdata, py_emit = py_lattice.ohmi_envelope(refpts)
    # Matlab call
    ml_emit = engine.pyproxy('atx', ml_lattice, 0.0, _ml_refs(refpts, nelems))
    ml_emit0, ml_params = engine.pyproxy('atx',
                                         ml_lattice,
                                         0.0,
                                         _ml_refs(0, nelems),
                                         nargout=2)
    revolution_period = get_s_pos(py_lattice, nelems) / speed_of_light
    damping_times = revolution_period / py_beamdata.damping_rates
    # Comparison
    assert_close(damping_times,
                 _py_data(ml_params['dampingtime']),
                 atol=1.e-6,
                 rtol=1.e-3)
    assert_close(py_beamdata.mode_emittances,
                 _py_data(ml_emit0['modemit']),
                 atol=1.e-20,
                 rtol=2.e-3)
    _compare_physdata(numpy.expand_dims(py_emit0, 0), ml_emit0, fields)
    _compare_physdata(py_emit, ml_emit, fields)
def test_rgb():
    image = np.ones((1, 3))
    label = np.arange(3).reshape(1, -1)
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    # Set alphas just in case the defaults change
    rgb = label2rgb(label, image=image, colors=colors, alpha=1, image_alpha=1)
    assert_close(rgb, [colors])
Beispiel #7
0
def test_find_sync_orbit(dba_lattice):
    expected = numpy.array([[1.030844e-5, 1.390795e-5, -2.439041e-30,
                             4.701621e-30, 1.265181e-5, 3.749859e-6],
                            [3.86388e-8, 1.163782e-7, -9.671192e-30,
                             3.567819e-30, 1.265181e-5, 7.5e-6]])
    _, all_points = physics.find_sync_orbit(dba_lattice, DP, [49, 99])
    assert_close(all_points, expected, rtol=1e-5, atol=1e-7)
Beispiel #8
0
def test_quantdiff(hmba_lattice):
    hmba_lattice = hmba_lattice.radiation_on(quadrupole_pass='******', copy=True)
    dmat = physics.radiation.quantdiffmat(hmba_lattice)
    lmat = physics.radiation._lmat(dmat)
    assert_close(lmat,
                 [[1.45502934e-07, 0.00000000e+00, 0.00000000e+00,
                   0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
                  [2.40963396e-09, 1.79735260e-08, 0.00000000e+00,
                   0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
                  [0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                   0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
                  [0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
                   0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
                  [3.72874832e-07, 2.37718999e-07, 0.00000000e+00,
                   0.00000000e+00, 5.78954180e-06, 0.00000000e+00],
                  [-1.72955964e-09, -5.42857509e-11, 0.00000000e+00,
                   0.00000000e+00, 6.52385922e-09, 3.25943528e-09]],
                 rtol=1e-4, atol=1e-20)
    assert_close(dmat,
        [[2.11711037e-14, 3.50608810e-16, 0.00000000e+00,
          0.00000000e+00, 5.42543819e-14, -2.51656002e-16],
         [3.50608810e-16, 3.28853971e-16, -0.00000000e+00,
          0.00000000e+00, 5.17114045e-15, -5.14331200e-18],
         [0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
          0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
         [0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
          0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
         [5.42543819e-14, 5.17114045e-15, 0.00000000e+00,
          0.00000000e+00, 3.37143402e-11, 3.71123417e-14],
         [-2.51656002e-16, -5.14331200e-18, 0.00000000e+00,
          0.00000000e+00, 3.71123417e-14, 5.61789810e-17]],
                 rtol=1e-5, atol=1e-20)
Beispiel #9
0
def test_linear_analysis(engine, lattices, dp):
    py_lattice, ml_lattice, _ = lattices
    nelems = len(py_lattice)
    fields = [('SPos', 's_pos'),
              ('ClosedOrbit', 'closed_orbit'),
              ('Dispersion', 'dispersion'),
              ('alpha', 'alpha'), ('beta', 'beta'),
              ('mu', 'mu'), ('M44', 'm44'),
              ('A', 'A'), ('B', 'B'), ('C', 'C'),
              ('gamma', 'gamma')]
    refpts = range(nelems + 1)
    py_data0, py_tune, py_chrom, py_data = physics.linopt(py_lattice, dp,
                                                          refpts, True,
                                                          ddp=1.E-6)
    # Matlab call
    ml_data, ml_tune, ml_chrom = engine.pyproxy('atlinopt', ml_lattice, dp,
                                                _ml_refs(refpts, nelems),
                                                nargout=3)
    ml_data0 = engine.pyproxy('atlinopt', ml_lattice, dp,
                              _ml_refs(nelems, nelems), nargout=3)[0]
    # Comparison
    assert_close(py_tune, _py_data(ml_tune), atol=2.e-6, rtol=0)    #1e-8
    assert_close(py_chrom, _py_data(ml_chrom), atol=2.e-3, rtol=0)
    _compare_physdata(numpy.expand_dims(py_data0, 0), ml_data0, fields,
                      rtol=1e-8)
    _compare_physdata(py_data, ml_data, fields, rtol=1e-8)
def test_image_alpha():
    image = np.random.uniform(size=(1, 3))
    label = np.arange(3).reshape(1, -1)
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    # If we set `image_alpha = 0`, then rgb should match label colors exactly.
    rgb = label2rgb(label, image=image, colors=colors, alpha=1, image_alpha=0)
    assert_close(rgb, [colors])
Beispiel #11
0
def test_find_m44_no_refpts(dba_lattice):
    m44 = physics.find_m44(dba_lattice, dp=DP)[0]
    expected = numpy.array([[-0.66380, 2.23415, 0., 0.],
                            [-0.25037, -0.66380, 0., 0.],
                            [-1.45698e-31, -1.15008e-30, -0.99922, 0.26217],
                            [6.57748e-33, 8.75482e-32, -5.9497e-3, -0.99922]])
    assert_close(m44, expected, rtol=1e-5, atol=1e-7)
Beispiel #12
0
def test_relative_threshold():
    image = np.zeros((5, 5), dtype=np.uint8)
    image[1, 1] = 10
    image[3, 3] = 20
    peaks = peak.peak_local_max(image, min_distance=1, threshold_rel=0.5)
    assert len(peaks) == 1
    assert_close(peaks, [(3, 3)])
Beispiel #13
0
def test_6d_analysis(engine, lattices):
    """Compare linopt6 in 6D"""
    py_lattice, ml_lattice, _ = lattices
    fields = [('SPos', 's_pos'), ('ClosedOrbit', 'closed_orbit'), ('M', 'M'),
              ('A', 'A'), ('Dispersion', 'dispersion'), ('alpha', 'alpha'),
              ('beta', 'beta'), ('mu', 'mu'), ('W', 'W')]
    ml_lattice = engine.pyproxy('atradon', ml_lattice)
    py_lattice = py_lattice.radiation_on(copy=True)
    pypts = range(10)
    mlpts = _ml_refs(py_lattice, pypts)

    # python call
    py_data0, py_ringdata, py_data = linopt6(py_lattice,
                                             refpts=pypts,
                                             get_w=True)
    # Matlab call
    ml_ringdata, ml_data = engine.pyproxy('atlinopt6',
                                          ml_lattice,
                                          mlpts,
                                          'get_w',
                                          nargout=2)
    # Comparison
    assert_close(py_ringdata.tune,
                 _py_data(ml_ringdata['tune']),
                 atol=1.e-12,
                 rtol=0)
    assert_close(py_ringdata.chromaticity,
                 _py_data(ml_ringdata['chromaticity']),
                 atol=1.e-5,
                 rtol=0)

    _compare_6d(py_data, ml_data, fields, atol=1.e-6, rtol=1e-8)
def test_pad_input():
    """Test `match_template` when `pad_input=True`.

    This test places two full templates (one with values lower than the image
    mean, the other higher) and two half templates, which are on the edges of
    the image. The two full templates should score the top (positive and
    negative) matches and the centers of the half templates should score 2nd.
    """
    # Float prefactors ensure that image range is between 0 and 1
    template = 0.5 * diamond(2)
    image = 0.5 * np.ones((9, 19))
    mid = slice(2, 7)
    image[mid, :3] -= template[:, -3:]  # half min template centered at 0
    image[mid, 4:9] += template  # full max template centered at 6
    image[mid, -9:-4] -= template  # full min template centered at 12
    image[mid, -3:] += template[:, :3]  # half max template centered at 18

    result = match_template(image, template, pad_input=True)

    # get the max and min results.
    sorted_result = np.argsort(result.flat)
    i, j = np.unravel_index(sorted_result[:2], result.shape)
    assert_close(j, (12, 0))
    i, j = np.unravel_index(sorted_result[-2:], result.shape)
    assert_close(j, (18, 6))
Beispiel #15
0
def test_image_alpha():
    image = np.random.uniform(size=(1, 3))
    label = np.arange(3).reshape(1, -1)
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    # If we set `image_alpha = 0`, then rgb should match label colors exactly.
    rgb = label2rgb(label, image=image, colors=colors, alpha=1, image_alpha=0)
    assert_close(rgb, [colors])
Beispiel #16
0
def test_relative_threshold():
    image = np.zeros((5, 5), dtype=np.uint8)
    image[1, 1] = 10
    image[3, 3] = 20
    peaks = peak.peak_local_max(image, min_distance=1, threshold_rel=0.5)
    assert len(peaks) == 1
    assert_close(peaks, [(3, 3)])
Beispiel #17
0
def _compare_physdata(py_data, ml_data, fields, atol=12, rtol=1.e-7):
    for (ml_key, py_key) in fields:
        ml_val = _py_data(ml_data[ml_key])
        if py_key == 'closed_orbit':
            py_val = numpy.squeeze(py_data[py_key][:, :4])
        else:
            py_val = numpy.squeeze(py_data[py_key])
        assert_close(py_val, ml_val, atol=atol, rtol=rtol)
Beispiel #18
0
def test_roberts_diagonal1():
    """Roberts' on an edge should be a one diagonal"""
    image = np.tri(10, 10, 0)
    expected = ~(np.tri(10, 10, -1).astype(bool) | \
                 np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected,None)
    result = F.roberts(image).astype(bool)
    assert_close(result,expected)
Beispiel #19
0
def test_quantdiff(engine, lattices):
    py_lattice, ml_lattice, radindex = lattices
    # Python call
    dmat = physics.radiation.quantdiffmat(py_lattice)
    # Matlab call
    dmat_ml = engine.pyproxy('quantumDiff', ml_lattice, radindex)
    # Comparison
    assert_close(dmat, dmat_ml, rtol=1.0e-8, atol=1.0e-18)
Beispiel #20
0
def test_find_m44_returns_same_answer_as_matlab(dba_lattice, refpts):
    m44, mstack = physics.find_m44(dba_lattice, dp=DP, refpts=refpts)
    assert_close(m44, M44_MATLAB, rtol=1e-5, atol=1e-7)
    assert mstack.shape == (len(refpts), 4, 4)
    m44, mstack = physics.find_m44(dba_lattice, dp=DP, refpts=refpts,
                                   full=True)
    assert_close(m44, M44_MATLAB, rtol=1e-5, atol=1e-7)
    assert mstack.shape == (len(refpts), 4, 4)
Beispiel #21
0
def test_roberts_diagonal1():
    """Roberts' filter on a diagonal edge should be a diagonal line."""
    image = np.tri(10, 10, 0)
    expected = ~(np.tri(10, 10, -1).astype(bool)
                 | np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected, None)
    result = filters.roberts(image).astype(bool)
    assert_close(result, expected)
Beispiel #22
0
def test_roberts_diagonal2():
    """Roberts' filter on a diagonal edge should be a diagonal line."""
    image = np.rot90(np.tri(10, 10, 0), 3)
    expected = ~np.rot90(np.tri(10, 10, -1).astype(bool) |
                         np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected, None)
    result = F.roberts(image).astype(bool)
    assert_close(result, expected)
Beispiel #23
0
def test_zip_0_gate(rate):
    # if gate is 0 ZIP is Poisson
    zip_ = ZeroInflatedPoisson(torch.zeros(1), torch.tensor(rate))
    pois = Poisson(torch.tensor(rate))
    s = pois.sample((20, ))
    zip_prob = zip_.log_prob(s)
    pois_prob = pois.log_prob(s)
    assert_close(zip_prob, pois_prob, atol=1e-06)
Beispiel #24
0
def test_find_orbit4_with_two_refpts_with_and_without_guess(dba_lattice):
    expected = numpy.array(
        [[8.148212e-6, 1.0993354e-5, 0, 0, DP, 2.963929e-6],
         [3.0422808e-8, 9.1635269e-8, 0, 0, DP, 5.9280346e-6]])
    _, all_points = physics.find_orbit4(dba_lattice, DP, [49, 99])
    assert_close(all_points, expected, atol=1e-12)
    _, all_points = physics.find_orbit4(dba_lattice, DP, [49, 99],
                                        numpy.array([0., 0., 0., 0., DP, 0.]))
    assert_close(all_points, expected, atol=1e-12)
Beispiel #25
0
def test_linopt_line(hmba_lattice, refpts):
    refpts.append(len(hmba_lattice))
    l0, q, qp, ld = at.linopt(hmba_lattice, refpts=refpts)
    lt0, qt, qpt, ltd = at.linopt(hmba_lattice, refpts=refpts, twiss_in=l0)
    assert_close(ld['beta'], ltd['beta'], rtol=1e-12)
    assert_close(ld['s_pos'], ltd['s_pos'], rtol=1e-12)
    assert_close(ld['closed_orbit'], ltd['closed_orbit'], rtol=1e-12)
    assert_close(ld['alpha'], ltd['alpha'], rtol=1e-12)
    assert_close(ld['dispersion'], ltd['dispersion'], rtol=1e-7, atol=1e-12)
def test_bg_and_color_cycle():
    image = np.zeros((1, 10))  # dummy image
    label = np.arange(10).reshape(1, -1)
    colors = [(1, 0, 0), (0, 0, 1)]
    bg_color = (0, 0, 0)
    rgb = label2rgb(label, image=image, bg_label=0, bg_color=bg_color,
                    colors=colors, alpha=1)
    assert_close(rgb[0, 0], bg_color)
    for pixel, color in zip(rgb[0, 1:], itertools.cycle(colors)):
        assert_close(pixel, color)
def test_label_consistency():
    """Assert that the same labels map to the same colors."""
    label_1 = np.arange(5).reshape(1, -1)
    label_2 = np.array([0, 1])
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1)]
    # Set alphas just in case the defaults change
    rgb_1 = label2rgb(label_1, colors=colors)
    rgb_2 = label2rgb(label_2, colors=colors)
    for label_id in label_2.flat:
        assert_close(rgb_1[label_1 == label_id], rgb_2[label_2 == label_id])
Beispiel #28
0
def test_label_consistency():
    """Assert that the same labels map to the same colors."""
    label_1 = np.arange(5).reshape(1, -1)
    label_2 = np.array([0, 1])
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1)]
    # Set alphas just in case the defaults change
    rgb_1 = label2rgb(label_1, colors=colors)
    rgb_2 = label2rgb(label_2, colors=colors)
    for label_id in label_2.flat:
        assert_close(rgb_1[label_1 == label_id], rgb_2[label_2 == label_id])
Beispiel #29
0
def test_zip_mean_variance(gate, rate):
    num_samples = 1000000
    zip_ = ZeroInflatedPoisson(torch.tensor(gate), torch.tensor(rate))
    s = zip_.sample((num_samples, ))
    expected_mean = zip_.mean
    estimated_mean = s.mean()
    expected_std = zip_.stddev
    estimated_std = s.std()
    assert_close(expected_mean, estimated_mean, atol=1e-02)
    assert_close(expected_std, estimated_std, atol=1e-02)
Beispiel #30
0
def test_bg_and_color_cycle():
    image = np.zeros((1, 10))  # dummy image
    label = np.arange(10).reshape(1, -1)
    colors = [(1, 0, 0), (0, 0, 1)]
    bg_color = (0, 0, 0)
    rgb = label2rgb(label, image=image, bg_label=0, bg_color=bg_color,
                    colors=colors, alpha=1)
    assert_close(rgb[0, 0], bg_color)
    for pixel, color in zip(rgb[0, 1:], itertools.cycle(colors)):
        assert_close(pixel, color)
Beispiel #31
0
def test_zinb_0_gate(total_count, probs):
    # if gate is 0 ZINB is NegativeBinomial
    zinb_ = ZeroInflatedNegativeBinomial(torch.zeros(1),
                                         total_count=torch.tensor(total_count),
                                         probs=torch.tensor(probs))
    neg_bin = NegativeBinomial(torch.tensor(total_count),
                               probs=torch.tensor(probs))
    s = neg_bin.sample((20, ))
    zinb_prob = zinb_.log_prob(s)
    neg_bin_prob = neg_bin.log_prob(s)
    assert_close(zinb_prob, neg_bin_prob, atol=1e-06)
Beispiel #32
0
def test_roberts_diagonal2():
    """Roberts' on an edge should be a other diagonal"""
    diagonal = np.tri(10, 10, 0,dtype=int)
    rev_diagonal = np.rot90(diagonal.transpose(),1)

    image = (rev_diagonal > 0).astype(float)
    expected = ~np.rot90((np.tri(10, 10, -1).astype(bool) | \
                np.tri(10, 10, -2).astype(bool).transpose()),1)
    expected = _mask_filter_result(expected,None)
    result = F.roberts(image).astype(bool)
    assert_close(result,expected)
Beispiel #33
0
def test_find_orbit6_produces_same_result_with_keep_lattice_True(hmba_lattice):
    hmba_lattice = hmba_lattice.radiation_on(quadrupole_pass=None, copy=True)
    orbit0, _ = physics.find_orbit6(hmba_lattice)
    # Technicality - the default arguments to find_orbit6 mean that
    # keep_lattice argument is always false.
    orbit1, _ = physics.find_orbit6(hmba_lattice, keep_lattice=True)
    # With INTEGRAL keep_lattice does take effect.
    orbit2, _ = physics.find_orbit6(
        hmba_lattice, keep_lattice=True, method=physics.ELossMethod.INTEGRAL
    )
    assert_close(orbit0, orbit1, rtol=0, atol=1e-12)
    assert_close(orbit0, orbit2, rtol=0, atol=1e-12)
Beispiel #34
0
def test_find_elem_m66(hmba_lattice, index):
    m66 = physics.find_elem_m66(hmba_lattice[index])
    if index == 19:
        expected = numpy.array([[1.0386, 0.180911, 0., 0., 0., 0.],
                                [0.434959, 1.0386, 0., 0., 0., 0.],
                                [0., 0., 0.961891, 0.176344, 0., 0.],
                                [0., 0., -0.423978, 0.961891, 0., 0.],
                                [0., 0., 0., 0., 1., 0.],
                                [0., 0., 0., 0., 0., 1.]])
    else:
        expected = numpy.eye(6)
    assert_close(m66, expected, rtol=1e-5, atol=1e-7)
Beispiel #35
0
def test_atpass(engine, lattices):
    py_lattice, ml_lattice, _ = lattices
    xy_step = 1.e-8
    scaling = [xy_step, xy_step, xy_step, xy_step, xy_step, xy_step]

    ml_rin = engine.diag(matlab.double(scaling))
    ml_rout = engine.atpass(ml_lattice, ml_rin, 1, 1)

    py_rin = numpy.asfortranarray(numpy.diag(scaling))
    at.atpass(py_lattice, py_rin, 1)

    assert_close(py_rin, ml_rout, rtol=0, atol=1.e-30)
Beispiel #36
0
def test_linopt_matching(test_ring):
    # Define the location of constraint
    sf = at.get_refpts(test_ring, 'SF*')[1::2]
    center = at.get_refpts(test_ring, 'CellCenter')

    # Define the variables
    names = ['QF1*', 'QD2*', 'QD3*', 'QF4*', 'QD5*', 'QF6*', 'QF8*']
    bounds = [[0, 5], [-5, 0], [-5, 0], [0, 5], [-5, 0], [0, 5], [0, 5]]
    variables = [
        at.ElementVariable(at.get_refpts(test_ring, nm),
                           'PolynomB',
                           index=1,
                           name=nm) for nm, bnd in zip(names, bounds)
    ]

    # Define an evaluation function for the phase advance (both planes)
    # noinspection PyUnusedLocal
    def mu_diff(lindata, tune, chrom):
        delta_mu = (lindata[1].mu - lindata[0].mu) / (2 * np.pi)
        return delta_mu % 1.0

    # Define the constraints
    cst1 = at.LinoptConstraints(test_ring)
    cst1.add('tunes', [0.38, 0.85], name='tunes')
    # Start of the ring
    cst1.add('alpha', [0.0, 0.0], refpts=0, name='alpha_0')
    cst1.add('dispersion', 0.0, refpts=0, index=1, name="eta'_0")
    # Center of the cell
    cst1.add('beta', 4.69999257, refpts=center, index=1, name='betay_c')
    cst1.add('alpha', [0.0, 0.0], refpts=center, name='alpha_c')
    cst1.add('dispersion', 0.0, refpts=center, index=1, name="eta'_c")
    # Focusing sextupoles
    cst1.add('beta', [5.40000677, 5.39998124],
             refpts=sf,
             index=1,
             name='betay_sf')
    cst1.add('alpha', [0.68000392, -0.67999686],
             refpts=sf,
             index=1,
             name='alphay_sf')
    cst1.add('dispersion', [0.08820002, 0.08819999],
             refpts=sf,
             index=0,
             name="eta_sf")
    # Phase advance
    cst1.add(mu_diff, [0.49721338, 0.48228011], refpts=sf, name='delta phi')

    # Perform the fit
    newring = at.match(test_ring, variables, (cst1, ), method='lm', verbose=1)

    # check the residuals
    assert_close(cst1.evaluate(newring), 0, rtol=0.0, atol=1e-4)
Beispiel #37
0
def test_linepass(engine, lattices):
    py_lattice, ml_lattice, _ = lattices
    xy_step = 1.e-8
    scaling = [xy_step, xy_step, xy_step, xy_step, xy_step, xy_step]

    ml_rin = engine.diag(matlab.double(scaling))
    ml_rout = numpy.array(engine.linepass(ml_lattice, ml_rin))

    py_rin = numpy.asfortranarray(numpy.diag(scaling))
    py_rout = numpy.squeeze(at.lattice_pass(py_lattice, py_rin,
                                            refpts=len(py_lattice)))

    assert_close(py_rout, ml_rout, rtol=0, atol=1.e-30)
Beispiel #38
0
def test_two_image_peaks():
    """Test reconstruction with two peak pixels isolated by the mask"""
    image = np.array([[1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 1, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1]])

    mask = np.array([[4, 4, 4, 1, 1, 1, 1, 1], [4, 4, 4, 1, 1, 1, 1, 1],
                     [4, 4, 4, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 4, 4, 4],
                     [1, 1, 1, 1, 1, 4, 4, 4], [1, 1, 1, 1, 1, 4, 4, 4]])

    expected = np.array([[2, 2, 2, 1, 1, 1, 1, 1], [2, 2, 2, 1, 1, 1, 1, 1],
                         [2, 2, 2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3],
                         [1, 1, 1, 1, 1, 3, 3, 3], [1, 1, 1, 1, 1, 3, 3, 3]])
    assert_close(reconstruction(image, mask), expected)
Beispiel #39
0
def test_linopt6(lattice, dp):
    """Compare the results of linopt and linopt6 in 4d"""
    refpts = range(21)
    lindata0, tune, chrom, lindata = linopt(lattice,
                                            dp,
                                            refpts,
                                            get_chrom=True)
    ld0, rd, ld = linopt6(lattice, refpts, dp=dp, get_chrom=True)
    assert_close(tune, rd.tune, rtol=1e-8)
    assert_close(chrom, rd.chromaticity, rtol=1e-8)

    assert_close(ld.beta, lindata.beta, rtol=1e-6)
    assert_close(ld.alpha, lindata.alpha, atol=1e-6, rtol=1e-6)
    assert_close(ld.dispersion, lindata.dispersion, atol=1e-9)
Beispiel #40
0
def test_line_functions(r=1.5, offset=3., y0=3):
    x = np.array([1, 2, 3]) + offset
    y = y0 * x**r
    assert_close(loglog.line_y(x[1], y[1], x[0], slope=r), y[0])
    assert_close(loglog.line_y(x[1], y[1], x[2], slope=r), y[2])
    assert_close(loglog.line_x(x[1], y[1], y[0], slope=r), x[0])
    assert_close(loglog.line_x(x[1], y[1], y[2], slope=r), x[2])
Beispiel #41
0
def test_vertical_mask_line(grad_func):
    """Vertical edge filters mask pixels surrounding input mask."""
    _, hgrad = np.mgrid[:1:11j, :1:11j]  # horizontal gradient with spacing 0.1
    hgrad[:, 5] = 1  # bad vertical line

    mask = np.ones_like(hgrad)
    mask[:, 5] = 0  # mask bad line

    expected = np.zeros_like(hgrad)
    expected[1:-1, 1:-1] = 0.2  # constant gradient for most of image,
    expected[1:-1, 4:7] = 0  # but line and neighbors masked

    result = grad_func(hgrad, mask)
    assert_close(result, expected)
Beispiel #42
0
def test_ragged_arrays_roundtrip():
    x = [(1, 2, 3), (4, 5, 6, 7)]
    y = [(1, 2), (3, 4, 5), (6, 7)]
    fname = 'temp_array_lists_test_data.npz'

    data_dict = fileio.save_ragged_arrays(fname, x=x, y=y)
    try:
        data_dict = fileio.load_ragged_arrays(fname, ('x', 'y'))
    finally:
        os.remove(fname)

    for dxi, xi in zip(data_dict['x'], x):
        assert_close(dxi, xi)
    for dyi, yi in zip(data_dict['y'], y):
        assert_close(dyi, yi)
def test_alpha():
    image = np.random.uniform(size=(3, 3))
    label = np.random.randint(0, 9, size=(3, 3))
    # If we set `alpha = 0`, then rgb should match image exactly.
    rgb = label2rgb(label, image=image, alpha=0, image_alpha=1)
    assert_close(rgb[..., 0], image)
    assert_close(rgb[..., 1], image)
    assert_close(rgb[..., 2], image)
def test_two_image_peaks():
    """Test reconstruction with two peak pixels isolated by the mask"""
    image = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 2, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 1, 1, 1],
                      [1, 1, 1, 1, 1, 1, 3, 1],
                      [1, 1, 1, 1, 1, 1, 1, 1]])

    mask = np.array([[4, 4, 4, 1, 1, 1, 1, 1],
                     [4, 4, 4, 1, 1, 1, 1, 1],
                     [4, 4, 4, 1, 1, 1, 1, 1],
                     [1, 1, 1, 1, 1, 4, 4, 4],
                     [1, 1, 1, 1, 1, 4, 4, 4],
                     [1, 1, 1, 1, 1, 4, 4, 4]])

    expected = np.array([[2, 2, 2, 1, 1, 1, 1, 1],
                         [2, 2, 2, 1, 1, 1, 1, 1],
                         [2, 2, 2, 1, 1, 1, 1, 1],
                         [1, 1, 1, 1, 1, 3, 3, 3],
                         [1, 1, 1, 1, 1, 3, 3, 3],
                         [1, 1, 1, 1, 1, 3, 3, 3]])
    assert_close(reconstruction(image, mask), expected)
def test_one_image_peak():
    """Test reconstruction with one peak pixel"""
    image = np.ones((5, 5))
    image[2, 2] = 2
    mask = np.ones((5, 5)) * 3
    assert_close(reconstruction(image, mask), 2)
def test_image_less_than_mask():
    """Test reconstruction where the image is uniform and less than mask"""
    image = np.ones((5, 5))
    mask = np.ones((5, 5)) * 2
    assert_close(reconstruction(image, mask), 1)
def test_image_equals_mask():
    """Test reconstruction where the image and mask are the same"""
    assert_close(reconstruction(np.ones((7, 5)), np.ones((7, 5))), 1)
def test_zeros():
    """Test reconstruction with image and mask of zeros"""
    assert_close(reconstruction(np.zeros((5, 7)), np.zeros((5, 7))), 0)
def test_no_input_image():
    label = np.arange(3).reshape(1, -1)
    colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    rgb = label2rgb(label, colors=colors)
    assert_close(rgb, [colors])
def test_zero_image_one_mask():
    """Test reconstruction with an image of all zeros and a mask that's not"""
    result = reconstruction(np.zeros((10, 10)), np.ones((10, 10)))
    assert_close(result, 0)
def test_rescale_stretch():
    image = np.array([51, 102, 153], dtype=np.uint8)
    out = exposure.rescale_intensity(image)
    assert out.dtype == np.uint8
    assert_close(out, [0, 127, 255])
def test_rescale_uint14_limits():
    image = np.array([0, uint16_max], dtype=np.uint16)
    out = exposure.rescale_intensity(image, out_range='uint14')
    assert_close(out, [0, uint14_max])
def test_nonconsecutive():
    labels = np.array([0, 2, 4, 0])
    colors=[(1, 0, 0), (0, 0, 1)]
    rout = np.array([(1., 0., 0.), (0., 0., 1.), (1., 0., 0.), (1., 0., 0.)])
    assert_close(rout, label2rgb(labels, colors=colors, alpha=1, image_alpha=1))
def test_rescale_named_out_range():
    image = np.array([0, uint16_max], dtype=np.uint16)
    out = exposure.rescale_intensity(image, out_range='uint10')
    assert_close(out, [0, uint10_max])
def test_rescale_out_range():
    image = np.array([-10, 0, 10], dtype=np.int8)
    out = exposure.rescale_intensity(image, out_range=(0, 127))
    assert out.dtype == np.int8
    assert_close(out, [0, 63, 127])
def test_rescale_in_range_clip():
    image = np.array([51., 102., 153.])
    out = exposure.rescale_intensity(image, in_range=(0, 102))
    assert_close(out, [0.5, 1, 1])
def test_rescale_in_range():
    image = np.array([51., 102., 153.])
    out = exposure.rescale_intensity(image, in_range=(0, 255))
    assert_close(out, [0.2, 0.4, 0.6])
def test_rescale_shrink():
    image = np.array([51., 102., 153.])
    out = exposure.rescale_intensity(image)
    assert_close(out, [0, 0.5, 1])
def test_fill_hole():
    """Test reconstruction by erosion, which should fill holes in mask."""
    seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0])
    mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0])
    result = reconstruction(seed, mask, method='erosion')
    assert_close(result, np.array([0, 3, 6, 4, 4, 4, 4, 4, 2, 0]))
def test_negative_labels():
    labels = np.array([0, -1, -2, 0])
    rout = np.array([(0., 0., 0.), (0., 0., 1.), (1., 0., 0.), (0., 0., 0.)])
    assert_close(rout, label2rgb(labels, bg_label=0, alpha=1, image_alpha=1))