Ejemplo n.º 1
0
def test_setup_origin():
    origin_inputs = ('domain', 'left-window', 'center-domain',
                     'lower-right-window', ('window', ), ('right', 'domain'),
                     ('lower', 'window'), ('lower', 'right', 'window'),
                     (0.5, 0.5, 'domain'), ((50, 'cm'), (50, 'cm'), 'domain'))
    w = (10, 'cm')

    ds = fake_random_ds(32, length_unit=100.0)
    generated_limits = []
    #lower limit -> llim
    #upper limit -> ulim
    #                 xllim xulim yllim yulim
    correct_limits = [
        45.0, 55.0, 45.0, 55.0, 0.0, 10.0, 0.0, 10.0, -5.0, 5.0, -5.0, 5.0,
        -10.0, 0, 0, 10.0, 0.0, 10.0, 0.0, 10.0, -55.0, -45.0, -55.0, -45.0,
        -5.0, 5.0, 0.0, 10.0, -10.0, 0, 0, 10.0, -5.0, 5.0, -5.0, 5.0, -5.0,
        5.0, -5.0, 5.0
    ]
    for o in origin_inputs:
        slc = SlicePlot(ds, 2, 'density', width=w, origin=o)
        ax = slc.plots['density'].axes
        xlims = ax.get_xlim()
        ylims = ax.get_ylim()
        lims = [xlims[0], xlims[1], ylims[0], ylims[1]]
        for l in lims:
            generated_limits.append(l)
    assert_array_almost_equal(correct_limits, generated_limits)
Ejemplo n.º 2
0
def test_on_off_compare():
    # fake density field that varies in the x-direction only
    den = np.arange(32**3) / 32**2 + 1
    den = den.reshape(32, 32, 32)
    den = np.array(den, dtype=np.float64)
    data = dict(density=(den, "g/cm**3"))
    bbox = np.array([[-1.5, 1.5], [-1.5, 1.5], [-1.5, 1.5]])
    ds = load_uniform_grid(data,
                           den.shape,
                           length_unit="Mpc",
                           bbox=bbox,
                           nprocs=64)

    sl_on = SlicePlot(ds, "z", [("gas", "density")])

    L = [0, 0, 1]
    north_vector = [0, 1, 0]
    sl_off = OffAxisSlicePlot(ds,
                              L, ("gas", "density"),
                              center=[0, 0, 0],
                              north_vector=north_vector)

    assert_array_almost_equal(sl_on.frb[("gas", "density")],
                              sl_off.frb[("gas", "density")])

    sl_on.set_buff_size((800, 400))
    sl_on._recreate_frb()
    sl_off.set_buff_size((800, 400))
    sl_off._recreate_frb()

    assert_array_almost_equal(sl_on.frb[("gas", "density")],
                              sl_off.frb[("gas", "density")])
Ejemplo n.º 3
0
def test_linear_interpolator_3d():
    random_data = np.random.random((64, 64, 64))
    # evenly spaced bins
    fv = {
        ax: v
        for ax, v in zip("xyz", np.mgrid[0.0:1.0:64j, 0.0:1.0:64j,
                                         0.0:1.0:64j])
    }
    tfi = lin.TrilinearFieldInterpolator(random_data,
                                         (0.0, 1.0, 0.0, 1.0, 0.0, 1.0), "xyz",
                                         True)
    assert_array_almost_equal(tfi(fv), random_data)

    # randomly spaced bins
    size = 64
    bins = np.linspace(0.0, 1.0, size)
    shifts = {
        ax: (1.0 / size) * np.random.random(size) - (0.5 / size)
        for ax in "xyz"
    }
    fv["x"] += shifts["x"][:, np.newaxis, np.newaxis]
    fv["y"] += shifts["y"][:, np.newaxis]
    fv["z"] += shifts["z"]
    tfi = lin.TrilinearFieldInterpolator(
        random_data,
        (bins + shifts["x"], bins + shifts["y"], bins + shifts["z"]),
        "xyz",
        True,
    )
    assert_array_almost_equal(tfi(fv), random_data, 15)
