def test_from_parameters(self): n = Uniform(0, 1) r = Uniform(0, np.pi / 2) spheres = [Sphere(n=n, r=r, center=[i, i, i]) for i in range(3)] spheres = Spheres(spheres) parameters = spheres.parameters self.assertEqual(spheres.guess, spheres.from_parameters(parameters))
def test_from_parameters_keeps_attributes(self): spheres = [ Sphere(n=np.random.rand(), r=0.1, center=[i, i, i]) for i in range(3) ] spheres = Spheres(spheres, warn="TEST") spheres = spheres.from_parameters(spheres.parameters) self.assertEqual(spheres.warn, "TEST")
def test_parameterize_scatterer_spheres_by_given(self): s1 = Sphere(r=0.5, n=1, center=[0, 0, 0]) s2 = Sphere(r=0.5, n=1, center=[1, 1, 1]) model = make_default_model(Spheres([s1, s2]), ['0:r', '1:x']) e1 = Sphere(r=prior.Uniform(0, np.inf, 0.5, '0:r'), n=1, center=[0, 0, 0]) e2 = Sphere(r=0.5, n=1, center=[prior.Uniform(-np.inf, np.inf, 1, '1:x'), 1, 1]) self.assertEqual(model.scatterer, Spheres([e1, e2]))
def test_adding_newly_tied_scatterer(self): n = Uniform(0, 1) r = Uniform(0, 1) spheres = [Sphere(n=n, r=r, center=[1, 1, 1])] spheres = Spheres(spheres) spheres.add(Sphere(n=n, r=r, center=[2, 2, 2])) expected_keys = { 'n', 'r', '0:center.0', '0:center.1', '0:center.2', '1:center.0', '1:center.1', '1:center.2' } self.assertEqual(set(spheres.parameters.keys()), expected_keys)
def test_adding_untied_scatterer(self): n = Uniform(0, 1) r = Uniform(0, 1) spheres = [Sphere(n=n, r=r, center=[i, i, i]) for i in range(2)] spheres = Spheres(spheres) spheres.add(Sphere(n=1, r=1, center=[2, 2, 2])) expected_keys = { 'n', 'r', '0:center.0', '0:center.1', '0:center.2', '1:center.0', '1:center.1', '1:center.2', '2:n', '2:r', '2:center.0', '2:center.1', '2:center.2' } self.assertEqual(set(spheres.parameters.keys()), expected_keys)
def test_polarization(): # test holograms for orthogonal polarizations; make sure they're # not the same, nor too different from one another. sc = Spheres([sphere]) xholo = calc_holo(xschema, sc, index, wavelen, xpolarization, scaling=scaling_alpha) yholo = calc_holo(yschema, sc, index, wavelen, ypolarization, scaling=scaling_alpha) # the two arrays should not be equal try: assert_array_almost_equal(xholo, yholo) except AssertionError: pass else: raise AssertionError( "Holograms computed for both x- and y-polarized light are too similar." ) # but their max and min values should be close assert_obj_close(xholo.max(), yholo.max()) assert_obj_close(xholo.min(), yholo.min()) return xholo, yholo
def test_cross_sections(): wavelen = 1. index = 1. polarization = [1., 0] a = 1. / (2 * np.pi) # size parameter 1 n = 1.5 + 0.1j sc = Spheres([ Sphere(n=n, r=a, center=[0., 0., a]), Sphere(n=n, r=a, center=[0., 0., -a]) ]) thry = Multisphere() # this ends up testing the angular dependence of scattering # as well as all the scattering coefficients with warnings.catch_warnings(): warnings.simplefilter('ignore', scipy.integrate.IntegrationWarning) xsects = calc_cross_sections(sc, illum_wavelen=wavelen, medium_index=index, illum_polarization=ypolarization) gold_xsects = np.array([0.03830316, 0.04877015, 0.08707331]) # calculated directly by SCSMFO. Efficiencies normalized # in funny way by SCSMFO, based on "volume mean radius". if 'TRAVIS' in os.environ: #This test fails on travis for unknown reasons. See github issue #194 raise SkipTest() else: assert_allclose(xsects[:3], gold_xsects, rtol=1e-3)
def test_radial_holos(): # Check that holograms computed with and w/o radial part of E_scat differ sc = Spheres(scatterers=[ Sphere(center=[7.1e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07), Sphere(center=[6e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07) ]) thry_nonrad = Multisphere() thry_rad = Multisphere(compute_escat_radial=True) holo_nonrad = calc_holo(schema, sc, index, wavelen, xpolarization, theory=thry_nonrad) holo_rad = calc_holo(schema, sc, index, wavelen, xpolarization, theory=thry_rad) # the two arrays should not be equal try: assert_allclose(holo_nonrad, holo_rad) except AssertionError: pass else: raise AssertionError( "Holograms computed with and without radial component of scattered electric field are too similar." )
def bisphere(a_p, n_p, z_p, theta, phi, noise=True): px = int(feature_extent(a_p, n_p, z_p, config)) * 2 detector = hp.detector_grid(2 * px, mag) center = (mag * px, mag * px, z_p) delta = np.array([ np.cos(phi) * np.cos(theta), np.sin(phi) * np.cos(theta), np.sin(theta) ]) c1 = +1.001 * a_p * delta c2 = -1.001 * a_p * delta cluster = np.array([c1, c2]) cluster_return = cluster.copy().tolist() cluster += center s1 = Sphere(center=cluster[0], n=n_p, r=a_p) s2 = Sphere(center=cluster[1], n=n_p, r=a_p) dimer = Spheres([s1, s2]) holo = np.squeeze( calc_holo(detector, dimer, medium_index=n_m, illum_wavelen=wv, illum_polarization=(1, 0))).data #noise if noise: holo += np.random.normal(0., 0.05, holo.shape) return holo, cluster_return
def scatter(x, y, z, particle_number, radius, detector, medium_index, illum_wavelen, illum_polarization, theory=Mie, refractive): #create all spheres in object compiled = [] for item in range(len(x)): compiled.append( Sphere(n=refractive, r=radius, center=(np.around(x[item], 3), np.around(y[item], 3), np.around(z[item], 3)))) collection = Spheres(compiled) #Actual field calculations field = calc_field(detector, collection, medium_index, illum_wavelen, illum_polarization, theory=Mie) return field
def test_getattr(self): spheres = [ Sphere(n=np.random.rand(), r=np.random.rand(), center=[i, i, i]) for i in range(3) ] spheres = Spheres(spheres) self.assertEqual(spheres[1], spheres.scatterers[1])
def test_tied_name(self): tied = prior.Uniform(0, 1) sphere1 = Sphere(n=prior.Uniform(1, 2), r=tied, center=[1, 1, 1]) sphere2 = Sphere(n=prior.Uniform(1, 2), r=tied, center=[1, 1, 1]) model = AlphaModel(Spheres([sphere1, sphere2])) expected_names = ['0:n', 'r', '1:n'] self.assertEqual(model._parameter_names, expected_names)
def test_fixed_values_not_tied(self): n = 1.5 r = 0.5 spheres = [Sphere(n=n, r=r) for i in range(3)] spheres = Spheres(spheres) expected_keys = {'0:n', '0:r', '1:n', '1:r', '2:n', '2:r'} self.assertEqual(set(spheres.parameters.keys()), expected_keys)
def test_select(): s = Sphere(n=xr.DataArray([1.5, 1.7], dims='ill', coords={'ill': ['r', 'g']}), center=[0, 0, 0], r=0.5) assert_equal(s.select({'ill': 'g'}), Sphere(n=1.7, center=[0, 0, 0], r=0.5)) ss = Spheres([s, s.translated([1, 1, 1])]) assert_equal( ss.select({'ill': 'g'}), Spheres([ Sphere(n=1.7, center=[0, 0, 0], r=0.5), Sphere(n=1.7, center=[1, 1, 1], r=0.5) ]))
def test_determine_default_theory_for_layered_spheres(self): layered_spheres = Spheres([Sphere(r=[0.5, 1], n=[1, 1.5])] * 2) with warnings.catch_warnings(): warnings.filterwarnings('ignore') default_theory = determine_default_theory_for(layered_spheres) correct_theory = Mie() self.assertTrue(default_theory == correct_theory)
def test_polarization_rotation_produces_small_changes_to_image(self): # we test that, for two sphere, rotating the polarization # does not drastically change the image # We place the two spheres along the line phi = 0 z_um = 3.0 s1 = Sphere(r=0.5, center=(1.0, 0.0, z_um), n=1.59) s2 = Sphere(r=0.5, center=(2.5, 0.0, z_um), n=1.59) scatterer = Spheres([s1, s2]) medium_wavevec = 2 * np.pi * 1.33 / 0.66 medium_index = test_common.index theory = Lens(LENS_ANGLE, Multisphere()) args = (scatterer, medium_wavevec, medium_index) rho_um = np.linspace(0, 5, 26) krho = medium_wavevec * rho_um phi = np.zeros(krho.size) kz = np.zeros(krho.size) + medium_wavevec * z_um pos = np.array([krho, phi, kz]) fields_xpol = theory._raw_fields(pos, *args, xr.DataArray([1, 0, 0])) fields_ypol = theory._raw_fields(pos, *args, xr.DataArray([0, 1, 0])) intensity_xpol = np.linalg.norm(fields_xpol, axis=0)**2 intensity_ypol = np.linalg.norm(fields_ypol, axis=0)**2 # We are just trying to check that rotating the polarization # does not rotate the image, so we can afford soft tolerances: tols = {'atol': 5e-2, 'rtol': 5e-2} self.assertTrue(np.allclose(intensity_xpol, intensity_ypol, **tols))
def test_all_ties(self): n = Uniform(0, 1) r = Uniform(0, 1) spheres = [Sphere(n=n, r=r, center=[i, i, i]) for i in range(3)] spheres = Spheres(spheres) expected_ties = ['0:n', '1:n', '2:n', '0:r', '1:r', '2:r'] self.assertEqual(spheres._all_ties, expected_ties)
def test_add_tie(self): spheres = [Sphere(n=Uniform(0, 1), r=Uniform(0, 1)) for i in range(3)] spheres = Spheres(spheres) spheres.add_tie('0:r', '1:r') spheres.add_tie('r', '2:r') spheres.add_tie('0:n', '1:n') spheres.add_tie('0:n', '2:n') expected_keys = {'n', 'r'} self.assertEqual(set(spheres.parameters.keys()), expected_keys)
def test_parameters_checks_ties(self): spheres = [Sphere(n=Uniform(0, 1), r=Uniform(0, 1)) for i in range(3)] ties = {'r': ['0:r', '1:r', '2:r'], 'n': ['0:n', '1:n', '2:n']} spheres = Spheres(spheres, ties=ties) spheres.ties['n'].append('dummy_name') msg = 'Tied parameter dummy_name not present in raw parameters' with self.assertRaisesRegex(ValueError, msg): spheres.parameters
def test_parameterize_scatterer_spheres(self): sphere = Sphere(r=0.5, n=1, center=[0, 0, 0]) model = make_default_model(Spheres([sphere, sphere], warn=False)) expected = { '0:n', '1:n', '0:r', '1:r', 'alpha', '0:x', '0:y', '0:z', '1:x', '1:y', '1:z' } self.assertEqual(set(model.parameters.keys()), expected)
def test_niter(): sc = Spheres(scatterers=[ Sphere(center=[7.1e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07), Sphere(center=[6e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07) ]) multi = Multisphere(niter=2) assert_raises(MultisphereFailure, calc_holo, schema, sc, index, wavelen, xpolarization, multi)
def test_constraint(): with warnings.catch_warnings(): warnings.simplefilter("ignore", OverlapWarning) spheres = Spheres( [Sphere(r=.5, center=(0, 0, 0)), Sphere(r=.5, center=(0, 0, .2))]) model = ExactModel(spheres, calc_holo, constraints=LimitOverlaps()) cost = model.lnprior({'1:Sphere.center[2]': .2}) assert_equal(cost, -np.inf)
def test_scatterer_io(): s = Sphere() assert_read_matches_write(s) s1 = Sphere(1.59, .5, [1, 1, 2]) s2 = Sphere(1.59, .5, [1, 3, 2]) sc = Spheres([s1, s2]) assert_read_matches_write(sc)
def test_optimization_with_maxiter_of_2(): gold_fit_dict = { '0:r': 0.52480509800531849, '1:center.1': 14.003687569304704, 'alpha': 0.93045027963762217, '0:center.2': 19.93177549652841, '1:r': 0.56292664494653732, '0:center.1': 15.000340621607815, '1:center.0': 14.020984607646726, '0:center.0': 15.000222185576494, '1:center.2': 20.115613202192328 } #calculate a hologram with known particle positions to do a fit against schema = detector_grid(shape=100, spacing=.1) s1 = Sphere(center=(15, 15, 20), n=1.59, r=0.5) s2 = Sphere(center=(14, 14, 20), n=1.59, r=0.5) cluster = Spheres([s1, s2]) holo = calc_holo(schema, cluster, 1.33, .66, illum_polarization=(1, 0)) #trying to do a fast fit: guess1 = Sphere(center=(prior.Uniform(5, 25, guess=15), prior.Uniform(5, 25, 15), prior.Uniform(5, 25, 20)), r=(prior.Uniform(.4, .6, guess=.45)), n=1.59) guess2 = Sphere(center=(prior.Uniform(5, 25, guess=14), prior.Uniform(5, 25, 14), prior.Uniform(5, 25, 20)), r=(prior.Uniform(.4, .6, guess=.45)), n=1.59) par_s = Spheres([guess1, guess2]) model = AlphaModel(par_s, medium_index=1.33, illum_wavelen=.66, illum_polarization=(1, 0), alpha=prior.Uniform(.1, 1, .6)) optimizer = Nmpfit(maxiter=2) with warnings.catch_warnings(): warnings.simplefilter('ignore') result = optimizer.fit(model, holo) assert_obj_close(gold_fit_dict, result.parameters, rtol=1e-5)
def test_Composite_tying(): # tied parameters n1 = Uniform(1.59, 1.6, guess=1.59) sc = Spheres([ Sphere(n=n1, r=Uniform(0.5, 0.7), center=np.array([10., 10., 20.])), Sphere(n=n1, r=Uniform(0.5, 0.7), center=np.array([9., 11., 21.])) ]) assert_equal(len(sc.parameters), 9) assert_equal(sc.parameters['n'].guess, 1.59) assert_equal(sc.parameters['0:r'], sc.parameters['1:r'])
def test_save_and_open(self): n = Uniform(0, 1) r = Uniform(0, np.pi / 2) spheres = [Sphere(n=n, r=r, center=[i, i, i]) for i in range(3)] spheres = Spheres(spheres) expected_keys = spheres.parameters.keys() with tempfile.TemporaryDirectory() as tempdir: hp.save(tempdir + '/test.out', spheres) spheres = hp.load(tempdir + '/test.out') self.assertEqual(spheres.parameters.keys(), expected_keys)
def test_tied_if_same_object(self): n = Uniform(0, 1) r = Uniform(0, 1) spheres = [Sphere(n=n, r=r, center=[i, i, i]) for i in range(3)] spheres = Spheres(spheres) expected_keys = { 'n', 'r', '0:center.0', '0:center.1', '0:center.2', '1:center.0', '1:center.1', '1:center.2', '2:center.0', '2:center.1', '2:center.2' } self.assertEqual(set(spheres.parameters.keys()), expected_keys)
def test_tied_parameter_naming(self): n = Uniform(0, 1) r = [Uniform(0, 1), Uniform(0, 1)] spheres = [Sphere(n=n, r=r[i % 2]) for i in range(4)] spheres = Spheres(spheres) expected_ties = { 'n': ['0:n', '1:n', '2:n', '3:n'], 'r': ['0:r', '2:r'], '1:r': ['1:r', '3:r'] } self.assertEqual(spheres.ties, expected_ties)
def test_2_sph(): sc = Spheres(scatterers=[ Sphere(center=[7.1e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07), Sphere(center=[6e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07) ]) holo = calc_holo(schema, sc, theory=Multisphere, scaling=.6) assert_obj_close(holo.max(), 1.4140292298443309) assert_obj_close(holo.mean(), 0.9955420925817654) assert_obj_close(holo.std(), 0.09558537595025796)
def test_raw_parameters(self): max_radius = np.sqrt(3) / 2.0 spheres = [ Sphere(n=np.random.rand(), r=np.random.rand() * max_radius, center=[i, i, i]) for i in range(3) ] spheres = Spheres(spheres) expected_keys = { '0:n', '1:n', '2:n', '0:r', '1:r', '2:r', '0:center.0', '0:center.1', '0:center.2', '1:center.0', '1:center.1', '1:center.2', '2:center.0', '2:center.1', '2:center.2' } self.assertEqual(set(spheres.raw_parameters.keys()), expected_keys)