Пример #1
0
    def test_calc_holo_with_twocolor_index(self):
        indices = OrderedDict([('red',1.5),('green',2)])
        radius = 0.5
        center = (1, 1, 1)
        illum_wavelen = OrderedDict([('red', 0.66), ('green', 0.52)])

        sphere_red = Sphere(n=indices['red'], r=radius, center=center)
        sphere_green = Sphere(n=indices['green'], r=radius, center=center)
        sphere_both = Sphere(n=indices, r=radius, center=center)

        schema_single_color = update_metadata(
            detector_grid(shape=2, spacing=1),
            illum_polarization=(0,1),
            medium_index=1.3)
        schema_two_colors = update_metadata(
            detector_grid(
                shape=2,spacing=1,extra_dims={'illumination':['red','green']}),
            illum_polarization=(0,1),
            medium_index=1.3)

        red_hologram = calc_holo(
            schema_single_color, sphere_red, illum_wavelen=illum_wavelen['red'])
        green_hologram = calc_holo(
            schema_single_color, sphere_green,
            illum_wavelen=illum_wavelen['green'])
        both_hologram = calc_holo(
            schema_two_colors,sphere_both, illum_wavelen=illum_wavelen)

        joined = np.concatenate([
            np.array([red_hologram.values]),
            np.array([green_hologram.values])])
        assert_equal(both_hologram.values, joined)
Пример #2
0
def test_prep_schema():
    sch_f = detector_grid(shape=5, spacing=1)
    sch_x = detector_grid(
        shape=5,
        spacing=1,
        extra_dims={'illumination': ['red', 'green', 'blue']})

    wl_f = 0.5
    wl_l = [0.5, 0.6, 0.7]
    wl_d = OrderedDict([('red', 0.5), ('green', 0.6), ('blue', 0.7)])
    wl_x = xr.DataArray([0.5, 0.6, 0.7],
                        dims='illumination',
                        coords={'illumination': ['red', 'green', 'blue']})

    pol_f = (0, 1)
    pol_d = OrderedDict([('red', (0, 1)), ('green', (1, 0)),
                         ('blue', (0.5, 0.5))])

    pol_x = xr.concat(
        [to_vector((0, 1)),
         to_vector((1, 0)),
         to_vector((0.5, 0.5))], wl_x.illumination)

    all_in = prep_schema(sch_x, 1, wl_x, pol_x)

    assert_obj_close(prep_schema(sch_x, 1, wl_d, pol_d), all_in)
    assert_obj_close(prep_schema(sch_x, 1, wl_l, pol_d), all_in)
    assert_obj_close(prep_schema(sch_f, 1, wl_x, pol_x), all_in)
Пример #3
0
    def test_on_same_spacing(self):
        true_spacing = 0.1
        detector = detector_grid((10, 10), spacing=true_spacing)

        spacing = get_spacing(detector)
        self.assertEqual(spacing[0], true_spacing)
        self.assertEqual(spacing[1], true_spacing)
Пример #4
0
 def test_on_detector_grid_when_size_is_1(self):
     shape = (1, 1)
     spacing = 0.1
     true_extents = {'x': 0, 'y': 0, 'z': 0}
     detector = detector_grid(shape, spacing)
     extents = get_extents(detector)
     self.assertEqual(extents, true_extents)
Пример #5
0
def make_data(seed=1):
    np.random.seed(seed)
    shape = (5, 5)
    data_values = np.random.randn(*shape)
    data = detector_grid(shape, 0.1)
    data.values[:] = data_values
    return data
Пример #6
0
 def best_fit(self):
     shape, spacing, start, coords = yaml.load(self.dataset.data.original_dims)
     schema = detector_grid(shape, spacing, extra_dims = coords)
     schema['x'] = schema['x'] + start[0]
     schema['y'] = schema['y'] + start[1]
     schema = copy_metadata(self.dataset.data, schema, do_coords = False) 
     return self.model._forward(self.values(), schema)
Пример #7
0
    def test_does_update_medium_index(self):
        detector = detector_grid(3, 0.1)

        np.random.seed(10)
        medium_index = 1 + np.random.rand()
        updated_detector = update_metadata(detector, medium_index=medium_index)
        self.assertEqual(updated_detector.medium_index, medium_index)