Ejemplo n.º 4
0
def test_neighbor_search():
    np.random.seed(0x4d3d3d3)
    ds = fake_particle_ds(npart=16**3)
    ds.periodicity = (True, True, True)
    ds.index
    fn, = add_nearest_neighbor_field("all", "particle_position", ds)
    dd = ds.all_data()
    nearest_neighbors = dd[fn]
    pos = dd["particle_position"]
    all_neighbors = np.zeros_like(nearest_neighbors)
    any_eq = np.zeros(pos.shape[0], dtype='bool')
    min_in = np.zeros(pos.shape[0], dtype='int64')
    for i in range(pos.shape[0]):
        dd.set_field_parameter("center", pos[i, :])
        #radius = dd["particle_radius"]
        #radius.sort()
        r2 = (pos[:, 0] * pos[:, 0]) * 0
        for j in range(3):
            DR = (pos[i, j] - pos[:, j])
            DRo = DR.copy()
            DR[DRo > ds.domain_width[j] / 2.0] -= ds.domain_width[j]
            DR[DRo < -ds.domain_width[j] / 2.0] += ds.domain_width[j]
            r2 += DR * DR
        radius = np.sqrt(r2)
        radius.sort()
        assert (radius[0] == 0.0)
        all_neighbors[i] = radius[63]
        any_eq[i] = np.any(np.abs(radius - nearest_neighbors[i]) < 1e-7)
        min_in[i] = np.argmin(np.abs(radius - nearest_neighbors[i]))
        #if i == 34: raise RuntimeError
        #dd.field_data.pop(("all", "particle_radius"))
    assert_equal((min_in == 63).sum(), min_in.size)
    assert_array_almost_equal(nearest_neighbors, all_neighbors)
def test_spherical_coordinate_conversion():
    normal = [0, 0, 1]
    real_r =     [ 0.72950559,  0.99384957,  1.13047198,  0.97696269,  
                   1.09807968,  1.12445067,  1.10788685,  1.38843954]
    real_theta = [ 2.44113629,  0.87012028,  2.14891444,  1.4032274 ,  
                   0.80979483,  2.10280198,  1.13507735,  1.85068416]
    real_phi =   [-2.65224483, -0.23804243, -1.47641858, -1.46498842, 
                  -0.40172325, -0.4422801 ,  0.95466734, -2.31085392]

    calc_r = get_sph_r(coords)
    calc_theta = get_sph_theta(coords, normal)
    calc_phi = get_sph_phi(coords, normal)

    assert_array_almost_equal(calc_r, real_r)
    assert_array_almost_equal(calc_theta, real_theta)
    assert_array_almost_equal(calc_phi, real_phi)

    normal = [1, 0, 0]
    real_theta = [ 2.17598842,  0.73347681,  1.49179079,  1.46647589,  
                   0.8412984 ,  0.67793705,  1.0193883 ,  2.27586987]
    real_phi =   [-1.94809584,  1.843405,   -2.56143151,  2.97309903,
                  1.96037671,  -2.1995016,   0.51841239, -2.77038877]

    calc_theta = get_sph_theta(coords, normal)
    calc_phi = get_sph_phi(coords, normal)

    assert_array_almost_equal(calc_theta, real_theta)
    assert_array_almost_equal(calc_phi, real_phi)
