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 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)
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_serialization(): par_s = Sphere(center=(Uniform(0, 1e-5, guess=.567e-5), Uniform(0, 1e-5, .567e-5), Uniform(1e-5, 2e-5)), r=Uniform(1e-8, 1e-5, 8.5e-7), n=Uniform(1, 2, 1.59)) alpha = Uniform(.1, 1, .6, 'alpha') schema = update_metadata(detector_grid(shape=100, spacing=.1151e-6), illum_wavelen=.66e-6, medium_index=1.33, illum_polarization=(1, 0)) model = AlphaModel(par_s, medium_index=schema.medium_index, illum_wavelen=schema.illum_wavelen, alpha=alpha) holo = calc_holo(schema, model.scatterer.guess, scaling=model.alpha.guess) result = fix_flat(NmpfitStrategy().fit(model, holo)) temp = tempfile.NamedTemporaryFile(suffix='.h5', delete=False) with warnings.catch_warnings(): warnings.simplefilter('ignore') save(temp.name, result) loaded = load(temp.name) assert_obj_close(result, loaded, context='serialized_result')
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 calc_model(self, params, metadata): sphere = self.create_sphere_from(params) # 0.036 ms theory, scaling = self._get_theory_and_scaling(params) if 'illum_wavelen' in params: wavelength = float(params['illum_wavelen']) metadata = update_metadata(metadata, illum_wavelen=wavelength) return calc_holo(metadata, sphere, theory=theory, scaling=scaling)
def compare_fit_holo(data, fit_scatterer, fit_lens_angle): guess_holo = hologram2array( calc_holo(data, fit_scatterer, theory=MieLens(lens_angle=fit_lens_angle))) data_holo = hologram2array(data) compare_imgs(data_holo, guess_holo, ['Data', 'Model'])
def calc_holo_safe( schema, scatterer, medium_index=None, illum_wavelen=None, **kwargs): try: holo = calc_holo( schema, scatterer, medium_index, illum_wavelen, **kwargs) return holo except DependencyMissing: raise SkipTest()
def calculate_models(data, fits): fitholos = [ calc_holo(datum, fit.scatterer, theory=MieLens(lens_angle=fit.parameters['lens_angle'])) if fit is not None else 0 * datum + 1 for datum, fit in zip(data, fits) ] return fitholos
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 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
def test_layered(): s = Sphere(n=(1, 2), r=(1, 2), center=(2, 2, 2)) sch = detector_grid((10, 10), .2) hs = calc_holo(sch, s, 1, .66, (1, 0)) guess = LayeredSphere((1, 2), (Uniform(1, 1.01), Uniform(.99, 1)), (2, 2, 2)) model = ExactModel(guess, calc_holo) res = NmpfitStrategy().fit(model, hs) assert_allclose(res.scatterer.t, (1, 1), rtol=1e-12)
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 make_fake_data(): detector = holopy.detector_grid([40, 40], spacing=2.878e-7) fake_data = calc_holo( detector, SPHERE, medium_index=1.33, illum_wavelen=6.58e-7, illum_polarization=(1, 0), theory='auto', scaling=CORRECT_ALPHA,) return fake_data
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_n(): sph = Sphere(.5, 1.6, (5, 5, 5)) sch = detector_grid(shape=[100, 100], spacing=[0.1, 0.1]) model = ExactModel(sph, calc_holo, medium_index=1.33, illum_wavelen=.66, illum_polarization=(1, 0)) holo = calc_holo(sch, model.scatterer.guess, 1.33, .66, (1, 0)) assert_allclose(model._residuals({'n': .5}, holo, 1).sum(), 0)
def residfunct(p, fjac=None): # nmpfit calls residfunct w/fjac as a kwarg, we ignore sphere = Sphere(n=p[0] + n_particle_imag * 1j, r=p[1], center=p[2:5]) thry = Mie(False) calculated = calc_holo(holo, sphere, scaling=p[5], theory=thry) status = 0 derivates = holo - calculated return ([status, get_values(flat(derivates))])
def calc_holo_mieonly(center0, center1, center2, n, r, alpha): sph = Sphere(center=(center0, center1, center2), n=n, r=r) camera_resolution = 5.6983 # px / um metadata = { 'spacing': 1 / camera_resolution, 'medium_index': 1.33, 'illum_wavelen': .660, 'illum_polarization': (1, 0) } return calc_holo(hp.load_image('image0029.tif', **metadata), sph, scaling=alpha).values.squeeze()
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_integer_correctness(): # we keep having bugs where the fitter doesn't schema = detector_grid(shape=10, spacing=1) s = Sphere(center=(10.2, 9.8, 10.3), r=.5, n=1.58) holo = calc_holo(schema, s, illum_wavelen=.660, medium_index=1.33, illum_polarization=(1, 0)) par_s = Sphere(r=.5, n=1.58, center=(Uniform(5, 15), Uniform(5, 15), Uniform(5, 15))) model = AlphaModel(par_s, alpha=Uniform(.1, 1, .6)) result = NmpfitStrategy().fit(model, holo) assert_allclose(result.scatterer.center, [10.2, 9.8, 10.3])
def forward(self, metadata, params): x = float(params['x']) y = float(params['y']) z = float(params['z']) n = float(params['n']) # FIXME: Enforce constraints with pryo API min_r = 1e-12 k = 2 * np.pi * metadata.medium_index / metadata.illum_wavelen max_r = 9.99e2 / k r = float(min(max(params['r'], min_r), max_r)) alpha = float(params['alpha']) sph = Sphere(center=(x, y, z), n=n, r=r) mod = calc_holo(metadata, sph, scaling=alpha).values.squeeze() return torch.tensor(mod, dtype=torch.float32)
def sphere(a_p, n_p, z_p): px = int(feature_extent(a_p, n_p, z_p, config)) detector = hp.detector_grid(2 * px, mag) center = (mag * px, mag * px, z_p) s = Sphere(center=center, n=n_p, r=a_p) holo = np.squeeze( calc_holo(detector, s, medium_index=n_m, illum_wavelen=wv, illum_polarization=(1, 0))).data #noise holo += np.random.normal(0., 0.05, holo.shape) return holo
def test_Shell(): s = Sphere( center=[7.141442573813124, 7.160766866147957, 11.095409800342143], n=[(1.27121212428 + 0j), (1.49 + 0j)], r=[0.960957713253 - 0.0055, 0.960957713253]) t = detector_grid(200, .071333) thry = Mie(False) h = calc_holo(t, s, 1.36, .658, illum_polarization=(1, 0), theory=thry, scaling=0.4826042444701572) verify(h, 'shell')
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 make_stack_figures(data, fits, n=None, r=None, z_positions=None): scatterers = [fit.scatterer for fit in fits] z = [fit.scatterer.center[2] for fit in fits] if z_positions is None else z_positions for scatterer, z_pos in zip(scatterers, z): scatterer.n = n if n is not None else scatterer.n scatterer.r = r if r is not None else scatterer.r scatterer.center[ 2] = z_pos if z_positions is not None else scatterer.center[2] model_holos = [ calc_holo(dt, scatterer, theory=MieLens(lens_angle=1.0)) for dt, scatterer in zip(data, scatterers) ] data_stack_xz = np.vstack([dt.values.squeeze()[50, :] for dt in data]) data_stack_yz = np.vstack([dt.values.squeeze()[:, 50] for dt in data]) model_stack_xz = np.vstack( [holo.values.squeeze()[50, :] for holo in model_holos]) model_stack_yz = np.vstack( [holo.values.squeeze()[:, 50] for holo in model_holos]) return data_stack_xz, data_stack_yz, model_stack_xz, model_stack_yz
def test_wrap_sphere(): sphere = Sphere(center=[7.1e-6, 7e-6, 10e-6], n=1.5811 + 1e-4j, r=5e-07) sphere_w = Spheres([sphere]) holo = calc_holo(schema, sphere, theory=Multisphere, scaling=.6) holo_w = calc_holo(schema, sphere_w, theory=Multisphere, scaling=.6) assert_array_equal(holo, holo_w)
from holopy.core.io import get_example_data_path imagepath = get_example_data_path('image0002.h5') exp_img = hp.load(imagepath) """ Qui se vuoi fissare due posizioni specifiche """ sphere1 = Sphere(center=(20, 20, 7), n=1.59, r=0.3) #all in micro m units sphere2 = Sphere(center=(25.6, 25.6, 7), n=1.59, r=0.3) collection = Spheres([sphere1, sphere2]) medium_index = 1.33 illum_wavelength = 0.660 illum_polarization = (1, 0) detector = hp.detector_grid(shape=512, spacing=0.1) #spacing=pix size holo = calc_holo(detector, collection, medium_index, illum_wavelength, illum_polarization) hp.show(holo) """ for look the trasversal profile of hologram centred in partice position plt.title('Hologram') plt.plot(holo[256]) plt.xlabel("Pixel") plt.ylabel("Intensity") plt.title('Holo Intensity') plt.xlim(100, 400) """ """ Qui se vuoi vedere come varia all-avvicinarsi/allontanarsi di una delle due sfere
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 25 13:44:25 2019 @author: claudiaravasio """ import holopy as hp from holopy.scattering import calc_holo, Sphere sphere = Sphere(n=1.59, r=0.3, center=(25.6, 25.6, 7)) medium_index = 1.33 illum_wavelen = 0.660 illum_polarization = (1, 0) detector = hp.detector_grid(shape=512, spacing=0.1) holo = calc_holo(detector, sphere, medium_index, illum_wavelen, illum_polarization) hp.show(holo) #hp.save_image('',holo)
import holopy as hp from holopy.scattering import calc_holo, Sphere sphere = Sphere(n = 1.59, r = .5, center = (4, 4, 5)) detector = hp.detector_grid(shape = 100, spacing = .1) medium_index = 1.33 illum_wavelen = 0.660 illum_polarization = (1,0) from holopy.core.io import get_example_data_path imagepath = get_example_data_path('image01.jpg') exp_img = hp.load_image(imagepath, spacing=0.0851, medium_index=medium_index, illum_wavelen=illum_wavelen, illum_polarization=illum_polarization) exp_img = exp_img[{'x':slice(0,100),'y':slice(0,100)}] from holopy.scattering import Spheres 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 = calc_holo(exp_img, collection) hp.show(holo)
import holopy as hp from holopy.scattering import calc_holo, Sphere sphere = Sphere(n=1.59, r=.5, center=(4, 4, 5)) detector = hp.detector_grid(shape=100, spacing=.1) medium_index = 1.33 illum_wavelen = 0.660 illum_polarization = (1, 0) from holopy.core.io import get_example_data_path imagepath = get_example_data_path('image01.jpg') exp_img = hp.load_image(imagepath, spacing=0.0851, medium_index=medium_index, illum_wavelen=illum_wavelen, illum_polarization=illum_polarization) exp_img = exp_img[{'x': slice(0, 100), 'y': slice(0, 100)}] from holopy.scattering import Spheres 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 = calc_holo(exp_img, collection) hp.show(holo)
import holopy as hp from holopy.scattering import calc_holo, Sphere sphere = Sphere(n = 1.59, r = .5, center = (4, 4, 5)) medium_index = 1.33 illum_wavelen = 0.660 illum_polarization = (1,0) detector = hp.detector_grid(shape = 100, spacing = .1) holo = calc_holo(detector, sphere, medium_index, illum_wavelen, illum_polarization) hp.show(holo)
def trisphere(a_p, n_p, z_p, alpha, theta, phi, check_geom=False): ''' alpha: angle of 3rd monomer wrt dimer -alpha=pi/3: equilateral triangle -alpha between pi/3 and 5pi/3 (no overlaps) theta, phi: rotation angles -theta=0 : aligned along xy plane -theta between 0 and 2pi -phi between 0 and 2pi ''' 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) if alpha < np.pi / 3 or alpha > 5 * np.pi / 3: raise Exception("Invalid value for alpha") #rotation about origin #delta = np.array([np.cos(phi)*np.cos(theta), np.sin(phi)*np.cos(theta), np.sin(theta)]) delta = np.array([1, 0, 0]) #angle of third monomer wrt dimer delta_2 = np.array([-np.cos(alpha), np.sin(alpha), 0]) c1 = 1.001 * a_p * delta c2 = -1.001 * a_p * delta c3 = c1 + 2.001 * a_p * delta_2 cluster = np.array([c1, c2, c3]) #get centroid of trimer and re-center centroid = np.mean(np.array([c1, c2, c3]), axis=0) cluster -= centroid #rotate trimer zax = np.array([0, 0, 1]) xax = np.array([1, 0, 0]) zrot = lambda c: rotate(c, zax, phi) xrot = lambda c: rotate(c, xax, theta) cluster = zrot(cluster) cluster = xrot(cluster) cluster_return = cluster.copy().tolist() #place in particle position cluster += center s1 = Sphere(center=cluster[0], n=n_p, r=a_p) s2 = Sphere(center=cluster[1], n=n_p, r=a_p) s3 = Sphere(center=cluster[2], n=n_p, r=a_p) trimer = Spheres([s1, s2, s3]) r_sum = 4 * a_p if check_geom: #geometry check npix = 60 #npix x npix grid coord_range = np.linspace(mag * px - r_sum, mag * px + r_sum, num=npix) x, y = np.meshgrid(coord_range, coord_range) trimer_points = np.zeros((npix, npix)) for i in range(npix): for j in range(npix): coord = [x[i][j], y[i][j], z_p] if trimer.contains(coord): trimer_points[i][j] = 1 plt.imshow(trimer_points) plt.show() holo = np.squeeze( calc_holo(detector, trimer, medium_index=n_m, illum_wavelen=wv, illum_polarization=(1, 0))).data #noise holo += np.random.normal(0., 0.05, holo.shape) return holo, cluster_return