Пример #8
0
    def test_holopy_hologram_equal_to_exact_calculation(self):
        # Checks that phase shifts and wrappers for mielens are correct
        theory_mielens = MieLens()
        illum_wavelength = 0.66  # 660 nm red light
        k = 2 * np.pi / illum_wavelength
        center = (10, 10, 5.)

        kwargs = {'particle_kz': center[2] * k,
                  'index_ratio': 1.2,
                  'size_parameter': 0.5 * k,
                  'lens_angle': theory_mielens.lens_angle}
        detector = detector_grid(10, 2.0)
        x = detector.x.values.reshape(-1, 1) - center[0]
        y = detector.y.values.reshape(1, -1) - center[1]

        rho = np.sqrt(x**2 + y**2)
        phi = np.arctan2(y, x)

        calculator = mielensfunctions.MieLensCalculator(**kwargs)
        scatterer = Sphere(n=kwargs['index_ratio'],
                           r=kwargs['size_parameter'] / k,
                           center=center)

        holo_calculate = calculator.calculate_total_intensity(k * rho, phi)
        holo_holopy = calc_holo(
            detector, scatterer, illum_wavelen=illum_wavelength,
            medium_index=1., illum_polarization=(1, 0), theory=theory_mielens)

        is_ok = np.allclose(holo_calculate, holo_holopy.values.squeeze(),
                            **TOLS)
        self.assertTrue(is_ok)
Пример #9
0
def test_subimage():
    i = detector_grid(shape=(10, 10), spacing=1)
    s = subimage(i, (5, 5), 2)
    assert s.shape == (1, 2, 2)

    i2 = data_grid(i, 1)
    s2 = subimage(i2, (5, 5), 2)
Пример #10
0
 def test_on_detector_grid_when_spacing_is_0(self):
     shape = (10, 12)  # (x, y)
     spacing = 0.0
     true_extents = {'x': 0, 'y': 0, 'z': 0}
     detector = detector_grid(shape, spacing)
     extents = get_extents(detector)
     self.assertEqual(extents, true_extents)
Пример #11
0
    def test_on_different_spacings(self):
        xspacing = 0.1
        yspacing = 0.2
        detector = detector_grid((10, 10), spacing=(xspacing, yspacing))

        spacing = get_spacing(detector)
        self.assertEqual(spacing[0], xspacing)
        self.assertEqual(spacing[1], yspacing)
Пример #12
0
def test_layered():
    l = LayeredSphere(n = (1, 2), t = (1, 1), center = (2, 2, 2))
    s = Sphere(n = (1,2), r = (1, 2), center = (2, 2, 2))
    sch = detector_grid((10, 10), .2)
    wavelen = .66
    hl = calc_holo(sch, l, index, wavelen, illum_polarization=xpolarization)
    hs = calc_holo(sch, s, index, wavelen, illum_polarization=xpolarization)
    assert_obj_close(hl, hs, rtol=0)
Пример #13
0
    def test_does_update_illum_wavelength(self):
        detector = detector_grid(3, 0.1)

        np.random.seed(11)
        illum_wavelen = np.random.rand()
        updated_detector = update_metadata(detector,
                                           illum_wavelen=illum_wavelen)
        self.assertEqual(updated_detector.illum_wavelen, illum_wavelen)
Пример #14
0
 def best_fit(self):
     shape, spacing, start, coords = yaml.load(
         self.dataset.data.original_dims)
     schema = detector_grid(shape, spacing, extra_dims=coords)
     schema['x'] = schema['x'] + start[0]
     schema['y'] = schema['y'] + start[1]
     schema = copy_metadata(self.dataset.data, schema, do_coords=False)
     return self.model._forward(self.values(), schema)
Пример #15
0
 def test_calc_holo_with_twocolor_alpha(self):
     detector = detector_grid(
         5, 1, extra_dims={'illumination': ['red', 'green']})
     scatterer = Sphere(
         r=0.5, n={'red': 1.5, 'green': 1.6}, center=(2, 2, 2))
     alpha = {'red': 0.8, 'green': 0.9}
     result = calc_holo(
         detector, scatterer, scaling=alpha, illum_polarization=(0, 1),
         illum_wavelen={'red': 0.66, 'green': 0.52}, medium_index=1.33)
     assert result is not None
Пример #16
0
 def test_normals_raises_error_with_deprecation_message(self):
     detector = detector_grid(3, 0.1)
     np.random.seed(13)
     normals = np.random.randn(3)
     normals /= np.linalg.norm(normals)
     self.assertRaisesRegex(ValueError,
                            "`normals` are deprecated*",
                            update_metadata,
                            detector,
                            normals=normals)
Пример #17
0
 def test_does_update_illum_polarization(self):
     detector = detector_grid(3, 0.1)
     np.random.seed(12)
     illum_polarization = np.random.randn(2)
     illum_polarization /= np.linalg.norm(illum_polarization)
     updated_detector = update_metadata(
         detector, illum_polarization=illum_polarization)
     is_ok = np.all(updated_detector.illum_polarization.values[:2] ==
                    illum_polarization)
     self.assertTrue(is_ok)