Ejemplo n.º 6
0
def test_phase_plot():
    fields = ("density", "temperature", "velocity_x", "velocity_y",
              "velocity_z")
    units = ("g/cm**3", "K", "cm/s", "cm/s", "cm/s")
    test_ds = fake_random_ds(16, fields=fields, units=units)
    regions = [
        test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3),
        test_ds.all_data()
    ]
    phases = []
    ph_fields = [
        [("gas", "density"), ("gas", "temperature"), ("gas", "mass")],
        [("gas", "density"), ("gas", "velocity_x"), ("gas", "mass")],
        [("index", "radius"), ("gas", "temperature"),
         ("gas", "velocity_magnitude")],
    ]
    for reg in regions:
        for x_field, y_field, z_field in ph_fields:
            # set n_bins to [16, 16] since matplotlib's postscript
            # renderer is slow when it has to write a lot of polygons
            phases.append(
                PhasePlot(reg, x_field, y_field, z_field, x_bins=16,
                          y_bins=16))
            phases.append(
                PhasePlot(
                    reg,
                    x_field,
                    y_field,
                    z_field,
                    fractional=True,
                    accumulation=True,
                    x_bins=16,
                    y_bins=16,
                ))
            p2d = create_profile(reg, [x_field, y_field],
                                 z_field,
                                 n_bins=[16, 16])
            phases.append(PhasePlot.from_profile(p2d))
    pp = PhasePlot(
        test_ds.all_data(),
        ("gas", "density"),
        ("gas", "temperature"),
        ("gas", "mass"),
    )
    pp.set_xlim(0.3, 0.8)
    pp.set_ylim(0.4, 0.6)
    pp._setup_plots()
    xlim = pp.plots[("gas", "mass")].axes.get_xlim()
    ylim = pp.plots[("gas", "mass")].axes.get_ylim()
    assert_array_almost_equal(xlim, (0.3, 0.8))
    assert_array_almost_equal(ylim, (0.4, 0.6))
    phases.append(pp)
    phases[0]._repr_html_()
    for idx, plot in enumerate(phases):
        test_prefix = f"{plot.plots.keys()}_{idx}"
        yield compare(test_ds,
                      plot,
                      test_prefix=test_prefix,
                      test_name="phase_plots")
Ejemplo n.º 7
0
    def test_creation_with_width(self, width):
        xlim, ylim, pwidth, aun = WIDTH_SPECS[width]
        plot = self.pplots_w[width]

        xlim = [plot.ds.quan(el[0], el[1]) for el in xlim]
        ylim = [plot.ds.quan(el[0], el[1]) for el in ylim]
        pwidth = [plot.ds.quan(el[0], el[1]) for el in pwidth]

        [assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]
        [assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]
        [assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]
Ejemplo n.º 8
0
    def test_creation_with_width(self):
        test_ds = fake_particle_ds()
        for width, (xlim, ylim, pwidth, _aun) in WIDTH_SPECS.items():
            plot = ParticleProjectionPlot(test_ds, 0, "particle_mass", width=width)

            xlim = [plot.ds.quan(el[0], el[1]) for el in xlim]
            ylim = [plot.ds.quan(el[0], el[1]) for el in ylim]
            pwidth = [plot.ds.quan(el[0], el[1]) for el in pwidth]

            [assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]
            [assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]
            [assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]
Ejemplo n.º 9
0
 def test_phase_plot(self):
     fields = ('density', 'temperature', 'velocity_x', 'velocity_y',
               'velocity_z')
     units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s')
     test_ds = fake_random_ds(16, fields=fields, units=units)
     regions = [
         test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3),
         test_ds.all_data()
     ]
     phases = []
     ph_fields = [('density', 'temperature', 'cell_mass'),
                  ('density', 'velocity_x', 'cell_mass'),
                  ('radius', 'temperature', 'velocity_magnitude')]
     for reg in regions:
         for x_field, y_field, z_field in ph_fields:
             # set n_bins to [16, 16] since matplotlib's postscript
             # renderer is slow when it has to write a lot of polygons
             phases.append(
                 PhasePlot(reg,
                           x_field,
                           y_field,
                           z_field,
                           x_bins=16,
                           y_bins=16))
             phases.append(
                 PhasePlot(reg,
                           x_field,
                           y_field,
                           z_field,
                           fractional=True,
                           accumulation=True,
                           x_bins=16,
                           y_bins=16))
             p2d = create_profile(reg, [x_field, y_field],
                                  z_field,
                                  n_bins=[16, 16])
             phases.append(PhasePlot.from_profile(p2d))
     pp = PhasePlot(test_ds.all_data(), 'density', 'temperature',
                    'cell_mass')
     pp.set_xlim(0.3, 0.8)
     pp.set_ylim(0.4, 0.6)
     pp._setup_plots()
     xlim = pp.plots['cell_mass'].axes.get_xlim()
     ylim = pp.plots['cell_mass'].axes.get_ylim()
     assert_array_almost_equal(xlim, (0.3, 0.8))
     assert_array_almost_equal(ylim, (0.4, 0.6))
     phases.append(pp)
     phases[0]._repr_html_()
     for p in phases:
         for fname in TEST_FLNMS:
             assert_fname(p.save(fname)[0])
