def test_calculate_scattering_matrix_has_correct_s1s2s3s4_labels(self): theory = Mie() scat_matrs = theory.calculate_scattering_matrix(SPHERE, SCAT_SCHEMA) epar_coords = scat_matrs.coords['Epar'].values eperp_coords = scat_matrs.coords['Eperp'].values self.assertTrue(np.all(epar_coords == np.array(['S2', 'S3']))) self.assertTrue(np.all(eperp_coords == np.array(['S4', 'S1'])))
def test_calculate_scattering_matrix_has_correct_spherical_coords(self): theory = Mie() scat_matrs = theory.calculate_scattering_matrix(SPHERE, SCAT_SCHEMA) true_r = np.array([ 2., 2.00249844, 2.00997512, 2.02237484, 2.03960781, 2.00249844, 2.00499377, 2.01246118, 2.02484567, 2.04205779, 2.00997512, 2.01246118, 2.01990099, 2.03224014, 2.04939015, 2.02237484, 2.02484567, 2.03224014, 2.04450483, 2.06155281, 2.03960781, 2.04205779, 2.04939015, 2.06155281, 2.07846097 ]) true_theta = np.array([ 0., 0.0499584, 0.09966865, 0.14888995, 0.19739556, 0.0499584, 0.07059318, 0.11134101, 0.15681569, 0.20330703, 0.09966865, 0.11134101, 0.1404897, 0.17836178, 0.21998798, 0.14888995, 0.15681569, 0.17836178, 0.2090333, 0.24497866, 0.19739556, 0.20330703, 0.21998798, 0.24497866, 0.2756428 ]) true_phi = np.array([ 0., 1.57079633, 1.57079633, 1.57079633, 1.57079633, 0., 0.78539816, 1.10714872, 1.24904577, 1.32581766, 0., 0.46364761, 0.78539816, 0.98279372, 1.10714872, 0., 0.32175055, 0.5880026, 0.78539816, 0.92729522, 0., 0.24497866, 0.46364761, 0.64350111, 0.78539816 ]) packed_r = scat_matrs.coords['r'].values packed_theta = scat_matrs.coords['theta'].values packed_phi = scat_matrs.coords['phi'].values self.assertTrue(np.allclose(true_r, packed_r, **MEDTOLS)) self.assertTrue(np.allclose(true_theta, packed_theta, **MEDTOLS)) self.assertTrue(np.allclose(true_phi, packed_phi, **MEDTOLS))
def test_raw_scat_matrs_same_as_mie(self): theory_mie = Mie() theory_tmat = Tmatrix() pos = np.array([10, 0, 0])[:,None] s = Sphere(n=1.59, r=0.9, center=(2, 2, 80)) s_mie = theory_mie._raw_scat_matrs(s, pos, 2*np.pi/.660, 1.33) s_tmat = theory_tmat._raw_scat_matrs(s, pos, 2*np.pi/.660, 1.33) self.assertTrue(np.allclose(s_mie, s_tmat))
def test_raw_fields_similar_to_mie(self): theory_mie = Mie(False, False) theory_tmat = Tmatrix() pos = np.array([10, 0, 0])[:,None] s = Sphere(n=1.59, r=0.9, center=(2, 2, 80)) pol = pd.Series([1, 0]) fields_mie = theory_mie._raw_fields(pos, s, 2*np.pi/.660, 1.33, pol) fields_tmat = theory_tmat._raw_fields(pos, s, 2*np.pi/.660, 1.33, pol) self.assertTrue(np.allclose(fields_mie, fields_tmat))
def test_fit_superposition(): """ Fit Mie superposition to a calculated hologram from two spheres """ # Make a test hologram optics = Optics(wavelen=6.58e-07, index=1.33, polarization=[0.0, 1.0], divergence=0, spacing=None, train=None, mag=None, pixel_scale=[2 * 2.302e-07, 2 * 2.302e-07]) s1 = Sphere(n=1.5891 + 1e-4j, r=.65e-6, center=(1.56e-05, 1.44e-05, 15e-6)) s2 = Sphere(n=1.5891 + 1e-4j, r=.65e-6, center=(3.42e-05, 3.17e-05, 10e-6)) sc = Spheres([s1, s2]) alpha = .629 theory = Mie(optics, 100) holo = theory.calc_holo(sc, alpha) # Now construct the model, and fit parameters = [ Parameter(name='x0', guess=1.6e-5, limit=[0, 1e-4]), Parameter('y0', 1.4e-5, [0, 1e-4]), Parameter('z0', 15.5e-6, [0, 1e-4]), Parameter('r0', .65e-6, [0.6e-6, 0.7e-6]), Parameter('nr', 1.5891, [1, 2]), Parameter('x1', 3.5e-5, [0, 1e-4]), Parameter('y1', 3.2e-5, [0, 1e-4]), Parameter('z1', 10.5e-6, [0, 1e-4]), Parameter('r1', .65e-6, [0.6e-6, 0.7e-6]) ] def make_scatterer(x0, x1, y0, y1, z0, z1, r0, r1, nr): s = Spheres([ Sphere(center=(x0, y0, z0), r=r0, n=nr + 1e-4j), Sphere(center=(x1, y1, z1), r=r1, n=nr + 1e-4j) ]) return s model = Model(parameters, Mie, make_scatterer=make_scatterer, alpha=Parameter('alpha', .63, [.5, 0.8])) result = fit(model, holo) assert_obj_close(result.scatterer, sc) assert_approx_equal(result.alpha, alpha, significant=4) assert_equal(result.model, model) assert_read_matches_write(result)
def test_calc_field(): s = Sphere(n=1.59, r=.5, center=(0, 0, 1)) t = update_metadata(detector_grid(shape=(2, 2), spacing=.1), illum_wavelen=0.66, medium_index=1.33, illum_polarization=(1, 0)) thry = Mie(False) f = calc_field(t, s, 1.33, .66, (1, 0), theory=thry) assert_obj_close(t.attrs, f.attrs) gold = xr.DataArray(np.array([[[ -3.95866810e-01 + 2.47924378e+00j, 0.00000000e+00 + 0.00000000e+00j, 0.00000000e+00 - 0.00000000e+00j ], [ -4.91260953e-01 + 2.32779296e+00j, 9.21716363e-20 - 5.72226912e-19j, 2.99878926e-18 - 1.41959276e-17j ]], [[ -4.89755627e-01 + 2.31844748e+00j, 0.00000000e+00 + 0.00000000e+00j, 4.89755627e-02 - 2.31844748e-01j ], [ -5.71886751e-01 + 2.17145168e+00j, 1.72579090e-03 - 8.72241140e-03j, 5.70160960e-02 - 2.16272927e-01j ]]]), dims=['x', 'y', 'vector'], coords={ 'x': t.x, 'y': t.y, 'vector': ['x', 'y', 'z'] }) assert abs((f - gold).max()) < 5e-9
def test_fit_mie_single(): holo = normalize(get_example_data('image0001.yaml')) parameters = [ Parameter(name='x', guess=.567e-5, limit=[0.0, 1e-5]), Parameter(name='y', guess=.576e-5, limit=[0, 1e-5]), Parameter(name='z', guess=15e-6, limit=[1e-5, 2e-5]), Parameter(name='n', guess=1.59, limit=[1, 2]), Parameter(name='r', guess=8.5e-7, limit=[1e-8, 1e-5]) ] def make_scatterer(x, y, z, r, n): return Sphere(n=n + 1e-4j, r=r, center=(x, y, z)) thry = Mie(False) model = Model(Parametrization(make_scatterer, parameters), thry.calc_holo, alpha=Parameter(name='alpha', guess=.6, limit=[.1, 1])) assert_raises(InvalidMinimizer, fit, model, holo, minimizer=Sphere) result = fit(model, holo) assert_obj_close(result.scatterer, gold_sphere, rtol=1e-3) assert_approx_equal(result.parameters['alpha'], gold_alpha, significant=3) assert_equal(model, result.model)
def test_dda_fit(): s = Sphere(n=1.59, r=.2, center=(5, 5, 5)) o = Optics(wavelen=.66, index=1.33, pixel_scale=.1) schema = ImageSchema(optics=o, shape=100) h = Mie.calc_holo(s, schema) def make_scatterer(r, x, y, z): local_s = Sphere(r=r, center=(x, y, z)) return Scatterer(local_s.indicators, n=s.n) parameters = [ par(.18, [.1, .3], name='r', step=.1), par(5, [4, 6], 'x'), par(5, [4, 6], 'y'), par(5.2, [4, 6], 'z') ] p = Parametrization(make_scatterer, parameters) model = Model(p, DDA.calc_holo) res = fit(model, h) assert_parameters_allclose(res.parameters, dict([('r', 0.2003609439787491), ('x', 5.0128083665603995), ('y', 5.0125252883133617), ('z', 4.9775097284878775)]), rtol=1e-3)
def test_serialization(): par_s = Sphere(center=(par(.567e-5, [0, 1e-5]), par(.576e-6, [0, 1e-5]), par(15e-6, [1e-5, 2e-5])), r=par(8.5e-7, [1e-8, 1e-5]), n=par(1.59, [1, 2])) alpha = par(.6, [.1, 1], 'alpha') schema = ImageSchema(shape=100, spacing=.1151e-6, optics=Optics(.66e-6, 1.33)) model = Model(par_s, Mie.calc_holo, alpha=alpha) holo = Mie.calc_holo(model.scatterer.guess, schema, model.alpha.guess) result = fit(model, holo) temp = tempfile.NamedTemporaryFile() save(temp, result) temp.flush() temp.seek(0) loaded = load(temp) assert_obj_close(result, loaded, context='serialized_result')
def test_Mie_multiple(): s1 = Sphere(n = 1.59, r = 5e-7, center = (1e-6, -1e-6, 10e-6)) s2 = Sphere(n = 1.59, r = 1e-6, center=[8e-6,5e-6,5e-6]) s3 = Sphere(n = 1.59+0.0001j, r = 5e-7, center=[5e-6,10e-6,3e-6]) sc = Spheres(scatterers=[s1, s2, s3]) thry = Mie(False) schema = yschema fields = calc_field(schema, sc, index, wavelen, ypolarization, thry) verify(fields, 'mie_multiple_fields') calc_intensity(schema, sc, index, wavelen, ypolarization, thry) holo = calc_holo(schema, sc, index, wavelen, theory=thry) verify(holo, 'mie_multiple_holo') # should throw exception when fed a ellipsoid el = Ellipsoid(n = 1.59, r = (1e-6, 2e-6, 3e-6), center=[8e-6,5e-6,5e-6]) with assert_raises(TheoryNotCompatibleError) as cm: calc_field(schema, el, index, wavelen, theory=Mie) assert_equal(str(cm.exception), "Mie scattering theory can't handle " "scatterers of type Ellipsoid") assert_raises(TheoryNotCompatibleError, calc_field, schema, el, index, wavelen, xpolarization, Mie) assert_raises(TheoryNotCompatibleError, calc_intensity, schema, el, index, wavelen, xpolarization, Mie) assert_raises(TheoryNotCompatibleError, calc_holo, schema, el, index, wavelen, xpolarization, Mie)
def test_radialEscat(): thry_1 = Mie() thry_2 = Mie(False) sphere = Sphere(r = 1e-6, n = 1.4 + 0.01j, center = [10e-6, 10e-6, 1.2e-6]) h1 = calc_holo(xschema, sphere, index, wavelen, illum_polarization=xpolarization) h2 = calc_holo(xschema, sphere, index, wavelen, illum_polarization=xpolarization, theory=thry_2) try: assert_array_almost_equal(h1, h2, decimal=12) except AssertionError: pass # no way to do "assert array not equal" in numpy.testing else: raise AssertionError("Holograms w/ and w/o full radial fields" + " are exactly equal")
def calculateHologram(self): #calculate hologram with current settings self.warning.setText('Calculating...') #self.compute.setChecked(True) scale = self.scale sender = self.sender() ######## hologram calculation (4x big to allow scrolling) start = time.time() sphere = Sphere(n = self.lcd5.value()+.0001j, r = self.lcd4.value(), center = (256*self.scale,256*self.scale,self.lcd3.value())) sphere2 = Sphere(n = self.lcd5.value()+.0001j, r = self.lcd4.value(), center = (self.lcd.value(),self.lcd2.value(),self.lcd3.value())) self.sphObject.setText(repr(sphere2)) schema = ImageSchema(shape = 512, spacing = float(self.pxsizeText.text()), optics = Optics(wavelen = float(self.waveText.text()), index = float(self.mindexText.text()), polarization = [1,0])) schema2 = ImageSchema(shape = 256, spacing = float(self.pxsizeText.text()), optics = Optics(wavelen = float(self.waveText.text()), index = float(self.mindexText.text()), polarization = [1,0])) self.schemaObject.setText(str(repr(schema2))) self.holo = Mie.calc_holo(sphere, schema) self.lastholo = self.holo self.lastZ = self.lcd3.value() end = time.time() #now take only the part that you want to display x = round(self.sld.value()) y = round(self.sld2.value()) im = toimage(self.holo[256-x:512-x,256-y:512-y]) #PIL image #https://github.com/shuge/Enjoy-Qt-Python-Binding/blob/master/image/display_img/pil_to_qpixmap.py #myQtImage = ImageQt(im) #qimage = QtGui.QImage(myQtImage) if im.mode == "RGB": pass elif im.mode == "L": im = im.convert("RGBA") data = im.tostring('raw',"RGBA") qim = QtGui.QImage(data, 256, 256, QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(qim) myScaledPixmap = pixmap.scaled(QtCore.QSize(400,400)) self.warning.setText('') self.hologram.setPixmap(myScaledPixmap) #self.hologram.setScaledContents(True) #myScaledPixmap.scaledToWidth(True) self.timer.setText('Calc. Time: '+str(round(end-start,4))+' s') self.timer.setAlignment(QtCore.Qt.AlignBottom | QtCore.Qt.AlignCenter)
def test_transforms_correctly_with_polarization_rotation(self): # We test that rotating the lab frame correctly rotates # the polarization. # If we rotate (x0, y0) -> (y1, -x1), then the polarization # in the new coordinates should be # E1x = E0y, E1y = -E1x scatterer = test_common.sphere medium_wavevec = 2 * np.pi / test_common.wavelen medium_index = test_common.index theory = Lens( lens_angle=LENS_ANGLE, theory=Mie(False, False), quad_npts_theta=200, quad_npts_phi=200, ) krho = np.linspace(0, 100, 11) phi_0 = 0 * krho phi_1 = np.full_like(krho, -np.pi / 2) kz = np.full_like(krho, 20.0) pol_0 = xr.DataArray([1.0, 0, 0]) pos_0 = np.array([krho, phi_0, kz]) pol_1 = xr.DataArray([0, -1.0, 0]) pos_1 = np.array([krho, phi_1, kz]) args = (scatterer, medium_wavevec, medium_index) fields_0 = theory._raw_fields(pos_0, *args, pol_0) fields_1 = theory._raw_fields(pos_1, *args, pol_1) tols = {'atol': 1e-5, 'rtol': 1e-5} assert_allclose(fields_1[0], fields_0[1], **tols) assert_allclose(fields_1[1], -fields_0[0], **tols)
def determine_default_theory_for(scatterer): if isinstance(scatterer, Sphere): theory = Mie() elif isinstance(scatterer, Spheres): if all([np.isscalar(scat.r) for scat in scatterer.scatterers]): theory = Multisphere() else: warn("HoloPy's multisphere theory can't handle coated spheres." + "Using Mie theory.") theory = Mie() elif isinstance(scatterer, Spheroid) or isinstance(scatterer, Cylinder): theory = Tmatrix() elif DDA()._can_handle(scatterer): theory = DDA() else: raise AutoTheoryFailed(scatterer) return theory
def test_calc_holo(): s = Sphere(n=1.59, r=.5, center=(0, 0, 1)) t = detector_grid(shape=(2, 2), spacing=.1) thry = Mie(False) h = calc_holo(t, s, 1.33, .66, (1, 0), theory=thry) assert_allclose( h, np.array([[[6.51162661], [5.67743548]], [[5.63554802], [4.89856241]]]))
def test_layered(): s = Sphere(n = (1,2), r = (1, 2), center = (2, 2, 2)) sch = ImageSchema((10, 10), .2, Optics(.66, 1, (1, 0))) hs = Mie.calc_holo(s, sch) guess = hp.scattering.scatterer.sphere.LayeredSphere((1,2), (par(1.01), par(.99)), (2, 2, 2)) model = Model(guess, Mie.calc_holo) res = fit(model, hs) assert_allclose(res.scatterer.t, (1, 1), rtol = 1e-12)
def test_fit_superposition(): """ Fit Mie superposition to a calculated hologram from two spheres """ # Make a test hologram optics = Optics(wavelen=6.58e-07, index=1.33, polarization=[0.0, 1.0], divergence=0, spacing=None, train=None, mag=None, pixel_scale=[2*2.302e-07, 2*2.302e-07]) s1 = Sphere(n=1.5891+1e-4j, r = .65e-6, center=(1.56e-05, 1.44e-05, 15e-6)) s2 = Sphere(n=1.5891+1e-4j, r = .65e-6, center=(3.42e-05, 3.17e-05, 10e-6)) sc = Spheres([s1, s2]) alpha = .629 theory = Mie(optics, 100) holo = theory.calc_holo(sc, alpha) # Now construct the model, and fit parameters = [Parameter(name = 'x0', guess = 1.6e-5, limit = [0, 1e-4]), Parameter('y0', 1.4e-5, [0, 1e-4]), Parameter('z0', 15.5e-6, [0, 1e-4]), Parameter('r0', .65e-6, [0.6e-6, 0.7e-6]), Parameter('nr', 1.5891, [1, 2]), Parameter('x1', 3.5e-5, [0, 1e-4]), Parameter('y1', 3.2e-5, [0, 1e-4]), Parameter('z1', 10.5e-6, [0, 1e-4]), Parameter('r1', .65e-6, [0.6e-6, 0.7e-6])] def make_scatterer(x0, x1, y0, y1, z0, z1, r0, r1, nr): s = Spheres([ Sphere(center = (x0, y0, z0), r=r0, n = nr+1e-4j), Sphere(center = (x1, y1, z1), r=r1, n = nr+1e-4j)]) return s model = Model(parameters, Mie, make_scatterer=make_scatterer, alpha = Parameter('alpha', .63, [.5, 0.8])) result = fit(model, holo) assert_obj_close(result.scatterer, sc) assert_approx_equal(result.alpha, alpha, significant=4) assert_equal(result.model, model) assert_read_matches_write(result)
def calc_model(cls, data, params, theory_type='mielens'): scatterer = cls._make_scatterer(params) if theory_type == 'mielens': theory = MieLens(lens_angle=params['lens_angle']) scaling = 1.0 else: theory = Mie() scaling = params['alpha'] model = calc_holo(data, scatterer, theory=theory, scaling=scaling) return model
def test_calc_holo_theta_npts_not_equal_phi_npts(self): scatterer = test_common.sphere pts = detector_grid(shape=4, spacing=test_common.pixel_scale) pts = update_metadata(pts, illum_wavelen=test_common.wavelen, medium_index=test_common.index, illum_polarization=test_common.xpolarization) theory = Lens(LENS_ANGLE, Mie(), quad_npts_theta=8, quad_npts_phi=10) holo = calc_holo(pts, scatterer, theory=theory) self.assertTrue(True)
def _get_theory_and_scaling(self, params): if self.theory == 'mielens': theory = MieLens(lens_angle=params['lens_angle']) # 0.0015 ms scaling = 1.0 elif self.theory == 'mieonly': theory = Mie() scaling = params['alpha'] elif self.theory == 'mielensalpha': theory = MieLens(lens_angle=params['lens_angle']) # 0.0015 ms scaling = params['alpha'] return theory, scaling
def test_calculate_scattering_matrix_has_correct_cartesian_coords(self): theory = Mie() scat_matrs = theory.calculate_scattering_matrix(SPHERE, SCAT_SCHEMA) true_x = np.array([ 0., 0., 0., 0., 0., 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.4, 0.4 ]) true_y = np.array([ 0., 0.1, 0.2, 0.3, 0.4, 0., 0.1, 0.2, 0.3, 0.4, 0., 0.1, 0.2, 0.3, 0.4, 0., 0.1, 0.2, 0.3, 0.4, 0., 0.1, 0.2, 0.3, 0.4 ]) true_z = np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) packed_x = scat_matrs.coords['x'].values packed_y = scat_matrs.coords['y'].values packed_z = scat_matrs.coords['z'].values self.assertTrue(np.allclose(true_x, packed_x, **MEDTOLS)) self.assertTrue(np.allclose(true_y, packed_y, **MEDTOLS)) self.assertTrue(np.allclose(true_z, packed_z, **MEDTOLS))
def test_integer_correctness(): # we keep having bugs where the fitter doesn't schema = ImageSchema(shape = 100, spacing = .1, optics = Optics(wavelen = .660, index = 1.33, polarization = (1, 0))) s = Sphere(center = (10.2, 9.8, 10.3), r = .5, n = 1.58) holo = Mie.calc_holo(s, schema) par_s = Sphere(center = (par(guess = 10, limit = [5,15]), par(10, [5, 15]), par(10, [5, 15])), r = .5, n = 1.58) model = Model(par_s, Mie.calc_holo, alpha = par(.6, [.1, 1])) result = fit(model, holo) assert_allclose(result.scatterer.center, [10.2, 9.8, 10.3])
def test_n(): sph = Sphere(par(.5), 1.6, (5,5,5)) sch = ImageSchema(shape=[100, 100], spacing=[0.1, 0.1], optics=Optics(wavelen=0.66, index=1.33, polarization=[1, 0], divergence=0.0), origin=[0.0, 0.0, 0.0]) model = Model(sph, Mie.calc_holo, alpha=1) holo = Mie.calc_holo(model.scatterer.guess, sch) coster = CostComputer(holo, model, use_random_fraction=.1) assert_allclose(coster.flattened_difference({'n' : .5}), 0)
def test_calc_intensity(): s = Sphere(n=1.59, r=.5, center=(0, 0, 1)) t = detector_grid(shape=(2, 2), spacing=.1) thry = Mie(False) i = calc_intensity(t, s, illum_wavelen=.66, medium_index=1.33, illum_polarization=(1, 0), theory=thry) assert_allclose( i, np.array([[[6.30336023], [5.65995739]], [[5.61505927], [5.04233591]]]))
def test_n(): sph = Sphere(par(.5), 1.6, (5,5,5)) sch = ImageSchema(shape=[100, 100], spacing=[0.1, 0.1], optics=Optics(wavelen=0.66, index=1.33, polarization=[1, 0], divergence=0.0), origin=[0.0, 0.0, 0.0]) model = Model(sph, Mie.calc_holo, alpha=1) holo = Mie.calc_holo(model.scatterer.guess, sch) coster = CostComputer(holo, model, random_subset=.1) assert_allclose(coster.flattened_difference({'n' : .5}), 0)
def evaluate_model(self, params): scatterer = self.make_scatterer(params) if self.theory == 'mieonly': theory = Mie() else: theory = MieLens(lens_angle=params['lens_angle']) if self.theory == 'mielens': scaling = 1.0 else: scaling = params['alpha'] model = calc_holo(self.data, scatterer, theory=theory, scaling=scaling) return model
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)]])
def test_single_sphere(): # single sphere hologram (only tests that functions return) thry = Mie(False) holo = calc_holo(xschema, sphere, index, wavelen, xpolarization, theory=thry, scaling=scaling_alpha) field = calc_field(xschema, sphere, index, wavelen, xpolarization, theory=thry) intensity = calc_intensity(xschema, sphere, medium_index=index, illum_wavelen=wavelen, illum_polarization=xpolarization, theory=thry) verify(holo, 'single_holo') verify(field, 'single_field') # now test some invalid scatterers and confirm that it rejects calculating # for them # large radius (calculation not attempted because it would take forever assert_raises(InvalidScatterer, calc_holo, xschema, Sphere(r=1, n = 1.59, center = (5,5,5)), medium_index=index, illum_wavelen=wavelen)
def test_fit_single_openopt(): holo = normalize(get_example_data('image0001.yaml')) s = Sphere(center = (par(guess=.567e-5, limit=[.4e-5,.6e-5]), par(.567e-5, (.4e-5, .6e-5)), par(15e-6, (1.3e-5, 1.8e-5))), r = par(8.5e-7, (5e-7, 1e-6)), n = ComplexParameter(par(1.59, (1.5,1.8)), 1e-4j)) model = Model(s, Mie(False).calc_holo, alpha = par(.6, [.1,1])) try: minimizer = OpenOpt('scipy_slsqp') except ImportError: raise SkipTest result = fit(model, holo, minimizer = minimizer) assert_obj_close(result.scatterer, gold_sphere, rtol=1e-3) # TODO: see if we can get this back to 3 sig figs correct alpha assert_approx_equal(result.parameters['alpha'], gold_alpha, significant=3) assert_equal(model, result.model)
def test_fit_mie_par_scatterer(): holo = normalize(get_example_data('image0001.yaml')) s = Sphere(center = (par(guess=.567e-5, limit=[0,1e-5]), par(.567e-5, (0, 1e-5)), par(15e-6, (1e-5, 2e-5))), r = par(8.5e-7, (1e-8, 1e-5)), n = ComplexParameter(par(1.59, (1,2)), 1e-4j)) thry = Mie(False) model = Model(s, thry.calc_holo, alpha = par(.6, [.1,1])) result = fit(model, holo) assert_obj_close(result.scatterer, gold_sphere, rtol=1e-3) # TODO: see if we can get this back to 3 sig figs correct alpha assert_approx_equal(result.parameters['alpha'], gold_alpha, significant=3) assert_equal(model, result.model) assert_read_matches_write(result)
def test_fit_random_subset(): holo = normalize(get_example_data('image0001.yaml')) s = Sphere(center=(par(guess=.567e-5, limit=[0, 1e-5]), par(.567e-5, (0, 1e-5)), par(15e-6, (1e-5, 2e-5))), r=par(8.5e-7, (1e-8, 1e-5)), n=ComplexParameter(par(1.59, (1, 2)), 1e-4)) model = Model(s, Mie(False).calc_holo, alpha=par(.6, [.1, 1])) np.random.seed(40) result = fit(model, holo, random_subset=.1) # TODO: this tolerance has to be rather large to pass, we should # probably track down if this is a sign of a problem assert_obj_close(result.scatterer, gold_sphere, rtol=1e-2) # TODO: figure out if it is a problem that alpha is frequently coming out # wrong in the 3rd decimal place. assert_approx_equal(result.parameters['alpha'], gold_alpha, significant=3) assert_equal(model, result.model) assert_read_matches_write(result)
def test_mie_polarization(): # test holograms for orthogonal polarizations; make sure they're # not the same, nor too different from one another. thry = Mie(False) xholo = calc_holo(xschema, sphere, index, wavelen, illum_polarization=xpolarization, scaling=scaling_alpha) yholo = calc_holo(yschema, sphere, index, wavelen, illum_polarization=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_dda_fit(): s = Sphere(n = 1.59, r = .2, center = (5, 5, 5)) o = Optics(wavelen = .66, index=1.33, pixel_scale=.1) schema = ImageSchema(optics = o, shape = 100) h = Mie.calc_holo(s, schema) def make_scatterer(r, x, y, z): local_s = Sphere(r = r, center = (x, y, z)) return Scatterer(local_s.indicators, n = s.n) parameters = [par(.18, [.1, .3], name='r', step=.1), par(5, [4, 6], 'x'), par(5, [4,6], 'y'), par(5.2, [4, 6], 'z')] p = Parametrization(make_scatterer, parameters) model = Model(p, DDA.calc_holo) res = fit(model, h) assert_parameters_allclose(res.parameters, OrderedDict([('r', 0.2003609439787491), ('x', 5.0128083665603995), ('y', 5.0125252883133617), ('z', 4.9775097284878775)]), rtol=1e-3)
def test_serialization(): par_s = Sphere(center = (par(.567e-5, [0, 1e-5]), par(.576e-6, [0, 1e-5]), par(15e-6, [1e-5, 2e-5])), r = par(8.5e-7, [1e-8, 1e-5]), n = par(1.59, [1,2])) alpha = par(.6, [.1, 1], 'alpha') schema = ImageSchema(shape = 100, spacing = .1151e-6, optics = Optics(.66e-6, 1.33)) model = Model(par_s, Mie.calc_holo, alpha=alpha) holo = Mie.calc_holo(model.scatterer.guess, schema, model.alpha.guess) result = fit(model, holo) temp = tempfile.NamedTemporaryFile() save(temp, result) temp.flush() temp.seek(0) loaded = load(temp) assert_obj_close(result, loaded, context = 'serialized_result')
import scipy from holopy.scattering.scatterer import Sphere, Spheres from holopy.core import ImageSchema, Optics from holopy.scattering.theory import Mie import matplotlib.pyplot as plt sphere = Sphere(n = 1.59+.0001j, r = .5, center = (4, 3, 5)) schema = ImageSchema(shape = 100, spacing = .1, optics = Optics(wavelen = .660, index = 1.33, polarization = [1,0])) s1 = Sphere(center=(5, 5, 5), n = 1.59, r = .5) s2 = Sphere(center=(4, 4, 5), n = 1.59, r = .5) collection = Spheres([s1, s2]) holo = Mie.calc_holo(collection, schema) scipy.misc.imsave('holoTest.png',holo) plt.imshow(holo) plt.show()
import holopy as hp from holopy.scattering.scatterer import Sphere from holopy.scattering.theory import Mie from holopy.core import ImageSchema, Optics schema = ImageSchema(shape = 100, spacing = .1, optics = Optics(wavelen = .660, index = 1.33, polarization = [1,0])) cs = Sphere(center=(2.5, 5, 5), n = (1.59, 1.42),\ r = (0.3, 0.6)) holo = Mie.calc_holo(cs, schema) hp.show(holo)
import matplotlib.pyplot as plt import numpy as np from holopy.core import Schema, Angles, Optics from holopy.scattering.scatterer import Sphere from holopy.scattering.theory import Mie schema = Schema( positions=Angles(np.linspace(0, np.pi, 100)), optics=Optics(wavelen=0.66, index=1.33, polarization=(1, 0)) ) sphere = Sphere(r=0.5, n=1.59) matr = Mie.calc_scat_matrix(sphere, schema) # It is typical to look at scattering matrices on a semilog plot. # You can make one as follows: plt.figure() plt.semilogy(np.linspace(0, np.pi, 100), abs(matr[:, 0, 0]) ** 2) plt.semilogy(np.linspace(0, np.pi, 100), abs(matr[:, 1, 1]) ** 2) plt.show()
def calculateHologram(self): # calculate hologram with current settings self.warning.setText("Calculating...") # self.compute.setChecked(True) scale = self.scale sender = self.sender() ######## hologram calculation (4x big to allow scrolling) start = time.time() sphere = Sphere( n=self.lcd5.value() + 0.0001j, r=self.lcd4.value(), center=(256 * self.scale, 256 * self.scale, self.lcd3.value()), ) sphere2 = Sphere( n=self.lcd5.value() + 0.0001j, r=self.lcd4.value(), center=(self.lcd.value(), self.lcd2.value(), self.lcd3.value()), ) self.sphObject.setText(repr(sphere2)) schema = ImageSchema( shape=512, spacing=float(self.pxsizeText.text()), optics=Optics( wavelen=float(self.waveText.text()), index=float(self.mindexText.text()), polarization=[1, 0] ), ) schema2 = ImageSchema( shape=256, spacing=float(self.pxsizeText.text()), optics=Optics( wavelen=float(self.waveText.text()), index=float(self.mindexText.text()), polarization=[1, 0] ), ) self.schemaObject.setText(str(repr(schema2))) self.holo = Mie.calc_holo(sphere, schema) self.lastholo = self.holo self.lastZ = self.lcd3.value() end = time.time() # now take only the part that you want to display x = round(self.sld.value()) y = round(self.sld2.value()) im = toimage(self.holo[256 - x : 512 - x, 256 - y : 512 - y]) # PIL image # https://github.com/shuge/Enjoy-Qt-Python-Binding/blob/master/image/display_img/pil_to_qpixmap.py # myQtImage = ImageQt(im) # qimage = QtGui.QImage(myQtImage) if im.mode == "RGB": pass elif im.mode == "L": im = im.convert("RGBA") data = im.tostring("raw", "RGBA") qim = QtGui.QImage(data, 256, 256, QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(qim) myScaledPixmap = pixmap.scaled(QtCore.QSize(400, 400)) self.warning.setText("") self.hologram.setPixmap(myScaledPixmap) # self.hologram.setScaledContents(True) # myScaledPixmap.scaledToWidth(True) self.timer.setText("Calc. Time: " + str(round(end - start, 4)) + " s") self.timer.setAlignment(QtCore.Qt.AlignBottom | QtCore.Qt.AlignCenter)
import holopy as hp from holopy.scattering.scatterer import Sphere from holopy.core import ImageSchema, Optics from holopy.scattering.theory import Mie sphere = Sphere(n = 1.59+.0001j, r = .5, center = (4, 3, 5)) schema = ImageSchema(shape = 100, spacing = .1, optics = Optics(wavelen = .660, index = 1.33, polarization = [1,0])) holo = Mie.calc_holo(sphere, schema) hp.show(holo)
def calculateHologram(self): #calculate hologram with current settings #schema is generic to all scattering theories schema = ImageSchema(shape = [int(self.heightText.text()),int(self.widthText.text())], spacing = float(self.pxsizeText.text()), optics = Optics(wavelen = float(self.waveText.text()), index = float(self.mindexText.text()), polarization = [1.0,0.0])) self.schemaObject.setText(str(repr(schema))) #first sphere is general for both single sphere and two sphere cases sphere = Sphere(n = self.lcd5.value()+.0001j, r = self.lcd4.value(), center = (self.lcd.value(),self.lcd2.value(),self.lcd3.value())) if self.reconstruct.isChecked(): self.slideZ(sphere, schema) start = end = 0 #fake time since reconstruction time is odd to keep track of here else: scale = self.scale sender = self.sender() start = time.time() if self.onesphere.checkState() == 2: self.sphObject.setText(repr(sphere)) #we have two theories to choose from for computing single sphere holograms if sphere.parameters != self.oldscattererparameters: #when changing parameters, always use GPU because it's fast enough self.gpu.toggle() if self.cpu.isChecked(): if sphere.parameters == self.oldMieCPUparameters and repr(schema) == repr(self.oldMieCPUschema): self.holo = self.oldMieCPUHolo print 'loaded cached mie hologram' else: self.holo = Mie.calc_holo(sphere,schema) print 'freshly calculated mie hologram' self.oldMieCPUHolo = self.holo self.oldMieCPUparameters = sphere.parameters self.oldMieCPUschema = schema else: if sphere.parameters == self.oldscattererparameters and repr(schema) == repr(self.oldMieGPUschema): self.holo = self.oldMieGPUHolo print 'loaded cached GPU hologram' else: self.holo = gpuMie.calc_holo(sphere, schema) self.oldMieGPUHolo = self.holo self.oldscattererparameters = sphere.parameters self.oldMieGPUschema = schema self.oldscatterer = sphere self.oldschema = schema else: #we have three theories to choose from for computing single sphere holograms s1 = sphere s2 = Sphere(n = self.lcd5.value()+.0001j, r = self.lcd4.value(), center = (self.lcd7.value(),self.lcd8.value(),self.lcd9.value())) cluster = Spheres([s1, s2]) self.sphObject.setText(repr(cluster)) if cluster.parameters != self.oldscatterer.parameters: self.gpu.toggle() if self.cpu.isChecked(): if cluster.parameters == self.oldMieCPUparameters and repr(schema) == repr(self.oldMieCPUschema): self.holo = self.oldMieCPUHolo print 'loaded cached CPU superposition hologram' else: self.holo = Mie.calc_holo(cluster, schema) self.oldMieCPUHolo = self.holo self.oldMieCPUschema = schema self.oldMieCPUparameters = cluster.parameters if self.multisphere.isChecked(): if cluster.parameters == self.oldMultiparameters and repr(schema) == repr(self.oldMultischema): self.holo = self.oldMultiHolo print 'loaded cached CPU multisphere hologram' else: self.holo = Multisphere.calc_holo(cluster, schema) self.oldtheory = 'multi' self.oldMultiHolo = self.holo self.oldMultiparameters = cluster.parameters self.oldMultischema = schema print 'multisphere calculation done' if self.gpu.isChecked(): if cluster.parameters == self.oldscattererparameters and repr(schema) == repr(self.oldschema): self.holo = self.oldMieGPUHolo print 'loaded cached GPU hologram' else: self.holo = gpuMie.calc_holo(cluster, schema) self.oldMieGPUHolo = self.holo self.oldschema = schema self.oldscatterer = cluster self.oldscattererparameters = cluster.parameters end = time.time() #display the hologram im = scipy.misc.toimage(self.holo) #PIL image #https://github.com/shuge/Enjoy-Qt-Python-Binding/blob/master/image/display_img/pil_to_qpixmap.py if im.mode == "RGB": pass elif im.mode == "L": im = im.convert("RGBA") data = im.tostring('raw',"RGBA") qim = QtGui.QImage(data, float(self.widthText.text()), float(self.heightText.text()), QtGui.QImage.Format_ARGB32) pixmap = QtGui.QPixmap.fromImage(qim) #set size of displayed image with max width or height = 500 px if float(self.widthText.text()) == float(self.heightText.text()): scaledsize = [500,500] else: if float(self.widthText.text()) > float(self.heightText.text()): scaledsize = [500,500/float(self.widthText.text())*float(self.heightText.text())] else: scaledsize = [500/float(self.heightText.text())*float(self.widthText.text()),500] myScaledPixmap = pixmap.scaled(QtCore.QSize(scaledsize[0],scaledsize[1])) self.warning.setText('') self.label.setPixmap(myScaledPixmap) if end-start > 0.03: self.timer.setText('Calc. Time: '+str(round(end-start,4))+' s') else: self.timer.setText('') if self.lcd3.value()<2*self.lcd4.value() or self.lcd9.value()<2*self.lcd4.value(): self.warning.setText('z < sphere diameter') if self.lcd.value() > float(self.heightText.text())*float(self.pxsizeText.text()): self.warning.setText('x out of range, move slider or increase height') if self.lcd2.value() > float(self.widthText.text())*float(self.pxsizeText.text()): self.warning.setText('y out of range, move slider or increase width') if float(self.pxsizeText.text()) <= 0: self.warning.setText('pixel scale must be greater than 0')