Пример #18
0
 def test_on_detector_grid_when_spacing_is_anisotropic(self):
     shape = (10, 12)  # (x, y)
     spacing = (0.1, 0.2)
     true_extents = {
         'x': shape[0] * spacing[0],
         'y': shape[1] * spacing[1],
         'z': 0
     }
     detector = detector_grid(shape, spacing)
     extents = get_extents(detector)
     self.assertEqual(extents, true_extents)
Пример #19
0
    def test_extra_dims_when_ordereddict(self):
        shape = (2, 2)
        extra_dims_sizes = (1, 2, 3, 4, 5, 6, 7, 8)  # ends up as 1.3 MB
        extra_dims_names = 'abcdefgh'
        extra_dims = OrderedDict()
        for k, v in zip(extra_dims_names, extra_dims_sizes):
            extra_dims.update({k: np.arange(v)})

        detector = detector_grid(shape, 0.1, extra_dims=extra_dims)
        true_shape = (1, ) + shape + extra_dims_sizes
        detector_shape = detector.values.shape
        self.assertEqual(true_shape, detector_shape)
Пример #20
0
 def test_calc_holo_with_twocolor_priors(self):
     detector = detector_grid(
         5, 1, extra_dims={'illumination': ['red', 'green']})
     index = {
         'red': prior.Uniform(1.5, 1.6),
         'green': prior.Uniform(1.5, 1.6)}
     scatterer = Sphere(r=0.5, n=index, center=(2,2,2))
     alpha = {'red': prior.Uniform(0.6, 1), 'green': prior.Uniform(0.6, 1)}
     model = AlphaModel(scatterer, alpha, illum_polarization=(0, 1),
                        illum_wavelen={'red': 0.66, 'green': 0.52},
                        medium_index=1.33)
     result = model.forward(model.initial_guess, detector)
     assert result is not None
Пример #21
0
def test_j0_roots():
    # Checks for misbehavior when j_0(x) = 0
    eps = 1e-12
    d = detector_grid(shape=8, spacing=1)
    d = update_metadata(d,illum_wavelen=1, medium_index=1,
                                illum_polarization=(1,0))

    s_exact = Sphere(r=1,n=1.1,center=(4,4,5)) # causes kr = 0 near center
    s_close = Sphere(r=1,n=1.1,center=(4,4,5-eps))

    h_exact = calc_field(d,s_exact)
    h_close = calc_field(d,s_close)

    np.testing.assert_allclose(h_exact, h_close)
Пример #22
0
def calculate_central_lobe_at(zs):
    illum_wavelength = 0.66  # 660 nm red light
    k = 2 * np.pi / illum_wavelength
    detector = detector_grid(4, 2.0)

    central_lobes = []
    for z in zs:
        center = (0, 0, z)
        scatterer = Sphere(n=1.59, r=0.5, center=center)
        holo = calc_holo(
            detector, scatterer, illum_wavelen=illum_wavelength,
            medium_index=1.33, illum_polarization=(1, 0), theory=MieLens())
        central_lobe = holo.values.squeeze()[0, 0]
        central_lobes.append(central_lobe)
    return np.array(central_lobes)
Пример #23
0
 def forward(self, pars):
     if hasattr(self.data, 'original_dims'):
         # dealing with subset data
         original_dims = self.data.original_dims
         # can't currently handle non-0 values of z, as in detector_grid
         x = original_dims['x']
         y = original_dims['y']
         shape = (len(x), len(y))
         spacing = (np.diff(x)[0], np.diff(y)[0])
         extra_dims = dict_without(original_dims, ['x', 'y', 'z'])
         schema = detector_grid(shape, spacing, extra_dims=extra_dims)
         schema = copy_metadata(self.data, schema, do_coords=False)
         schema['x'] = x
         schema['y'] = y
     else:
         schema = self.data
     return self.model.forward(pars, schema)
Пример #24
0
    def test_extra_dims_when_dict(self):
        # Test that extra_dims behaves correctly when dicts are not ordered,
        # in lower versions of Python
        shape = (2, 2)
        extra_dims_sizes = (1, 2, 3, 4, 5, 6, 7, 8)  # ends up as 1.3 MB
        extra_dims_names = 'abcdefgh'
        extra_dims = dict()
        for k, v in zip(extra_dims_names, extra_dims_sizes):
            extra_dims.update({k: np.arange(v)})

        detector = detector_grid(shape, 0.1, extra_dims=extra_dims)
        # Then, rather than check that the order is the same, we want
        # to check that (i) all keys are present, and (ii) each key has
        # the correct value, which we check by the shapes being equal:
        for key, value in extra_dims.items():
            self.assertIn(key, detector.coords)
            self.assertEqual(value.shape, detector.coords[key].values.shape)