Ejemplo n.º 10
0
    def test_creation_with_width(self):
        test_ds = fake_random_ds(16)
        for width in WIDTH_SPECS:
            xlim, ylim, pwidth, aun = WIDTH_SPECS[width]
            plot = ProjectionPlot(test_ds, 0, 'density', width=width)

            xlim = [plot.ds.quan(el[0], el[1]) for el in xlim]
            ylim = [plot.ds.quan(el[0], el[1]) for el in ylim]
            pwidth = [plot.ds.quan(el[0], el[1]) for el in pwidth]

            [assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]
            [assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]
            [assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]
            assert_true(aun == plot._axes_unit_names)
Ejemplo n.º 11
0
    def setUpClass(cls):
        fields = ('density', 'temperature', 'velocity_x', 'velocity_y',
                  'velocity_z')
        units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s')
        test_ds = fake_random_ds(64, fields=fields, units=units)
        regions = [test_ds.region([0.5]*3, [0.4]*3, [0.6]*3), test_ds.all_data()]
        profiles = []
        phases = []
        pr_fields = [('density', 'temperature'), ('density', 'velocity_x'),
                     ('temperature', 'cell_mass'), ('density', 'radius'),
                     ('velocity_magnitude', 'cell_mass')]
        ph_fields = [('density', 'temperature', 'cell_mass'),
                     ('density', 'velocity_x', 'cell_mass'),
                     ('radius', 'temperature', 'velocity_magnitude')]
        for reg in regions:
            for x_field, y_field in pr_fields:
                profiles.append(ProfilePlot(reg, x_field, y_field))
                profiles.append(ProfilePlot(reg, x_field, y_field,
                                            fractional=True, accumulation=True))
                p1d = create_profile(reg, x_field, y_field)
                profiles.append(ProfilePlot.from_profiles(p1d))
            for x_field, y_field, z_field in ph_fields:
                # set n_bins to [16, 16] since matplotlib's postscript
                # renderer is slow when it has to write a lot of polygons
                phases.append(PhasePlot(reg, x_field, y_field, z_field,
                                        x_bins=16, y_bins=16))
                phases.append(PhasePlot(reg, x_field, y_field, z_field,
                                        fractional=True, accumulation=True,
                                        x_bins=16, y_bins=16))
                p2d = create_profile(reg, [x_field, y_field], z_field,
                                     n_bins=[16, 16])
                phases.append(PhasePlot.from_profile(p2d))
        pp = PhasePlot(test_ds.all_data(), 'density', 'temperature', 'cell_mass')
        pp.set_xlim(0.3, 0.8)
        pp.set_ylim(0.4, 0.6)
        pp._setup_plots()
        xlim = pp.plots['cell_mass'].axes.get_xlim()
        ylim = pp.plots['cell_mass'].axes.get_ylim()
        assert_array_almost_equal(xlim, (0.3, 0.8))
        assert_array_almost_equal(ylim, (0.4, 0.6))
        phases.append(pp)

        p1 = create_profile(test_ds.all_data(), 'density', 'temperature')
        p2 = create_profile(test_ds.all_data(), 'density', 'velocity_x')
        profiles.append(ProfilePlot.from_profiles(
            [p1, p2], labels=['temperature', 'velocity']))

        cls.profiles = profiles
        cls.phases = phases
        cls.ds = test_ds
Ejemplo n.º 12
0
def test_linear_interpolator_1d():
    random_data = np.random.random(64)
    fv = {'x': np.mgrid[0.0:1.0:64j]}
    # evenly spaced bins
    ufi = lin.UnilinearFieldInterpolator(random_data, (0.0, 1.0), "x", True)
    assert_array_equal(ufi(fv), random_data)

    # randomly spaced bins
    size = 64
    shift = (1. / size) * np.random.random(size) - (0.5 / size)
    fv["x"] += shift
    ufi = lin.UnilinearFieldInterpolator(random_data,
                                         np.linspace(0.0, 1.0, size) + shift,
                                         "x", True)
    assert_array_almost_equal(ufi(fv), random_data, 15)
