def test_sim_dyn_save_hdf5(setup_cte_sim, mocker): '''Test that the dynamics solution is saved a loaded correctly''' with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim.states['energy_states'])) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_dynamics() assert mocked.call_count == 2 with temp_bin_filename() as filename: solution.save(filename) sol_hdf5 = simulations.DynamicsSolution.load(filename) assert sol_hdf5 assert sol_hdf5.cte == solution.cte assert np.allclose(sol_hdf5.y_sol, solution.y_sol) assert np.allclose(sol_hdf5.t_sol, solution.t_sol) assert sol_hdf5.index_S_i == solution.index_S_i assert sol_hdf5.index_A_j == solution.index_A_j assert sol_hdf5 == solution sol_hdf5.log_errors() sol_hdf5.plot() plotter.plt.close('all')
def test_sim_conc_dep_dyn(setup_cte_sim, mocker): '''Test that the concentration dependence works''' with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim['states']['energy_states'])) conc_list = [(0, 0.3), (0.1, 0.3), (0.1, 0)] sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_concentration_dependence(conc_list, dynamics=True) # dynamics call solve_ode twice (pulse and relaxation) assert mocked.call_count == 2 * len(conc_list) assert solution solution.plot() solution.log_errors() with temp_config_filename('') as filename: solution.save(filename) sol_hdf5 = simulations.ConcentrationDependenceSolution.load(filename) assert sol_hdf5 assert sol_hdf5 == solution sol_hdf5.plot() plotter.plt.close('all')
def test_sim_power_dep_no_plot(setup_cte_sim, mocker): '''A plot was requested, but no_plot is set''' setup_cte_sim['no_plot'] = True with temp_bin_filename() as temp_filename: mocked = mocker.patch( 'simetuc.simulations.Simulations.simulate_pulsed_steady_state') mocked.return_value = simulations.SteadyStateSolution( np.empty((1000, )), np.empty((1000, 2 * setup_cte_sim['states']['energy_states'])), [], [], setup_cte_sim) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) power_dens_list = np.logspace(1, 2, 3) solution = sim.simulate_power_dependence(power_dens_list) assert mocked.call_count == len(power_dens_list) with pytest.warns(plotter.PlotWarning) as warnings: solution.plot() # assert len(warnings) == 1 # one warning warning = warnings.pop(plotter.PlotWarning) assert issubclass(warning.category, plotter.PlotWarning) assert 'A plot was requested, but no_plot setting is set' in str( warning.message) plotter.plt.close('all')
def test_sim_steady2(setup_cte_sim): '''Test average steady state''' setup_cte_sim['excitations']['Vis_473'][0].t_pulse = 1e-08 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_avg_steady_state() assert solution
def test_sim_conc_dep_no_plot(setup_cte_sim, mocker): '''A plot was requested, but no_plot is set''' setup_cte_sim['no_plot'] = True with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim['states']['energy_states'])) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) conc_list = [(0.01, 0.3), (0.1, 0.3)] solution = sim.simulate_concentration_dependence(conc_list, dynamics=False) assert mocked.call_count == 2 * len(conc_list) with pytest.warns(plotter.PlotWarning) as warnings: solution.plot() # assert len(warnings) == 1 # one warning warning = warnings.pop(plotter.PlotWarning) assert issubclass(warning.category, plotter.PlotWarning) assert 'A plot was requested, but no_plot setting is set' in str( warning.message) plotter.plt.close('all')
def test_sim_dyn_no_t_pulse(setup_cte_sim): '''Test that the dynamics gives an error if t_pulse is not defined''' del setup_cte_sim['excitations']['Vis_473'][0].t_pulse with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) with pytest.raises(AttributeError): sim.simulate_dynamics()
def test_sim_dyn_save_txt(setup_cte_sim): '''Test that the dynamics solution is saved a loaded correctly''' with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_dynamics() with temp_config_filename('') as filename: solution.save_txt(filename)
def test_sim_average_dyn(setup_cte_sim): '''Test average dynamics.''' setup_cte_sim['lattice']['S_conc'] = 0 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_avg_dynamics() assert solution
def test_sim_power_dep_save_txt(setup_cte_sim, mocker): '''Test that the power dep solution is saved as text correctly''' with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) power_dens_list = np.logspace(1, 2, 3) solution = sim.simulate_power_dependence(power_dens_list, average=True) with temp_config_filename('') as filename: solution.save_txt(filename)
def test_sim_dyn_diff(setup_cte_sim): '''Test that the two dynamics are different''' setup_cte_sim['lattice']['S_conc'] = 0 setup_cte_sim['lattice']['A_conc'] = 0.2 with temp_bin_filename() as temp_filename: sim1 = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution1 = sim1.simulate_dynamics() solution1.total_error setup_cte_sim['ions'] = {} setup_cte_sim['lattice']['S_conc'] = 0.2 setup_cte_sim['lattice']['A_conc'] = 0 with temp_bin_filename() as temp_filename: sim2 = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution2 = sim2.simulate_dynamics() solution2.total_error assert sim1 != sim2 assert solution1 != solution2
def test_sim_dyn_wrong_state_plot(setup_cte_sim): '''Test that you can't plot a wrong state.''' setup_cte_sim['lattice']['S_conc'] = 0 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_dynamics() with pytest.raises(ValueError): solution.plot(state=10) plotter.plt.close('all')
def test_sim_conc_dep_save_txt(setup_cte_sim, mocker): '''Test that the conc dep solution is saved as text correctly''' with temp_bin_filename() as temp_filename: conc_list = [(0, 0.3), (0.1, 0.3), (0.1, 0)] sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_concentration_dependence(conc_list, dynamics=False, average=True) with temp_config_filename('') as filename: solution.save_txt(filename)
def test_sim_dyn_errors(setup_cte_sim): '''Test that the dynamics work''' setup_cte_sim['lattice']['S_conc'] = 0 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_dynamics() solution.errors assert isinstance(solution.errors, np.ndarray) solution.log_errors()
def test_sim_power_dep(setup_cte_sim, mocker, average, excitation_name): '''Test that the power dependence works''' for exc_name, exc_list in setup_cte_sim.excitations.items(): for exc in exc_list: if exc_name is excitation_name: exc.active = True else: exc.active = False with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim.states['energy_states'])) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) assert sim.cte == setup_cte_sim power_dens_list = np.logspace(1, 3, 3 - 1 + 1) solution = sim.simulate_power_dependence(power_dens_list, average=average) assert (mocked.call_count == 2 * len(power_dens_list)) or (mocked.call_count == len(power_dens_list)) assert solution solution.plot() with temp_config_filename('') as filename: solution.save_txt(filename) with temp_config_filename('') as filename: solution.save(filename) solution_hdf5 = simulations.PowerDependenceSolution.load(filename) assert solution_hdf5 for sol, sol_hdf5 in zip(solution.solution_list, solution_hdf5.solution_list): assert sol.y_sol.shape == sol_hdf5.y_sol.shape assert np.allclose(sol.t_sol, sol_hdf5.t_sol) assert np.allclose(sol.y_sol, sol_hdf5.y_sol) assert sol.cte == sol_hdf5.cte print(type(sol.index_S_i), type(sol_hdf5.index_S_i)) print(sol.index_S_i, sol_hdf5.index_S_i) assert sol.index_S_i == sol_hdf5.index_S_i assert sol.index_A_j == sol_hdf5.index_A_j assert sol == sol_hdf5 assert solution_hdf5 == solution solution_hdf5.plot() plotter.plt.close('all')
def test_optim_save_txt(setup_cte, mocker): '''Test that the optim solution is saved as text correctly''' init_param = np.array([proc.value for proc in setup_cte['optimization']['processes']]) def mocked_optim_fun(function, params, sim): return 2 + (np.array([val for val in params.valuesdict().values()]) - 1.1*init_param)**2 mocker.patch('simetuc.optimize.optim_fun', new=mocked_optim_fun) with temp_bin_filename() as temp_filename: solution = optimize.optimize_dynamics(setup_cte, full_path=temp_filename) with temp_config_filename('') as filename: solution.save_txt(filename)
def test_sites(setup_cte, sites): '''Test a lattice with different unit cell parameters ''' cte = setup_cte cte['lattice']['sites_pos'] = sites[0] cte['lattice']['sites_occ'] = sites[1] with pytest.raises(lattice.LatticeError): with temp_bin_filename() as temp_filename: (dist_array, ion_type, doped_lattice, initial_population, lattice_info, index_S_i, index_A_j, index_S_k, dist_S_k, index_S_l, dist_S_l, index_A_k, dist_A_k, index_A_l, dist_A_l) = lattice.generate(cte, full_path=temp_filename)
def test_unit_cell(setup_cte, cell_params): '''Test a lattice with different unit cell parameters ''' cte = setup_cte for key, param in zip(['a', 'b', 'c', 'alpha', 'beta', 'gamma'], cell_params): cte.lattice[key] = param with pytest.raises(lattice.LatticeError): with temp_bin_filename() as temp_filename: (dist_array, ion_type, doped_lattice, initial_population, lattice_info, index_S_i, index_A_j, index_S_k, dist_S_k, index_S_l, dist_S_l, index_A_k, dist_A_k, index_A_l, dist_A_l) = lattice.generate(cte, full_path=temp_filename)
def test_sim_dyn(setup_cte_sim): '''Test that the dynamics work''' setup_cte_sim['lattice']['S_conc'] = 0 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) assert sim.cte == setup_cte_sim solution = sim.simulate_dynamics() assert solution solution.plot() solution.plot(state=7) solution.plot(state=1) plotter.plt.close('all')
def test_optim_wrong_method(setup_cte, mocker): '''Test that the optimization works without the optimization params being present in cte''' # mock the simulation by returning an error that goes to 0 init_param = np.array([proc.value for proc in setup_cte['optimization']['processes']]) def mocked_optim_fun(function, params, sim): return 2 + (np.array([val for val in params.valuesdict().values()]) - 1.1*init_param)**2 mocker.patch('simetuc.optimize.optim_fun', new=mocked_optim_fun) setup_cte['optimization']['method'] = 'wrong_method' with pytest.raises(ValueError) as excinfo: with temp_bin_filename() as temp_filename: optimize.optimize_dynamics(setup_cte, full_path=temp_filename) assert excinfo.match(r"Wrong optimization method") assert excinfo.type == ValueError
def test_sim_conc_dep_empty_conc(setup_cte_sim): '''Conc list is empty''' with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) conc_list = [] solution = sim.simulate_concentration_dependence(conc_list) with pytest.warns(plotter.PlotWarning) as warnings: solution.plot() # assert len(warnings) == 1 # one warning warning = warnings.pop(plotter.PlotWarning) assert issubclass(warning.category, plotter.PlotWarning) assert 'Nothing to plot! The concentration_dependence list is emtpy!' in str( warning.message) plotter.plt.close('all')
def test_sim_power_dep_correct_power_dens(setup_cte_sim, mocker): '''Check that the solutions have the right power_dens''' setup_cte_sim['no_plot'] = True with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim['states']['energy_states'])) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) power_dens_list = np.logspace(1, 3, 3) solution = sim.simulate_power_dependence(power_dens_list) assert mocked.call_count == 2 * len(power_dens_list) for num, pow_dens in enumerate(power_dens_list): assert solution[num].power_dens == pow_dens
def test_sim_sample_dynamics(setup_cte_sim, mocker, N_samples): '''Test that sampling the dynamics works''' setup_cte_sim['lattice']['S_conc'] = 0 mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim.states['energy_states'])) with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) assert sim.cte == setup_cte_sim solution = sim.sample_simulation(sim.simulate_dynamics, N_samples=N_samples) assert solution assert mocked.call_count == 2 * N_samples
def test_sim_no_plot(setup_cte_sim): '''Test that no plot works''' setup_cte_sim['no_plot'] = True with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_dynamics() with pytest.warns(plotter.PlotWarning) as warnings: solution.plot() # assert len(warnings) == 1 # one warning warning = warnings.pop(plotter.PlotWarning) assert issubclass(warning.category, plotter.PlotWarning) assert 'A plot was requested, but no_plot setting is set' in str( warning.message) plotter.plt.close('all')
def test_sim_conc_dep_only_S(setup_cte_sim, mocker): '''Conc list has only S changing''' with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim['states']['energy_states'])) sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) conc_list = [(0.01, 0.3), (0.1, 0.3), (0.3, 0.3)] solution = sim.simulate_concentration_dependence(conc_list, dynamics=False) assert mocked.call_count == 2 * len(conc_list) assert solution solution.plot() plotter.plt.close('all')
def test_sim_conc_dep_list(setup_cte_sim, mocker): '''Test that the concentration dependence works''' with temp_bin_filename() as temp_filename: mocked = mocker.patch('simetuc.odesolver._solve_ode') # the num_states changes when the temp lattice is created, # allocate 2x so that we're safe. Also make the num_points 1000. mocked.return_value = np.random.random( (1000, 2 * setup_cte_sim['states']['energy_states'])) conc_list = [(0, 0.3), (0.1, 0.3), (0.1, 0)] sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) solution = sim.simulate_concentration_dependence(conc_list, dynamics=True) # dynamics call solve_ode twice (pulse and relaxation) assert mocked.call_count == 2 * len(conc_list) for num, conc in enumerate(conc_list): assert solution[num].concentration == conc
def test_optim_no_dict_params(setup_cte, mocker): '''Test that the optimization works with an empty optimization dict''' # mock the simulation by returning an error that goes to 0 init_param = np.array([proc.value for proc in setup_cte.energy_transfer.values() if proc.value != 0]) def mocked_optim_fun(function, params, sim): return 2 + (np.array([val for val in params.valuesdict().values()]) - 1.1*init_param)**2 mocker.patch('simetuc.optimize.optim_fun', new=mocked_optim_fun) setup_cte['optimization'] = {} setup_cte['optimization']['processes'] = [proc for proc in setup_cte.energy_transfer.values() if proc.value != 0] setup_cte['optimization']['options'] = {} with temp_bin_filename() as temp_filename: optim_solution = optimize.optimize_dynamics(setup_cte, full_path=temp_filename) best_x = optim_solution.best_params min_f = optim_solution.min_f res = optim_solution.result assert len(best_x) == len(init_param) assert min_f == np.sqrt((res.residual**2).sum())
def test_cte_wrong(setup_cte, params): '''Test a lattice with different unit cell parameters ''' cte = setup_cte cte['lattice']['S_conc'] = params[0] cte['lattice']['A_conc'] = params[1] cte['lattice']['N_uc'] = params[2] cte['states']['sensitizer_states'] = params[3] cte['states']['activator_states'] = params[4] if params[5] is not None: cte['lattice']['radius'] = params[5] del cte['lattice']['N_uc'] with pytest.raises(lattice.LatticeError): with temp_bin_filename() as temp_filename: (dist_array, ion_type, doped_lattice, initial_population, lattice_info, index_S_i, index_A_j, index_S_k, dist_S_k, index_S_l, dist_S_l, index_A_k, dist_A_k, index_A_l, dist_A_l) = lattice.generate(cte, full_path=temp_filename)
def test_sim_steady1(setup_cte_sim): '''Test that the steady state solution is saved a loaded correctly''' setup_cte_sim['excitations']['Vis_473'][0].t_pulse = 1e-08 with temp_bin_filename() as temp_filename: sim = simulations.Simulations(setup_cte_sim, full_path=temp_filename) assert sim.cte == setup_cte_sim solution = sim.simulate_steady_state() assert solution solution.log_populations() solution.plot() solution.log_populations() # redo with temp_config_filename('') as filename: solution.save(filename) sol_hdf5 = simulations.SteadyStateSolution.load(filename) assert sol_hdf5 assert sol_hdf5 == solution sol_hdf5.plot() plotter.plt.close('all')
def test_optim(setup_cte, mocker, method, function, average, processes, excitations, N_samples): '''Test that the optimization works''' # mock the simulation by returning an error that goes to 0 init_param = np.array([proc.value for proc in processes]) def mocked_optim_fun(function, params, sim): return 2 + (np.array([val for val in params.valuesdict().values()]) - 1.1*init_param)**2 mocker.patch('simetuc.optimize.optim_fun', new=mocked_optim_fun) setup_cte['optimization']['method'] = method setup_cte['optimization']['processes'] = processes setup_cte['optimization']['excitations'] = excitations fun = getattr(optimize, function) with warnings.catch_warnings(), temp_bin_filename() as temp_filename: warnings.filterwarnings("ignore", message="divide by zero encountered in double_scalars") optim_solution = fun(setup_cte, average=average, full_path=temp_filename, N_samples=N_samples) best_x = optim_solution.best_params min_f = optim_solution.min_f res = optim_solution.result assert len(best_x) == len(processes) if method in 'brute': assert min_f == np.sqrt(res.candidates[0].score) else: assert min_f == np.sqrt((res.residual**2).sum())
def test_single_atom(setup_cte, concs): '''Generate lattices with a single S or A''' cte = setup_cte cte['lattice']['N_uc'] = 1 cte['states']['sensitizer_states'] = 2 cte['states']['activator_states'] = 7 # single A atom success = False cte['lattice']['S_conc'] = concs[0] cte['lattice']['A_conc'] = concs[1] while not success: try: with temp_bin_filename() as temp_filename: (dist_array, ion_type, doped_lattice, initial_population, lattice_info, index_S_i, index_A_j, index_S_k, dist_S_k, index_S_l, dist_S_l, index_A_k, dist_A_k, index_A_l, dist_A_l) = lattice.generate(cte, full_path=temp_filename) except lattice.LatticeError: # no ions were generated, repeat pass else: if len(ion_type) == 1: # only one ion was generated success = True