Пример #25
0
def test_raw_fields():
    sp = Sphere(r=.5, n=1.6, center=(10, 10, 5))
    wavelen = .66
    index = 1.33
    pol = to_vector((0, 1))
    sch = detector_grid(3, .1)
    wavevec=2*np.pi/(wavelen/index)
    pos = Mie._transform_to_desired_coordinates(
        sch, (10, 10, 5), wavevec=wavevec)
    rf = Mie()._raw_fields(
        pos, sp, medium_wavevec=wavevec, medium_index=index,
        illum_polarization=pol)
    assert_allclose(rf, [[(0.0015606995428858754-0.0019143174710834162j),
  (-0.0003949071974815011-0.0024154494284017187j),
  (-0.002044525390662322-0.001302770747742109j),
  (-0.0003949071974815009-0.002415449428401719j),
  (-0.002055824337886397-0.0012853546864338861j),
  (-0.00230285180386436+0.000678693819245102j),
  (-0.0020445253906623225-0.0013027707477421095j),
  (-0.0023028518038643603+0.0006786938192451026j),
  (-0.0010011090105680883+0.0021552249454706712j)],
 [(-0.0010507058414478587+0.0036584360153097306j),
  (0.0020621595919700776+0.003210547679920805j),
  (0.0037794246074692407+0.000585690417403587j),
  (0.0020542215584045407+0.0031619947065620246j),
  (0.0037426710578253295+0.000527040269055415j),
  (0.002871631795307833-0.002470099566862354j),
  (0.0036968090916832948+0.0005330478443315597j),
  (0.002824872178181336-0.0024563186266035124j),
  (2.261564613123139e-06-0.003751168280253104j)],
 [(0.0010724312167657794+0.0039152445632936j),
  (0.003651474601303447+0.0017688083711547462j),
  (0.003740131549224567-0.001566271371618957j),
  (0.0036883581831347947+0.0017866751223785315j),
  (0.0037648739662344477-0.001614943488355339j),
  (0.0012643679510138835-0.003894481935619062j),
  (0.003816460764514863-0.0015982360934887314j),
  (0.0012772696647997395-0.0039342215472070105j),
  (-0.0021320123934202356-0.0035427449839031066j)]])
Пример #26
0
def test_large_sphere():
    large_sphere_gold=[[[0.96371831],[1.04338683]],[[1.04240049],[0.99605225]]]
    s=Sphere(n=1.5, r=5, center=(10,10,10))
    sch=detector_grid(10,.2)
    hl=calc_holo(sch, s, illum_wavelen=.66, medium_index=1, illum_polarization=(1,0))
    assert_obj_close(np.array(hl[0:2,0:2]),large_sphere_gold)
Пример #27
0
 def test_returned_shape_is_correct(self):
     spacing = 0.1
     shape = (9, 12)
     true_shape = (1, ) + shape
     detector = detector_grid(shape, spacing)
     self.assertEqual(detector.values.shape, true_shape)
Пример #28
0
import unittest
import warnings

import xarray as xr
import numpy as np
from nose.plugins.attrib import attr

from holopy.inference.prior import Uniform
from holopy.inference.result import UncertainValue, FitResult, SamplingResult
from holopy.inference import AlphaModel, CmaStrategy, EmceeStrategy
from holopy.scattering import Sphere
from holopy.scattering.errors import MissingParameter
from holopy.core.metadata import detector_grid, update_metadata
from holopy.core.tests.common import assert_read_matches_write

DATA = update_metadata(detector_grid(shape=10, spacing=2), 1.33, 0.660, (0, 1))
par_s = Sphere(n=Uniform(1.5, 1.65), r=Uniform(0.5, 0.7), center=[10, 10, 10])
MODEL = AlphaModel(par_s, alpha=Uniform(0.6, 0.9, guess=0.8))
INTERVALS = [
    UncertainValue(1.6, 0.1, name='n'),
    UncertainValue(0.6, 0.1, name='r'),
    UncertainValue(0.7, 0.1, name='alpha')
]


def generate_fit_result():
    return FitResult(DATA, MODEL, CmaStrategy(), 10, {'intervals': INTERVALS})


def generate_sampling_result():
    samples = np.array([[[1, 2], [11, 12], [3, 3]], [[0, 3], [1, 3], [5, 6]]])
Пример #29
0
def make_metadata():
    detector = detector_grid(7, 0.1, name='metadata')
    return update_metadata(detector, **METADATA_VALUES)
Пример #30
0
 def test_does_update_noise_sd(self):
     detector = detector_grid(3, 0.1)
     np.random.seed(13)
     noise_sd = np.random.rand()
     updated_detector = update_metadata(detector, noise_sd=noise_sd)
     self.assertEqual(updated_detector.noise_sd, noise_sd)
Пример #31
0
 def test_name_is_stored(self):
     name = 'this-is-a-name'
     detector = detector_grid(10, 0.1, name=name)
     self.assertEqual(detector.name, name)