Ejemplo n.º 13
0
def test_linear_interpolator_2d():
    random_data = np.random.random((64, 64))
    # evenly spaced bins
    fv = dict(
        (ax, v) for ax, v in zip("xyz", np.mgrid[0.0:1.0:64j, 0.0:1.0:64j]))
    bfi = lin.BilinearFieldInterpolator(random_data, (0.0, 1.0, 0.0, 1.0),
                                        "xy", True)
    assert_array_equal(bfi(fv), random_data)

    # randomly spaced bins
    size = 64
    bins = np.linspace(0.0, 1.0, size)
    shifts = dict((ax, (1. / size) * np.random.random(size) - (0.5 / size)) \
                  for ax in "xy")
    fv["x"] += shifts["x"][:, np.newaxis]
    fv["y"] += shifts["y"]
    bfi = lin.BilinearFieldInterpolator(
        random_data, (bins + shifts["x"], bins + shifts["y"]), "xy", True)
    assert_array_almost_equal(bfi(fv), random_data, 15)
Ejemplo n.º 14
0
def test_cython_tree():
    r"""This test makes sure that the cython kdtree is finding the correct
    nearest neighbors.
    """
    # Four points.
    pos = np.empty((4, 3), dtype='float64')
    # Make four points by hand that, in particular, will allow us to test
    # the periodicity of the kdtree.
    points = np.array([0.01, 0.5, 0.98, 0.99])
    pos[:, 0] = points
    pos[:, 1] = points
    pos[:, 2] = points
    kdtree = cKDTree(pos, leafsize=2)
    qv = np.array([0.999] * 3)
    res = kdtree.query(qv, 4, period=[1., 1., 1])
    # What the answers should be.
    dist = np.array([2.43e-04, 3.63e-04, 1.083e-03, 7.47003e-01])
    tags = np.array([3, 0, 2, 1], dtype='int64')
    assert_array_almost_equal(res[0], dist)
    assert_array_equal(res[1], tags)
Ejemplo n.º 15
0
def sph_fields_validate(ds_fn):
    ds = yt.load(ds_fn, **(load_kwargs[ds_fn]))
    ad = ds.all_data()
    for gf, pf in gas_fields_to_particle_fields.items():
        gas_field = ad["gas", gf]
        part_field = ad[ds._sph_ptypes[0], pf]

        assert_array_almost_equal(gas_field, part_field)

        npart = ds.particle_type_counts[ds._sph_ptypes[0]]
        err_msg = "Field %s is not the correct shape" % (gf, )
        assert_equal(npart, gas_field.shape[0], err_msg=err_msg)

    dd = ds.r[0.4:0.6, 0.4:0.6, 0.4:0.6]

    for i, ax in enumerate("xyz"):
        dd.set_field_parameter("cp_%s_vec" % (ax, ), yt.YTArray([1, 1, 1]))
        dd.set_field_parameter("axis", i)
    dd.set_field_parameter("omega_baryon", 0.3)

    for f in ds.fields.gas:
        gas_field = dd[f]
        assert f.is_sph_field
Ejemplo n.º 16
0
def test_set_unit():
    ds = fake_random_ds(32, fields=(("gas", "temperature"),), units=("K",))
    slc = SlicePlot(ds, 2, ("gas", "temperature"))

    orig_array = slc.frb["gas", "temperature"].copy()

    slc.set_unit(("gas", "temperature"), "degF")

    assert str(slc.frb["gas", "temperature"].units) == "°F"
    assert_array_almost_equal(
        np.array(slc.frb["gas", "temperature"]), np.array(orig_array) * 1.8 - 459.67
    )

    # test that a plot modifying function that destroys the frb preserves the
    # new unit
    slc.set_buff_size(1000)

    assert str(slc.frb["gas", "temperature"].units) == "°F"

    slc.set_buff_size(800)

    slc.set_unit(("gas", "temperature"), "K")
    assert str(slc.frb["gas", "temperature"].units) == "K"
    assert_array_almost_equal(slc.frb["gas", "temperature"], orig_array)

    slc.set_unit(("gas", "temperature"), "keV", equivalency="thermal")
    assert str(slc.frb["gas", "temperature"].units) == "keV"
    assert_array_almost_equal(
        slc.frb["gas", "temperature"], (orig_array * kboltz).to("keV")
    )

    # test that a plot modifying function that destroys the frb preserves the
    # new unit with an equivalency
    slc.set_buff_size(1000)

    assert str(slc.frb["gas", "temperature"].units) == "keV"

    # test that destroying the FRB then changing the unit using an equivalency
    # doesn't error out, see issue #1316
    slc = SlicePlot(ds, 2, ("gas", "temperature"))
    slc.set_buff_size(1000)
    slc.set_unit(("gas", "temperature"), "keV", equivalency="thermal")
    assert str(slc.frb["gas", "temperature"].units) == "keV"
Ejemplo n.º 17
0
def test_set_unit():
    ds = fake_random_ds(32, fields=('temperature',), units=('K',))
    slc = SlicePlot(ds, 2, 'temperature')

    orig_array = slc.frb['gas', 'temperature'].copy()

    slc.set_unit('temperature', 'degF')

    assert str(slc.frb['gas', 'temperature'].units) == 'degF'
    assert_array_almost_equal(np.array(slc.frb['gas', 'temperature']),
                              np.array(orig_array)*1.8 - 459.67)

    # test that a plot modifying function that destroys the frb preserves the
    # new unit
    slc.set_buff_size(1000)

    assert str(slc.frb['gas', 'temperature'].units) == 'degF'

    slc.set_buff_size(800)

    slc.set_unit('temperature', 'K')
    assert str(slc.frb['gas', 'temperature'].units) == 'K'
    assert_array_almost_equal(slc.frb['gas', 'temperature'], orig_array)

    slc.set_unit('temperature', 'keV', equivalency='thermal')
    assert str(slc.frb['gas', 'temperature'].units) == 'keV'
    assert_array_almost_equal(slc.frb['gas', 'temperature'],
                              (orig_array*kboltz).to('keV'))

    # test that a plot modifying function that destroys the frb preserves the
    # new unit with an equivalency
    slc.set_buff_size(1000)

    assert str(slc.frb['gas', 'temperature'].units) == 'keV'

    # test that destroying the FRB then changing the unit using an equivalency
    # doesn't error out, see issue #1316
    slc = SlicePlot(ds, 2, 'temperature')
    slc.set_buff_size(1000)
    slc.set_unit('temperature', 'keV', equivalency='thermal')
    assert str(slc.frb['gas', 'temperature'].units) == 'keV'
def test_cylindrical_coordinate_conversion():
    normal = [0, 0, 1]
    real_r = [
        0.47021498, 0.75970506, 0.94676179, 0.96327853, 0.79516968, 0.96904193,
        1.00437346, 1.3344104
    ]
    real_theta = [
        -2.65224483, -0.23804243, -1.47641858, -1.46498842, -0.40172325,
        -0.4422801, 0.95466734, -2.31085392
    ]
    real_z = [
        -0.55774212, 0.64076921, -0.61774511, 0.16294352, 0.75728738,
        -0.57039201, 0.46759728, -0.38355343
    ]

    calc_r = get_cyl_r(coords, normal)
    calc_theta = get_cyl_theta(coords, normal)
    calc_z = get_cyl_z(coords, normal)

    assert_array_almost_equal(calc_r, real_r)
    assert_array_almost_equal(calc_theta, real_theta)
    assert_array_almost_equal(calc_z, real_z)

    normal = [1, 0, 0]
    real_r = [
        0.59994016, 0.66533898, 1.12694569, 0.97165149, 0.81862843, 0.70524152,
        0.94368441, 1.05738542
    ]
    real_theta = [
        -0.37729951, -2.86898397, -0.99063518, -1.73928995, -2.75201227,
        -0.62870527, 2.08920872, -1.19959244
    ]
    real_z = [
        -0.41503037, 0.73828247, 0.08922066, 0.10173242, 0.73186508, 0.8757989,
        0.58040762, -0.89983356
    ]

    calc_r = get_cyl_r(coords, normal)
    calc_theta = get_cyl_theta(coords, normal)
    calc_z = get_cyl_z(coords, normal)

    assert_array_almost_equal(calc_r, real_r)
    assert_array_almost_equal(calc_theta, real_theta)
    assert_array_almost_equal(calc_z, real_z)
Ejemplo n.º 19
0
def test_setup_origin():
    origin_inputs = (
        "domain",
        "left-window",
        "center-domain",
        "lower-right-window",
        ("window", ),
        ("right", "domain"),
        ("lower", "window"),
        ("lower", "right", "window"),
        (0.5, 0.5, "domain"),
        ((50, "cm"), (50, "cm"), "domain"),
    )
    w = (10, "cm")

    ds = fake_random_ds(32, length_unit=100.0)
    generated_limits = []
    # lower limit -> llim
    # upper limit -> ulim
    #                 xllim xulim yllim yulim
    correct_limits = [
        45.0,
        55.0,
        45.0,
        55.0,
        0.0,
        10.0,
        0.0,
        10.0,
        -5.0,
        5.0,
        -5.0,
        5.0,
        -10.0,
        0,
        0,
        10.0,
        0.0,
        10.0,
        0.0,
        10.0,
        -55.0,
        -45.0,
        -55.0,
        -45.0,
        -5.0,
        5.0,
        0.0,
        10.0,
        -10.0,
        0,
        0,
        10.0,
        -5.0,
        5.0,
        -5.0,
        5.0,
        -5.0,
        5.0,
        -5.0,
        5.0,
    ]
    for o in origin_inputs:
        slc = SlicePlot(ds, 2, ("gas", "density"), width=w, origin=o)
        ax = slc.plots[("gas", "density")].axes
        xlims = ax.get_xlim()
        ylims = ax.get_ylim()
        lims = [xlims[0], xlims[1], ylims[0], ylims[1]]
        for l in lims:
            generated_limits.append(l)
    assert_array_almost_equal(correct_limits, generated_limits)
def test_spherical_coordinate_projections():
    normal = [0, 0, 1]
    theta = get_sph_theta(coords, normal)
    phi = get_sph_phi(coords, normal)
    zero = np.tile(0, coords.shape[1])

    # Purely radial field
    vecs = np.array([
        np.sin(theta) * np.cos(phi),
        np.sin(theta) * np.sin(phi),
        np.cos(theta)
    ])
    assert_array_almost_equal(
        zero, get_sph_theta_component(vecs, theta, phi, normal))
    assert_array_almost_equal(zero, get_sph_phi_component(vecs, phi, normal))

    # Purely toroidal field
    vecs = np.array([-np.sin(phi), np.cos(phi), zero])
    assert_array_almost_equal(
        zero, get_sph_theta_component(vecs, theta, phi, normal))
    assert_array_almost_equal(zero,
                              get_sph_r_component(vecs, theta, phi, normal))

    # Purely poloidal field
    vecs = np.array([
        np.cos(theta) * np.cos(phi),
        np.cos(theta) * np.sin(phi), -np.sin(theta)
    ])
    assert_array_almost_equal(zero, get_sph_phi_component(vecs, phi, normal))
    assert_array_almost_equal(zero,
                              get_sph_r_component(vecs, theta, phi, normal))
def test_cylindrical_coordinate_projections():
    normal = [0, 0, 1]
    theta = get_cyl_theta(coords, normal)
    z = get_cyl_z(coords, normal)
    zero = np.tile(0, coords.shape[1])

    # Purely radial field
    vecs = np.array([np.cos(theta), np.sin(theta), zero])
    assert_array_almost_equal(zero,
                              get_cyl_theta_component(vecs, theta, normal))
    assert_array_almost_equal(zero, get_cyl_z_component(vecs, normal))

    # Purely toroidal field
    vecs = np.array([-np.sin(theta), np.cos(theta), zero])
    assert_array_almost_equal(zero, get_cyl_z_component(vecs, normal))
    assert_array_almost_equal(zero, get_cyl_r_component(vecs, theta, normal))

    # Purely z field
    vecs = np.array([zero, zero, z])
    assert_array_almost_equal(zero,
                              get_cyl_theta_component(vecs, theta, normal))
    assert_array_almost_equal(zero, get_cyl_r_component(vecs, theta, normal))