def testBackengineInputDir(self):
        """ Test that we can start a test calculation if the input path is a directory. """

        # Cleanup.
        self.__dirs_to_remove.append('diffr')

        parameters = {
            'uniform_rotation': True,
            'calculate_Compton': False,
            'slice_interval': 100,
            'number_of_slices': 2,
            'pmi_start_ID': 1,
            'pmi_stop_ID': 1,
            'number_of_diffraction_patterns': 2,
            'beam_parameter_file':
            TestUtilities.generateTestFilePath('s2e.beam'),
            'beam_geometry_file':
            TestUtilities.generateTestFilePath('s2e.geom'),
        }

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters,
                                             input_path=os.path.dirname(
                                                 self.input_h5),
                                             output_path='diffr')

        # Call backengine.
        status = diffractor.backengine()

        # Check successful completion.
        self.assertEqual(status, 0)
    def testDataInterfaceQueries(self):
        """ Check that the data interface queries work. """

        # Get test instance.
        # Setup pmi parameters.
        pmi_parameters = {'number_of_trajectories' : 1,
                          'number_of_steps'        : 100,
                          'sample_path' : TestUtilities.generateTestFilePath('sample.h5')
                         }
        test_interactor = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                                          input_path=self.input_h5,
                                                          output_path='pmi_out.h5',
                                                          sample_path = TestUtilities.generateTestFilePath('sample.h5') )

        # Get expected and provided data descriptors.
        expected_data = test_interactor.expectedData()
        provided_data = test_interactor.providedData()

        # Check types are correct.
        self.assertIsInstance(expected_data, list)
        self.assertIsInstance(provided_data, list)
        for d in expected_data:
            self.assertIsInstance(d, str)
            self.assertEqual(d[0], '/')
        for d in provided_data:
            self.assertIsInstance(d, str)
            self.assertEqual(d[0], '/')
    def testDefaultConstruction(self):
        """ Testing the default construction of the class. """

        # Prepare input.
        shutil.copytree( TestUtilities.generateTestFilePath( 'pmi_out' ), os.path.abspath( 'pmi' ) )

        # Ensure proper cleanup.
        self.__dirs_to_remove.append( os.path.abspath( 'pmi') )
        self.__dirs_to_remove.append( os.path.abspath( 'diffr' ) )

        # Set up parameters.
        parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 1,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file' : TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 2,
                   }
        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters)

        self.assertIsInstance(diffractor, SingFELPhotonDiffractor)

        self.assertEqual( diffractor.input_path,  os.path.abspath( 'pmi') )
        self.assertEqual( diffractor.output_path, os.path.abspath( 'diffr') )
    def testDataInterfaceQueries(self):
        """ Check that the data interface queries work. """

        # Get test instance.G
        # Setup pmi parameters.
        pmi_parameters = {
            'number_of_trajectories': 1,
            'number_of_steps': 100,
            'sample_path': TestUtilities.generateTestFilePath('sample.h5')
        }
        test_interactor = XMDYNDemoPhotonMatterInteractor(
            parameters=pmi_parameters,
            input_path=self.input_h5,
            output_path='pmi_out.h5',
            sample_path=TestUtilities.generateTestFilePath('sample.h5'))

        # Get expected and provided data descriptors.
        expected_data = test_interactor.expectedData()
        provided_data = test_interactor.providedData()

        # Check types are correct.
        self.assertIsInstance(expected_data, list)
        self.assertIsInstance(provided_data, list)
        for d in expected_data:
            self.assertIsInstance(d, str)
            self.assertEqual(d[0], '/')
        for d in provided_data:
            self.assertIsInstance(d, str)
            self.assertEqual(d[0], '/')
    def testBackengineWithPropInput(self):
        """ Check that beam parameters can be taken from a given propagation output file."""

        self.__dirs_to_remove.append("diffr")

        parameters = CrystFELPhotonDiffractorParameters(
            sample=self.__sample,
            detector_geometry=TestUtilities.generateTestFilePath(
                "simple.geom"),
            beam_parameters=None,
            number_of_diffraction_patterns=1,
        )

        diffractor = CrystFELPhotonDiffractor(
            parameters=parameters,
            input_path=TestUtilities.generateTestFilePath(
                "prop_out_0000001.h5"),
            output_path="diffr",
        )

        # Set spectrum type to tophat otherwise calculation will never finish.
        diffractor.parameters.beam_parameters.photon_energy_spectrum_type = "tophat"

        # Check that beam parameters have been updated from prop output.
        diffractor.backengine()
Пример #6
0
    def testBackengineMultipleProp(self):
        """ Check that the backengine method works correctly. """

        # Prepare input.
        shutil.copytree(TestUtilities.generateTestFilePath('prop_out'),
                        os.path.abspath('prop'))
        self.__dirs_to_remove.append('prop')
        self.__dirs_to_remove.append('pmi')

        parameters = PhotonMatterInteractorParameters(number_of_trajectories=1)
        test_interactor = XMDYNPhotonMatterInteractor(
            parameters=parameters,
            input_path='prop',
            output_path='pmi',
            sample_path=TestUtilities.generateTestFilePath('sample.h5'))

        # Call backengine
        status = test_interactor.backengine()

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check we have generated the expected output.
        self.assertIn('pmi_out_0000001.h5',
                      os.listdir(test_interactor.output_path))
    def testConstruction(self):
        """ Test the default constructor of this class. """
        # Setup a minimal experiment simulation.
        source_input = TestUtilities.generateTestFilePath('FELsource_out.h5')
        diffr_input =  TestUtilities.generateTestFilePath('pmi_out.h5')
        pmi_input = TestUtilities.generateTestFilePath('prop_out.h5')
        photon_source = XFELPhotonSource(parameters=None, input_path=source_input, output_path='FELsource_out.h5')
        photon_propagator = XFELPhotonPropagator(parameters=None, input_path='FELsource_out.h5', output_path='prop_out.h5')
        photon_interactor = FakePhotonMatterInteractor(parameters=None, input_path=pmi_input, output_path='pmi_out.h5')

        diffraction_parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 1,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file' : TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                   }
        photon_diffractor = SingFELPhotonDiffractor(parameters=diffraction_parameters, input_path=diffr_input, output_path='diffr_out.h5')

        photon_detector = PerfectPhotonDetector(parameters = None, input_path='diffr_out.h5', output_path='detector_out.h5')
        photon_analyzer = S2EReconstruction(parameters=None, input_path='detector_out.h5', output_path='analyzer_out.h5')

        pxs = PhotonExperimentSimulation(photon_source=photon_source,
                                         photon_propagator=photon_propagator,
                                         photon_interactor=photon_interactor,
                                         photon_diffractor=photon_diffractor,
                                         photon_detector=photon_detector,
                                         photon_analyzer=photon_analyzer,
                                         )

        # Check instance.
        self.assertIsInstance( pxs, PhotonExperimentSimulation )
Пример #8
0
    def testCalculatorQueries(self):
        """ Test that the calculator queries return the correct calculators. """
        # Setup a minimal experiment simulation.
        source_input = TestUtilities.generateTestFilePath('FELsource_out.h5')
        diffr_input = TestUtilities.generateTestFilePath('pmi_out_0000001.h5')
        pmi_input = TestUtilities.generateTestFilePath('prop_out.h5')
        photon_source = XFELPhotonSource(parameters=None,
                                         input_path=source_input,
                                         output_path='FELsource_out.h5')
        photon_propagator = XFELPhotonPropagator(parameters=None,
                                                 input_path='FELsource_out.h5',
                                                 output_path='prop_out.h5')
        photon_interactor = XMDYNDemoPhotonMatterInteractor(
            parameters=None,
            input_path=pmi_input,
            output_path='pmi_out.h5',
            sample_path=self.__sample_path)

        diffraction_parameters = {
            'uniform_rotation': True,
            'calculate_Compton': False,
            'slice_interval': 100,
            'number_of_slices': 2,
            'pmi_start_ID': 1,
            'pmi_stop_ID': 1,
            'number_of_diffraction_patterns': 2,
            'beam_parameter_file':
            TestUtilities.generateTestFilePath('s2e.beam'),
            'beam_geometry_file':
            TestUtilities.generateTestFilePath('s2e.geom'),
            'number_of_MPI_processes': 2,
        }
        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters,
            input_path=diffr_input,
            output_path='diffr_out.h5')

        photon_detector = IdealPhotonDetector(parameters=None,
                                              input_path='diffr_out.h5',
                                              output_path='detector_out.h5')
        photon_analyzer = S2EReconstruction(parameters=None,
                                            input_path='detector_out.h5',
                                            output_path='analyzer_out.h5')

        pxs = PhotonExperimentSimulation(
            photon_source=photon_source,
            photon_propagator=photon_propagator,
            photon_interactor=photon_interactor,
            photon_diffractor=photon_diffractor,
            photon_detector=photon_detector,
            photon_analyzer=photon_analyzer,
        )

        # Check queries.
        self.assertIs(pxs.photon_source, photon_source)
        self.assertIs(pxs.photon_propagator, photon_propagator)
        self.assertIs(pxs.photon_interactor, photon_interactor)
        self.assertIs(pxs.photon_diffractor, photon_diffractor)
        self.assertIs(pxs.photon_detector, photon_detector)
        self.assertIs(pxs.photon_analyzer, photon_analyzer)
    def setUpClass(cls):
        """ Setting up the test class. """
        #  Diffraction with parameters pmi_stop_ID =1.
        cls.diffractorParam_1 = SingFELPhotonDiffractorParameters(
            uniform_rotation=True,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=2,
            pmi_start_ID=1,
            pmi_stop_ID=1,
            number_of_diffraction_patterns=2,
            beam_parameter_file=TestUtilities.generateTestFilePath('s2e.beam'),
            beam_geometry_file=TestUtilities.generateTestFilePath('s2e.geom'),
            number_of_MPI_processes=2,
        )

        #  Diffraction with parameters pmi_stop_ID =2.
        cls.diffractorParam_2 = SingFELPhotonDiffractorParameters(
            uniform_rotation=True,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=2,
            pmi_start_ID=1,
            pmi_stop_ID=2,
            number_of_diffraction_patterns=2,
            beam_parameter_file=TestUtilities.generateTestFilePath('s2e.beam'),
            beam_geometry_file=TestUtilities.generateTestFilePath('s2e.geom'),
            number_of_MPI_processes=2,
        )
    def testConstructionWithPropInput(self):
        """ Check that beam parameters can be taken from a given propagation output file."""

        parameters = CrystFELPhotonDiffractorParameters(
            sample=self.__sample,
            detector_geometry=TestUtilities.generateTestFilePath(
                "simple.geom"),
            beam_parameters=None,
            number_of_diffraction_patterns=1,
        )

        diffractor = CrystFELPhotonDiffractor(
            parameters=parameters,
            input_path=TestUtilities.generateTestFilePath(
                "prop_out_0000001.h5"),
            output_path="diffr",
        )

        # Set spectrum type to tophat otherwise calculation will never finish.
        diffractor.parameters.beam_parameters.photon_energy_spectrum_type = "tophat"

        # Check that beam parameters have been updated from prop output.
        self.assertAlmostEqual(
            diffractor.parameters.beam_parameters.photon_energy.m_as(
                electronvolt), 4972.8402471221643, 5)
    def testDefaultConstruction(self):
        """ Testing the default construction. """

        # Attempt to construct an instance of the class.
        parameters = CrystFELPhotonDiffractorParameters(
            sample=TestUtilities.generateTestFilePath("2nip.pdb"))

        # Check instance and inheritance.
        self.assertIsInstance(parameters, CrystFELPhotonDiffractorParameters)
        self.assertIsInstance(parameters, AbstractCalculatorParameters)

        # Check all parameters are set to default values.
        self.assertEqual(parameters.sample,
                         TestUtilities.generateTestFilePath("2nip.pdb"))
        self.assertTrue(parameters.uniform_rotation)
        self.assertEqual(parameters.beam_parameters, None)
        self.assertEqual(parameters.detector_geometry, None)
        self.assertTrue(parameters.uniform_rotation)
        self.assertEqual(parameters.number_of_diffraction_patterns, 1)
        self.assertFalse(parameters.powder)
        self.assertEqual(parameters.intensities_file, None)
        self.assertEqual(parameters.crystal_size_min, None)
        self.assertEqual(parameters.crystal_size_max, None)
        self.assertFalse(parameters.poissonize, False)
        self.assertEqual(parameters.number_of_background_photons, 0)
        self.assertFalse(parameters.suppress_fringes)
        self.assertEqual(parameters.beam_parameters, None)
        self.assertEqual(parameters.detector_geometry, None)
    def testBackengineInputDir(self):
        """ Test that we can start a test calculation if the input path is a directory. """

        # Cleanup.
        self.__dirs_to_remove.append('diffr')

        parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 2,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file': TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 2,
                     }

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters, input_path=TestUtilities.generateTestFilePath('pmi_out'), output_path='diffr')

        # Call backengine.
        status = diffractor.backengine()

        # Check successful completion.
        self.assertEqual(status, 0)
    def testBackengineDefaultPaths(self):
        """ Test that we can start a calculation with default paths given. """

        # Prepare input.
        shutil.copytree( TestUtilities.generateTestFilePath( 'pmi_out' ), os.path.abspath( 'pmi' ) )

        # Ensure proper cleanup.
        self.__dirs_to_remove.append( os.path.abspath( 'pmi') )
        self.__dirs_to_remove.append( os.path.abspath( 'diffr' ) )

        parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 1,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file' : TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 2,
                     }

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters)

        # Call backengine.
        status = diffractor.backengine()

        # Check successful completion.
        self.assertEqual(status, 0)

        # Check expected files exist.
        self.assertTrue( os.path.isdir( os.path.abspath( 'diffr' ) ) )
        self.assertIn( 'diffr_out_0000001.h5', os.listdir( os.path.abspath( 'diffr' ) ) )
        self.assertIn( 'diffr_out_0000002.h5', os.listdir( os.path.abspath( 'diffr' ) ) )
Пример #14
0
    def testDiffr0_2(self):
        """ Test that we can handle diffr input version 0.2 """

        self.__files_to_remove.append('orient_out.h5')

        # Construct the object.
        emc_parameters = {
            "initial_number_of_quaternions": 2,
            "max_number_of_quaternions": 4,
            "max_number_of_iterations": 10,
            "min_error": 1.e-6,
            "beamstop": True,
            "detailed_output": True,
        }

        emc = EMCOrientation(
            parameters=emc_parameters,
            input_path=TestUtilities.generateTestFilePath("diffr_0.2"),
            output_path='orient_out.h5',
            tmp_files_path=None,
            run_files_path=None,
        )

        # Call backengine.
        status = emc.backengine()

        self.assertEqual(status, 0)

        # Cleanup.
        self.__files_to_remove.append('orient_out.h5')

        # Construct the object.
        emc_parameters = {
            "initial_number_of_quaternions": 3,
            "max_number_of_quaternions": 4,
            "max_number_of_iterations": 3,
            "min_error": 1.e-6,
            "beamstop": True,
            "detailed_output": True,
        }

        emc = EMCOrientation(
            parameters=emc_parameters,
            input_path=TestUtilities.generateTestFilePath("diffr_newstyle.h5"),
            output_path='orient_out.h5',
            tmp_files_path=None,
            run_files_path=None,
        )

        # Call backengine.
        status = emc.backengine()

        # Check success.
        self.assertEqual(status, 0)
    def testCheckInterfaceConsistency(self):
        """ Test if the check for interface consistency works correctly. """

        # Setup a minimal experiment simulation.
        source_input = TestUtilities.generateTestFilePath('FELsource_out.h5')
        diffr_input = TestUtilities.generateTestFilePath('pmi_out.h5')
        pmi_input = TestUtilities.generateTestFilePath('prop_out.h5')
        photon_source = XFELPhotonSource(parameters=None,
                                         input_path=source_input,
                                         output_path='FELsource_out.h5')
        photon_propagator = XFELPhotonPropagator(parameters=None,
                                                 input_path='FELsource_out.h5',
                                                 output_path='prop_out.h5')
        photon_interactor = FakePhotonMatterInteractor(
            parameters=None, input_path=pmi_input, output_path='pmi_out.h5')

        diffraction_parameters = {
            'uniform_rotation': True,
            'calculate_Compton': False,
            'slice_interval': 100,
            'number_of_slices': 2,
            'pmi_start_ID': 1,
            'pmi_stop_ID': 1,
            'number_of_diffraction_patterns': 2,
            'beam_parameter_file':
            TestUtilities.generateTestFilePath('s2e.beam'),
            'beam_geometry_file':
            TestUtilities.generateTestFilePath('s2e.geom'),
        }
        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters,
            input_path=diffr_input,
            output_path='diffr_out.h5')

        photon_detector = PerfectPhotonDetector(parameters=None,
                                                input_path='diffr_out.h5',
                                                output_path='detector_out.h5')
        photon_analyzer = S2EReconstruction(parameters=None,
                                            input_path='detector_out.h5',
                                            output_path='analyzer_out.h5')

        pxs = PhotonExperimentSimulation(
            photon_source=photon_source,
            photon_propagator=photon_propagator,
            photon_interactor=photon_interactor,
            photon_diffractor=photon_diffractor,
            photon_detector=photon_detector,
            photon_analyzer=photon_analyzer,
        )

        interfaces_are_consistent = pxs._checkInterfaceConsistency()

        self.assertTrue(interfaces_are_consistent)
Пример #16
0
    def testNoRotation(self):
        """ Test that we can run singfel with no-rotation option."""

        diffraction_parameters = SingFELPhotonDiffractorParameters(
            uniform_rotation=None,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=3,
            pmi_start_ID=1,
            pmi_stop_ID=1,
            number_of_diffraction_patterns=2,
            detector_geometry=self.detector_geometry,
            forced_mpi_command='mpirun -np 2',
        )

        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters,
            input_path=TestUtilities.generateTestFilePath('pmi_out'),
            output_path='diffr_newstyle')

        # Cleanup.
        #self.__dirs_to_remove.append(photon_diffractor.output_path)

        # Run backengine and convert files.
        # Ensure removal of directory.
        self.__dirs_to_remove.append(photon_diffractor.output_path)

        photon_diffractor.backengine()
        photon_diffractor.saveH5()

        # Cleanup new style files.
        # Ensure removal of linked hdf.
        self.__files_to_remove.append(photon_diffractor.output_path)

        with h5py.File(photon_diffractor.output_path) as handle:
            pattern = handle['data/0000001/diffr'].value

        # 2nd run.
        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters,
            input_path=TestUtilities.generateTestFilePath('pmi_out'),
            output_path='diffr_newstyle')

        # Run backengine and convert files.
        photon_diffractor.backengine()
        photon_diffractor.saveH5()

        with h5py.File(photon_diffractor.output_path) as handle:
            new_pattern = handle['data/0000001/diffr'].value

        self.assertAlmostEqual(numpy.linalg.norm(pattern - new_pattern), 0.0,
                               5)
    def testCalculatorQueries(self):
        """ Test that the calculator queries return the correct calculators. """
        # Setup a minimal experiment simulation.
        source_input = TestUtilities.generateTestFilePath("FELsource_out.h5")
        diffr_input = TestUtilities.generateTestFilePath("pmi_out_0000001.h5")
        pmi_input = TestUtilities.generateTestFilePath("prop_out.h5")
        photon_source = XFELPhotonSource(parameters=None, input_path=source_input, output_path="FELsource_out.h5")
        photon_propagator = XFELPhotonPropagator(
            parameters=None, input_path="FELsource_out.h5", output_path="prop_out.h5"
        )
        photon_interactor = XMDYNDemoPhotonMatterInteractor(
            parameters=None, input_path=pmi_input, output_path="pmi_out.h5", sample_path=self.__sample_path
        )

        diffraction_parameters = {
            "uniform_rotation": True,
            "calculate_Compton": False,
            "slice_interval": 100,
            "number_of_slices": 2,
            "pmi_start_ID": 1,
            "pmi_stop_ID": 1,
            "number_of_diffraction_patterns": 2,
            "beam_parameter_file": TestUtilities.generateTestFilePath("s2e.beam"),
            "beam_geometry_file": TestUtilities.generateTestFilePath("s2e.geom"),
            "number_of_MPI_processes": 2,
        }
        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters, input_path=diffr_input, output_path="diffr_out.h5"
        )

        photon_detector = IdealPhotonDetector(parameters=None, input_path="diffr_out.h5", output_path="detector_out.h5")
        photon_analyzer = S2EReconstruction(
            parameters=None, input_path="detector_out.h5", output_path="analyzer_out.h5"
        )

        pxs = PhotonExperimentSimulation(
            photon_source=photon_source,
            photon_propagator=photon_propagator,
            photon_interactor=photon_interactor,
            photon_diffractor=photon_diffractor,
            photon_detector=photon_detector,
            photon_analyzer=photon_analyzer,
        )

        # Check queries.
        self.assertIs(pxs.photon_source, photon_source)
        self.assertIs(pxs.photon_propagator, photon_propagator)
        self.assertIs(pxs.photon_interactor, photon_interactor)
        self.assertIs(pxs.photon_diffractor, photon_diffractor)
        self.assertIs(pxs.photon_detector, photon_detector)
        self.assertIs(pxs.photon_analyzer, photon_analyzer)
    def testConstructionRootPath(self):
        """ Testing the construction of the class with a given root path. """

        # Setup pmi parameters.
        pmi_parameters = {'number_of_trajectories' : 1,
                         }

        interactor = XMDYNPhotonMatterInteractor(
                parameters=pmi_parameters,
                output_path='pmi_out',
                input_path=TestUtilities.generateTestFilePath('prop_out_0000001.5'),
                sample_path=TestUtilities.generateTestFilePath('sample.h5'),
                root_path='root.0000001',
                )
        self.assertEqual(interactor.root_path, 'root.0000001')
    def testConstructionWithDict(self):
        """ Testing the construction of the class with a parameter dictionary. """

        # Setup pmi parameters.
        pmi_parameters = {'number_of_trajectories' : 1,
                         }

        interactor = XMDYNPhotonMatterInteractor(
                parameters=pmi_parameters,
                output_path='pmi_out',
                input_path=TestUtilities.generateTestFilePath('prop_out_0000001.5'),
                sample_path=TestUtilities.generateTestFilePath('sample.h5'),
                )

        self.assertIsInstance(interactor, XMDYNPhotonMatterInteractor)
Пример #20
0
    def testConstructionWithSample(self):
        """ Testing the construction with sample passed via parameters."""

        # Ensure proper cleanup.
        sample_file = TestUtilities.generateTestFilePath('2nip.pdb')
        self.__dirs_to_remove.append(os.path.abspath('diffr'))

        # Set up parameters.
        parameters = SingFELPhotonDiffractorParameters(
            sample=sample_file,
            uniform_rotation=False,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=5,
            pmi_start_ID=1,
            pmi_stop_ID=1,
            number_of_diffraction_patterns=1,
            beam_parameters=self.beam,
            detector_geometry=self.detector_geometry,
            forced_mpi_command='mpirun')

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters)

        self.assertIsInstance(diffractor, SingFELPhotonDiffractor)
        self.assertEqual(diffractor.input_path, os.path.abspath(sample_file))
        self.assertEqual(diffractor.output_path, os.path.abspath('diffr'))
    def testDefaultConstruction(self):
        """ Testing the default construction of the class. """

        # Construct the object.
        interactor = XMDYNDemoPhotonMatterInteractor(sample_path = TestUtilities.generateTestFilePath('sample.h5') )

        self.assertIsInstance(interactor, XMDYNDemoPhotonMatterInteractor)
    def testSingleDiffrFileMultiplePatterns(self):
        """ Test that EMC accepts a single (new style) input file from diffraction containing multiple patterns. """

        # Cleanup.
        self.__files_to_remove.append('orient_out.h5')

        # Construct the object.
        emc_parameters = {"initial_number_of_quaternions" : 3,
                          "max_number_of_quaternions"     : 4,
                          "max_number_of_iterations"      : 3,
                          "min_error"                     : 1.e-6,
                          "beamstop"                      : True,
                          "detailed_output"               : True,
                          }

        emc = EMCOrientation(parameters=emc_parameters,
                             input_path=TestUtilities.generateTestFilePath("diffr_newstyle.h5"),
                             output_path='orient_out.h5',
                             tmp_files_path=None,
                             run_files_path=None,)

        # Call backengine.
        status = emc.backengine()

        # Check success.
        self.assertEqual(status, 0)
    def testBackengine(self):
        """ Check that the backengine method works correctly. """


        # Clean up.
        self.__dirs_to_remove.append('pmi')

        # Get test instance.
        pmi_parameters = {'number_of_trajectories' : 1,
                          'number_of_steps'        : 100,
                         }

        test_interactor = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                                          input_path=self.input_h5,
                                                          output_path='pmi',
                                                          sample_path = TestUtilities.generateTestFilePath('sample.h5') )

        # Call backengine
        status = test_interactor.backengine()

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check we have generated the expected output.
        self.assertTrue( 'pmi_out_0000001.h5' in os.listdir( test_interactor.output_path ) )
Пример #24
0
 def testPlotAvgPatternLegacy(self):
     """ Check we can plot the average diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(
         input_path=TestUtilities.generateTestFilePath('diffr_0.1'))
     analyzer.plotPattern(operation=numpy.mean)
     if RENDER_PLOT:
         plt.show()
Пример #25
0
    def testPlotIntensityQMap(self):
        """ Test plotting the intensity map."""
        xfel_photon_analyzer = XFELPhotonAnalysis(
            input_path=TestUtilities.generateTestFilePath(
                'prop_out_0000001.h5'))

        xfel_photon_analyzer.plotIntensityMap(qspace=True)
Пример #26
0
    def testBackengineInputDir(self):
        """ Test that we can start a test calculation if the input path is a directory. """

        # Cleanup.
        self.__dirs_to_remove.append('diffr')

        parameters = SingFELPhotonDiffractorParameters(
            uniform_rotation=True,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=2,
            pmi_start_ID=1,
            pmi_stop_ID=1,
            number_of_diffraction_patterns=2,
            detector_geometry=self.detector_geometry,
            forced_mpi_command='mpirun -np 2',
        )

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(
            parameters=parameters,
            input_path=TestUtilities.generateTestFilePath('pmi_out'),
            output_path='diffr')

        # Call backengine.
        status = diffractor.backengine()

        # Check successful completion.
        self.assertEqual(status, 0)
Пример #27
0
 def __init__(self):
     input_path = TestUtilities.generateTestFilePath(
         'FELsource_out.h5')
     super(TestPhotonAnalyzer,
           self).__init__(parameters=None,
                          input_path=input_path,
                          output_path='test_out.h5')
Пример #28
0
    def test_load_snapshot_from_dir(self):
        """ Test loading a xmdyn snapshot from a directory that contains xmdyn output. """

        pmi = XMDYNPhotonMatterInteractor(
            load_from_path=TestUtilities.generateTestFilePath('xmdyn_run'),
            output_path='pmi')

        snapshot = pmi.f_load_snp_from_dir(
            os.path.join(self.input_xmdyn_dir, 'snp', '1280'.zfill(8)))

        self.assertIsInstance(snapshot, dict)

        expected_keys = [
            'Z',
            'T',
            'uid',
            'r',
            'v',
            'm',
            'q',
            'f0',
            'Q',
        ]

        present_keys = snapshot.keys()
        for k in expected_keys:
            self.assertIn(k, present_keys)
    def testBackengine(self):
        """ Check that the backengine method works correctly. """

        # Clean up.
        self.__dirs_to_remove.append('prop')
        self.__dirs_to_remove.append( 'pmi' )

        # Get test instance.
        pmi_parameters = {
                'number_of_trajectories' : 1,
                         }

        test_interactor = XMDYNPhotonMatterInteractor(parameters=pmi_parameters,
                                                          input_path=self.input_h5,
                                                          output_path='pmi',
                                                          sample_path = TestUtilities.generateTestFilePath('sample.h5') )

        #self.__dirs_to_remove.append(test_interactor.root_path)
        # Call backengine
        status = test_interactor.backengine()

        self.assertTrue(os.path.isdir(test_interactor.output_path))

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check we have generated the expected output.
        self.assertTrue( 'pmi_out_0000001.h5' in os.listdir( test_interactor.output_path ) )
Пример #30
0
    def testNumpylPowerVsTime(self):
        """ Test export numpy array from the total power as function of time. """
        xfel_photon_analyzer = XFELPhotonAnalysis(
            input_path=TestUtilities.generateTestFilePath(
                'prop_out_0000001.h5'))

        xs_mf, int0_mean = xfel_photon_analyzer.numpyTotalPower()
Пример #31
0
    def testPlotOnAxisPowerDensityVsTime(self):
        """ Test plotting the on-axis power as function of time. """
        xfel_photon_analyzer = XFELPhotonAnalysis(
            input_path=TestUtilities.generateTestFilePath(
                'prop_out_0000001.h5'))

        xfel_photon_analyzer.plotOnAxisPowerDensity()
    def testShapedConstructionPaths(self):
        """ Testing the construction of the class with parameters. """

        # Construct.
        feff = FEFFPhotonMatterInteractor(
            parameters=self.__parameters,
            input_path=TestUtilities.generateTestFilePath('prop'),
            output_path='absorption.h5')

        # Check type.
        self.assertIsInstance(feff, FEFFPhotonMatterInteractor)

        # Get parameters and check.
        parameters = feff.parameters

        self.assertEqual(parameters.atoms, self.__atoms)
        self.assertEqual(parameters.potentials, self.__potentials)
        self.assertEqual(parameters.edge, self.__edge)
        self.assertEqual(parameters.amplitude_reduction_factor,
                         self.__amplitude_reduction_factor)
        self.assertEqual(parameters.effective_path_distance,
                         self.__effective_path_distance)

        self.assertEqual(feff.output_path,
                         os.path.join(os.getcwd(), 'absorption.h5'))
Пример #33
0
    def testPlotOnAxisPowerDensityVsEnergy(self):
        """ Test plotting the total power spectrum."""
        xfel_photon_analyzer = XFELPhotonAnalysis(
            input_path=TestUtilities.generateTestFilePath(
                'prop_out_0000001.h5'))

        xfel_photon_analyzer.plotOnAxisPowerDensity(spectrum=True)
    def testSettersAndQueries(self):
        """ Testing the default construction of the class using a dictionary. """

        self.__files_to_remove.append("5udc.pdb")

        # Construct with defaults.
        parameters = CrystFELPhotonDiffractorParameters(
            TestUtilities.generateTestFilePath("2nip.pdb"))

        # Set some members to non-defaults.
        parameters.sample = "5udc.pdb"
        parameters.powder = True
        parameters.number_of_diffraction_patterns = 10
        parameters.number_of_background_photons = 100
        parameters.poissonize = True
        parameters.suppress_fringes = True
        parameters.crystal_size_min = 10.0e-9 * meter
        parameters.crystal_size_max = 100.0e-9 * meter
        parameters.uniform_rotation = False

        # Check all parameters are set as intended.
        self.assertEqual(parameters.sample, "5udc.pdb")
        self.assertFalse(parameters.uniform_rotation)
        self.assertEqual(parameters.number_of_diffraction_patterns, 10)
        self.assertTrue(parameters.powder)
        self.assertEqual(parameters.crystal_size_min, 10.0e-9 * meter)
        self.assertEqual(parameters.crystal_size_max, 100.0e-9 * meter)
        self.assertTrue(parameters.poissonize)
        self.assertEqual(parameters.number_of_background_photons, 100)
        self.assertTrue(parameters.suppress_fringes)
Пример #35
0
    def testMinimalExample(self):
        """ Check that beam parameters can be taken from a given propagation output file."""

        self.__files_to_remove.append("detector_out.h5")

        parameters = XCSITPhotonDetectorParameters(detector_type="AGIPDSPB", )

        diffractor = XCSITPhotonDetector(
            parameters=parameters,
            input_path=TestUtilities.generateTestFilePath(
                "diffr/diffr_out_0000001.h5"),
            output_path="detector_out.h5",
        )

        diffractor._readH5()
        diffractor.backengine()
        diffractor.saveH5()

        # Assert output was created.
        self.assertTrue(os.path.isfile("detector_out.h5"))

        # Check if we can read the output.
        with h5py.File("detector_out.h5") as h5:
            self.assertIn("data", h5.keys())
            self.assertIn("data", h5["data"].keys())
            self.assertIn("photons", h5["data"].keys())
Пример #36
0
    def testPlotTotalPowerVsTime(self):
        """ Test plotting the total power as function of time. """
        xfel_photon_analyzer = XFELPhotonAnalysis(
            input_path=TestUtilities.generateTestFilePath(
                'prop_out_0000001.h5'))

        xfel_photon_analyzer.plotTotalPower()
Пример #37
0
    def testBackengineRestart(self):
        """ Check that we can restart an aborted simulation. """

        # Clean up.
        #self.__dirs_to_remove.append('pmi')

        # Get test instance.
        pmi_parameters = {
            'number_of_trajectories': 1,
        }

        test_interactor = XMDYNPhotonMatterInteractor(
            parameters=pmi_parameters,
            input_path=self.input_h5,
            output_path='pmi',
            sample_path=TestUtilities.generateTestFilePath('sample.h5'),
            root_path='pmi/root.1')

        #self.__dirs_to_remove.append(test_interactor.root_path)
        # Call backengine
        with test_interactor.backengine() as status:
            import time
            time.sleep(10)
            test_interactor._XMDYNPhotonMatterInteractor__process.kill()

        self.assertTrue(os.path.isdir(test_interactor.output_path))

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check we have generated the expected output.
        self.assertTrue(
            'pmi_out_0000001.h5' in os.listdir(test_interactor.output_path))

        self.assertTrue(os.path.isdir(test_interactor.root_path))
Пример #38
0
    def setUpClass(cls):
        """ Setting up the test class. """
        cls.input_h5 = TestUtilities.generateTestFilePath('pmi_out_0000001.h5')
        detector_panel = DetectorPanel(
            ranges={
                'fast_scan_min': 0,
                'fast_scan_max': 21,
                'slow_scan_min': 0,
                'slow_scan_max': 21
            },
            pixel_size=2.2e-4 * meter,
            photon_response=1.0,
            distance_from_interaction_plane=0.13 * meter,
            corners={
                'x': -11,
                'y': -11
            },
        )

        cls.detector_geometry = DetectorGeometry(panels=[detector_panel])

        cls.beam = PhotonBeamParameters(
            photon_energy=8.6e3 * electronvolt,
            beam_diameter_fwhm=1.0e-6 * meter,
            pulse_energy=1.0e-3 * joule,
            photon_energy_relative_bandwidth=0.001,
            divergence=1e-3 * radian,
            photon_energy_spectrum_type="SASE",
        )
Пример #39
0
    def testDefaultConstructionLegacy(self):
        """ Testing the default construction of the class with MPI parameter. """

        # Prepare input.
        shutil.copytree(TestUtilities.generateTestFilePath('pmi_out'),
                        os.path.abspath('pmi'))

        # Ensure proper cleanup.
        self.__dirs_to_remove.append(os.path.abspath('pmi'))
        self.__dirs_to_remove.append(os.path.abspath('diffr'))

        # Set up parameters.
        parameters = SingFELPhotonDiffractorParameters(
            sample=None,
            uniform_rotation=False,
            calculate_Compton=False,
            slice_interval=100,
            number_of_slices=3,
            pmi_start_ID=1,
            pmi_stop_ID=1,
            number_of_diffraction_patterns=2,
            beam_parameters=self.beam,
            detector_geometry=self.detector_geometry,
            forced_mpi_command='mpirun -np 2',
        )
        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters,
                                             input_path='pmi')

        # Check type.
        self.assertIsInstance(diffractor, SingFELPhotonDiffractor)

        # Check default output_path.
        self.assertEqual(diffractor.output_path, os.path.abspath('diffr'))
    def testSingleFile(self):
        """ Test that saveH5() generates only one linked hdf. """


        diffraction_parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : True,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 4,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file': TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 8,
                   }

        photon_diffractor = SingFELPhotonDiffractor(
                parameters=diffraction_parameters,
                input_path=TestUtilities.generateTestFilePath('pmi_out'),
                output_path='diffr_newstyle')

        # Cleanup.
        self.__dirs_to_remove.append(photon_diffractor.output_path)

        # Run backengine and convert files.
        photon_diffractor.backengine()
        photon_diffractor.saveH5()

        # Cleanup new style files.
        self.__files_to_remove.append(photon_diffractor.output_path)

        # Check that only one file was generated.
        self.assertTrue( os.path.isfile( photon_diffractor.output_path ))

        # Open the file for reading.
        h5_filehandle = h5py.File( photon_diffractor.output_path, 'r')

        # Count groups under /data.
        number_of_patterns = len(h5_filehandle.keys()) - 3

        self.assertEqual( number_of_patterns, 8 )

        # Assert global metadata is present.
        self.assertIn("params", h5_filehandle.keys() )
        self.assertIn("version", h5_filehandle.keys() )
        self.assertIn("info", h5_filehandle.keys() )
        self.assertIn("geom", h5_filehandle["params"].keys() )
    def testConstructionParameters(self):
        """ Check we can construct with a parameter object. """
        parameters = SingFELPhotonDiffractorParameters(uniform_rotation = True,
                                                       calculate_Compton = False,
                                                       slice_interval = 100,
                                                       number_of_slices = 2,
                                                       pmi_start_ID = 1,
                                                       pmi_stop_ID  = 1,
                                                       number_of_diffraction_patterns = 2,
                                                       beam_parameter_file = TestUtilities.generateTestFilePath('s2e.beam'),
                                                       beam_geometry_file = TestUtilities.generateTestFilePath('s2e.geom'),
                                                       number_of_MPI_processes = 2,
                                                       )
        diffractor = SingFELPhotonDiffractor(parameters=parameters, input_path=self.input_h5, output_path='diffr_out.h5')

        # Check instance.
        self.assertIsInstance( diffractor, SingFELPhotonDiffractor )
    def testShapedConstruction(self):
        """ Testing the construction of the class with parameters. """

        parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 1,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file' : TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 2,
                   }

        # Construct the object.
        diffractor = SingFELPhotonDiffractor(parameters=parameters, input_path=self.input_h5, output_path='diffr_out.h5')

        self.assertIsInstance(diffractor, SingFELPhotonDiffractor)
    def testOPMD(self):
        """ Check that the input directory scanner filters out the opmd files."""

        # Clean up.
        self.__dirs_to_remove.append('pmi')

        # Setup parameters.
        pmi_parameters = {'number_of_trajectories' : 10,
                          'number_of_steps'        : 100,
                         }

        test_interactor = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                                          input_path=TestUtilities.generateTestFilePath('prop_out'),
                                                          output_path='pmi',
                                                          sample_path=TestUtilities.generateTestFilePath('sample.h5') )

        # Call backengine
        status = test_interactor.backengine()

        self.assertEqual(status, 0 )
    def testBackengineDefaultPaths(self):
        """ Check that the backengine method works correctly. """

        # Prepare input.
        shutil.copytree( TestUtilities.generateTestFilePath('prop_out'), os.path.abspath( 'prop' ) )
        self.__dirs_to_remove.append( 'prop' )
        self.__dirs_to_remove.append( 'pmi' )

        test_interactor = XMDYNDemoPhotonMatterInteractor(sample_path=TestUtilities.generateTestFilePath('sample.h5') )

        # Call backengine
        status = test_interactor.backengine()

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check we have generated the expected output.
        self.assertTrue( os.path.isdir( os.path.abspath( 'prop' ) ) )
        self.assertIn( 'pmi_out_0000001.h5' , os.listdir( test_interactor.output_path ) )
        self.assertIn( 'pmi_out_0000002.h5' , os.listdir( test_interactor.output_path ) )
    def testBackengineMultipleInputFile(self):
        """ Test a backengine run with multiple input files. """
        # Construct the object.
        xfel_propagator = XFELPhotonPropagator( parameters=None, input_path=TestUtilities.generateTestFilePath( 'FELsource_out' ), output_path='prop_out' )

        # Call the backengine.
        status = xfel_propagator.backengine()

        # Check backengine returned sanely.
        self.assertEqual( status, 0 )

        # Ensure clean-up.
        self.__dirs_to_remove.append(xfel_propagator.output_path)
    def testBug53(self):
        """ Tests a script that was found to raise if run in parallel mode. """

        self.__dirs_to_remove.append('diffr')

        diffraction_parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : True,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 9,
                     'number_of_diffraction_patterns' : 1,
                     'beam_parameter_file': TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                     'number_of_MPI_processes' : 10,
                   }

        photon_diffractor = SingFELPhotonDiffractor(
                parameters=diffraction_parameters,
                input_path=TestUtilities.generateTestFilePath('pmi_out'),
                output_path='diffr')

        photon_diffractor.backengine()
    def testCheckInterfaceConsistency(self):
        """ Test if the check for interface consistency works correctly. """

        # Setup a minimal experiment simulation.
        source_input = TestUtilities.generateTestFilePath('FELsource_out.h5')
        diffr_input =  TestUtilities.generateTestFilePath('pmi_out.h5')
        pmi_input = TestUtilities.generateTestFilePath('prop_out.h5')
        photon_source = XFELPhotonSource(parameters=None, input_path=source_input, output_path='FELsource_out.h5')
        photon_propagator = XFELPhotonPropagator(parameters=None, input_path='FELsource_out.h5', output_path='prop_out.h5')
        photon_interactor = XMDYNDemoPhotonMatterInteractor(parameters=None, input_path=pmi_input, output_path='pmi_out.h5')

        diffraction_parameters={ 'uniform_rotation': True,
                     'calculate_Compton' : False,
                     'slice_interval' : 100,
                     'number_of_slices' : 2,
                     'pmi_start_ID' : 1,
                     'pmi_stop_ID'  : 1,
                     'number_of_diffraction_patterns' : 2,
                     'beam_parameter_file' : TestUtilities.generateTestFilePath('s2e.beam'),
                     'beam_geometry_file' : TestUtilities.generateTestFilePath('s2e.geom'),
                   }
        photon_diffractor = SingFELPhotonDiffractor(parameters=diffraction_parameters, input_path=diffr_input, output_path='diffr_out.h5')

        photon_detector = PerfectPhotonDetector(parameters = None, input_path='diffr_out.h5', output_path='detector_out.h5')
        photon_analyzer = S2EReconstruction(parameters=None, input_path='detector_out.h5', output_path='analyzer_out.h5')

        pxs = PhotonExperimentSimulation(photon_source=photon_source,
                                         photon_propagator=photon_propagator,
                                         photon_interactor=photon_interactor,
                                         photon_diffractor=photon_diffractor,
                                         photon_detector=photon_detector,
                                         photon_analyzer=photon_analyzer,
                                         )

        interfaces_are_consistent = pxs._checkInterfaceConsistency()

        self.assertTrue( interfaces_are_consistent )
    def testShapedConstruction(self):
        """ Testing the construction of the class with parameters. """

        # Setup pmi parameters.
        pmi_parameters = {'number_of_trajectories' : 1,
                          'number_of_steps'        : 100,
                         }

        interactor = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                                     output_path='pmi_out',
                                                     input_path='pmi_in',
                                                     sample_path=TestUtilities.generateTestFilePath('sample.h5'),
                                                     )

        self.assertIsInstance(interactor, XMDYNDemoPhotonMatterInteractor)
    def testLoadPDBFile(self):
        """ Check that the sample can be taken from a pdb directly. """

        # Clean up.
        self.__dirs_to_remove.append('pmi')

        # Get test instance.
        pmi_parameters = {'number_of_trajectories' : 10,
                          'number_of_steps'        : 100,
                         }

        pmi = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                              input_path=self.input_h5,
                                              output_path='pmi',
                                              sample_path=TestUtilities.generateTestFilePath('2nip.pdb') )

        # Call backengine
        status = pmi.backengine()

        self.assertEqual(status, 0 )
    def testBackengineDefaultPath(self):
        """ Test that we can start a test calculation. """

        # Prepare path.
        shutil.copytree( TestUtilities.generateTestFilePath( 'diffr' ), 'detector' )

        # Ensure proper cleanup.
        self.__dirs_to_remove.append( 'detector' )
        self.__dirs_to_remove.append( 'analysis' )

        emc_parameters = {'initial_number_of_quaternions' : 1,
                          'max_number_of_quaternions'     : 2,
                          'max_number_of_iterations'      : 10,
                          'min_error'                     : 1.0e-6,
                          'beamstop'                      : True,
                          'detailed_output'               : False
                               }

        dm_parameters = {'number_of_trials'        : 5,
                         'number_of_iterations'    : 2,
                         'averaging_start'         : 15,
                         'leash'                   : 0.2,
                         'number_of_shrink_cycles' : 2,
                         }

        # Construct the object.
        analyzer = S2EReconstruction(parameters={'EMC_Parameters' : emc_parameters, 'DM_Parameters' : dm_parameters})

        # Call backengine.
        status = analyzer.backengine()

        # Check return value.
        self.assertEqual(status, 0)

        # Check presence of output files.
        self.assertTrue( os.path.isdir( 'analysis' ) )
        self.assertIn( 'orient_out.h5', os.listdir( 'analysis' ) )
        self.assertIn( 'phase_out.h5', os.listdir( 'analysis' ) )
    def testIssue53(self):
        """ Check that xmdyn_demo writes the Nph variable according to bugfix 53."""

        # Clean up.
        self.__dirs_to_remove.append('pmi')

        # Get test instance.
        pmi_parameters = {'number_of_trajectories' : 10,
                          'number_of_steps'        : 100,
                         }

        pmi = XMDYNDemoPhotonMatterInteractor(parameters=pmi_parameters,
                                              input_path=self.input_h5,
                                              output_path='pmi',
                                              sample_path=TestUtilities.generateTestFilePath('2nip.pdb') )

        # Call backengine
        status = pmi.backengine()

        h5 = h5py.File('pmi/pmi_out_0000001.h5')
        Nph = h5['/data/snp_0000001/Nph']

        self.assertEqual(Nph.shape, (1,))
Пример #52
0
import paths

# Import SimEx modules.
from TestUtilities import TestUtilities
from SimEx.Calculators.XFELPhotonSource import XFELPhotonSource
from SimEx.Calculators.XFELPhotonPropagator import XFELPhotonPropagator
from SimEx.Calculators.XMDYNDemoPhotonMatterInteractor import XMDYNDemoPhotonMatterInteractor
from SimEx.Calculators.SingFELPhotonDiffractor import SingFELPhotonDiffractor
from SimEx.Calculators.PerfectPhotonDetector import PerfectPhotonDetector
from SimEx.Calculators.S2EReconstruction import S2EReconstruction
from SimEx.PhotonExperimentSimulation.PhotonExperimentSimulation import PhotonExperimentSimulation


# Location of the FEL source file.
source_input = TestUtilities.generateTestFilePath('FELsource_out/FELsource_out_0000001.h5')

# Photon source.
photon_source = XFELPhotonSource(parameters=None, input_path=source_input, output_path='FELsource_out_0000001.h5')

# Photon propagator, default parameters.
photon_propagator = XFELPhotonPropagator(parameters=None, input_path='FELsource_out_0000001.h5', output_path='prop_out_0000001.h5')

# Photon interactor with default parameters.
pmi_parameters= {'sample_path' :TestUtilities.generateTestFilePath('sample.h5')}
photon_interactor = XMDYNDemoPhotonMatterInteractor( parameters=pmi_parameters,
                                                     input_path='prop_out_0000001.h5',
                                                     output_path='pmi')

#  Diffraction with parameters.
diffraction_parameters={ 'uniform_rotation': 1,
Пример #53
0
 def setUpClass(cls):
     """ Setting up the test class. """
     cls.input_h5 = TestUtilities.generateTestFilePath('diffr')
Пример #54
0
    def testReference(self, debug=False):
        """ Check that singfel reproduces a given set of reference data. """

        self.__dirs_to_remove.append('diffr')

        beam_file = TestUtilities.generateTestFilePath('s2e.beam')
        geom_file = TestUtilities.generateTestFilePath('s2e.geom')
        # Setup diffraction parameters (no rotation because reference test).
        parameters = SingFELPhotonDiffractorParameters(
                                                       uniform_rotation=False,
                                                       calculate_Compton=True,
                                                       slice_interval=100,
                                                       number_of_slices=100,
                                                       pmi_start_ID=1,
                                                       pmi_stop_ID =1,
                                                       number_of_diffraction_patterns=1,
                                                       beam_parameter_file=beam_file,
                                                       beam_geometry_file=geom_file,
                                                       number_of_MPI_processes=2,
                                                        )

        # Setup diffraction calculator.
        diffractor = SingFELPhotonDiffractor(
                parameters=parameters,
                input_path=TestUtilities.generateTestFilePath('pmi_out'),
                output_path='diffr'
                )

        # Run (reads input and write output, as well).
        diffractor.backengine()

        # Open results file.
        h5_handle = h5py.File(os.path.join(diffractor.output_path,'diffr_out_0000001.h5'),'r')

        # Get data (copy).
        diffraction_data = h5_handle['/data/diffr'].value

        h5_handle.close()

        # Get total intensity.
        intensity = diffraction_data.sum()

        # Get hash of the data.
        this_hash = hash( diffraction_data.tostring() )

        if debug:
            print "%15.14e" % (intensity)

            # Save wavefront data for reference.
            #########################################################################################
            ## ATTENTION: Overwrites reference data, use only if you're sure you want to do this. ###
            #########################################################################################
            #with open(TestUtilities.generateTestFilePath("singfel_reference.hash.txt"), 'w') as hashfile:
                #hashfile.write(str(this_hash))
                #hashfile.close()
            #########################################################################################

            self.assertEqual(math.pi, 22./7.)

        # Load reference hash.
        with open( TestUtilities.generateTestFilePath("singfel_reference.hash.txt"), 'r') as hashfile:
            ref_hash = hashfile.readline()
            hashfile.close()

        # Weak test.
        reference_intensity = '5.18647193908691e+01'
        self.assertEqual( "%15.14e" % (intensity), reference_intensity)

        # Strong test.
        self.assertEqual( ref_hash, str(this_hash) )
 def __init__(self):
     super (Source2, self).__init__(parameters=None,
                                   input_path = TestUtilities.generateTestFilePath('FELsource_out.h5'),
                                   output_path = None)
 def __init__(self):
     input_path = TestUtilities.generateTestFilePath('FELsource_out.h5')
     super(TestPhotonSource, self).__init__(parameters=None, input_path=input_path, output_path='test_out.h5')
Пример #57
0
 def setUpClass(cls):
     """ Setting up the test class. """
     cls.input_h5 = TestUtilities.generateTestFilePath('orient_out.h5')
Пример #58
0
    def testGaussianReference(self, debug=False):
        """ Check that propagation of a Gaussian pulse (in t,x,y) through vacuum reproduces reference data. """


        # Central photon energy.
        ekev = 8.4 # Energy [keV]

        # Pulse parameters.
        qnC = 0.5               # e-bunch charge, [nC]
        pulse_duration = 9.0e-15 # [s]
        pulseEnergy = 1.5e-3    # total pulse energy, J

        # Coherence time
        coh_time = 0.25e-15 # [s]

        # Distance in free space.
        z0 = 10. # (m), position where to build the wavefront.
        z1 = 10. # (m), distance to travel in free space.

        # Beam divergence.
        theta_fwhm = 2.5e-6 # rad

        wlambda = 12.4*1e-10/ekev # wavelength, m
        w0 = wlambda/(numpy.pi*theta_fwhm) # beam waist, m
        zR = (math.pi*w0**2)/wlambda #Rayleigh range, m
        fwhm_at_zR = theta_fwhm*zR #FWHM at Rayleigh range, m
        sigmaAmp = w0/(2.0*math.sqrt(math.log(2.0))) #sigma of amplitude, m

        if debug:
            print (" *** Pulse properties ***")
            print (" lambda = %4.3e m" % (wlambda) )
            print (" w0 = %4.3e m" % (w0) )
            print (" zR = %4.3e m" % (zR) )
            print (" fwhm at zR = %4.3e m" % (fwhm_at_zR) )
            print (" sigma = %4.3e m" % (sigmaAmp) )

        # expected beam radius after free space drift.
        expected_beam_radius = w0*math.sqrt(1.0+(z0/zR)**2)


        # Number of points in each x and y dimension.
        np=400

        # Sampling window = 6 sigma of initial beam.
        range_xy = 6.*expected_beam_radius
        dx = range_xy / (np-1)
        nslices = 20

        if debug:
            print (" Expected beam waist at z=%4.3f m : %4.3e m." % (z0, expected_beam_radius) )
            print ("Setting up mesh of %d points per dimension on a %4.3e x %4.3e m^2 grid with grid spacing %4.3e m." % (np, range_xy, range_xy, dx) )

        # Construct srw wavefront.
        srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -range_xy/2., range_xy/2.,
                                        -range_xy/2., range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z0,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        # Convert to wpg.
        wf = Wavefront(srwl_wf)

        if debug:
            print('*** z=%4.3e m ***' % (z0))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)

        # Construct the beamline.
        beamline = Beamline()

        # Add free space drift.
        drift = Drift(z1)
        beamline.append( drift, Use_PP(semi_analytical_treatment=1))

        # Propagate
        srwl.SetRepresElecField(wf._srwl_wf, 'f') # <---- switch to frequency domain
        beamline.propagate(wf)
        srwl.SetRepresElecField(wf._srwl_wf, 't')

        if debug:
            print('*** z=%4.3e m ***' % (z0+z1))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)


        # Get propagated wavefront data.
        wf_intensity = wf.get_intensity()

        # Project on t axis.
        wf_onaxis = wf_intensity.sum(axis=(0,1))

        # Get hash of the data.
        wf_hash = hash( wf_intensity.tostring() )

        # Load reference hash.
        with open(TestUtilities.generateTestFilePath("reference_wf_gauss_10m.hash.txt"), 'r') as hashfile:
            ref_hash = hashfile.readline()
            hashfile.close()
        ref_onaxis = numpy.loadtxt(TestUtilities.generateTestFilePath("reference_wf_gauss_onaxis_10m.txt"))

        # Weak test.
        for x,y in zip(wf_onaxis, ref_onaxis):
            self.assertAlmostEqual( x, y, 14 )

        # Strong test.
        self.assertEqual( str(wf_hash), ref_hash)
    def testBackengine(self):
        """ Check that the backengine method works correctly. """

        # Get test instance.
        pmi_parameters = {'number_of_trajectories' : 10}
        test_interactor = FakePhotonMatterInteractor(parameters=pmi_parameters, input_path=self.input_h5, output_path='pmi')

        # Call backengine
        status = test_interactor.backengine()

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Check that output was written to the given directory.
        self.assertTrue( os.path.isdir( test_interactor.output_path ) )
        self.assertEqual( len( os.listdir( test_interactor.output_path ) ), test_interactor.parameters['number_of_trajectories'] )

        # Call backengine again, so see that it works if directory already exists.
        status = test_interactor.backengine()

        # Check that the backengine returned zero.
        self.assertEqual(status, 0)

        # Test that exception raises if output_path is a file that already exists.
        shutil.copyfile( os.path.join( test_interactor.output_path, 'pmi_out_0000001.h5' ), 'pmi_out_0000001.h5' )
        shutil.rmtree(test_interactor.output_path)

        fake = FakePhotonMatterInteractor( parameters=pmi_parameters, input_path=self.input_h5, output_path=TestUtilities.generateTestFilePath( 'pmi_out_0000001.h5' ) )
        self.assertEqual( fake.backengine(), 1 )

        # Clean up.
        self.__paths_to_remove.append('pmi')
        self.__files_to_remove.append('pmi_out_0000001.h5')
    def testSimS2EWorkflowDefaultPaths(self):
        """ Testing that a workflow akin to the simS2E example workflow works. No IO paths specified. """

        # These directories and files are expected to be present after a successfull calculation.
        expected_dirs = ["source_in", "source", "prop", "pmi", "diffr", "analysis"]

        expected_files = [
            "source/FELsource_out_0000000.h5",
            "source/FELsource_out_0000001.h5",
            "prop/prop_out_0000000.h5",
            "prop/prop_out_0000001.h5",
            "pmi/pmi_out_0000001.h5",
            "pmi/pmi_out_0000002.h5",
            "diffr/diffr_out_0000001.h5",
            "diffr/diffr_out_0000002.h5",
            "diffr.h5",
            "detector",
            "analysis/orient_out.h5",
            "analysis/phase_out.h5",
        ]

        # Ensure proper cleanup.
        self.__dirs_to_remove = expected_dirs
        self.__files_to_remove.append("diffr.h5")
        self.__files_to_remove.append("detector")

        # Get proper FEL source files to start from.
        shutil.copytree(TestUtilities.generateTestFilePath("FELsource_out"), "source_in")

        # Photon source.
        photon_source = XFELPhotonSource(input_path="source_in")

        # Photon propagator, default parameters.
        photon_propagator = XFELPhotonPropagator()

        # Photon interactor with default parameters.
        photon_interactor = XMDYNDemoPhotonMatterInteractor(sample_path=self.__sample_path)

        #  Diffraction with parameters.
        diffraction_parameters = {
            "uniform_rotation": True,
            "calculate_Compton": False,
            "slice_interval": 100,
            "number_of_slices": 2,
            "pmi_start_ID": 1,
            "pmi_stop_ID": 2,
            "number_of_diffraction_patterns": 1,
            "beam_parameter_file": TestUtilities.generateTestFilePath("s2e.beam"),
            "beam_geometry_file": TestUtilities.generateTestFilePath("s2e.geom"),
            "number_of_MPI_processes": 2,
        }

        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters, input_path=TestUtilities.generateTestFilePath("pmi_out")
        )

        # Reconstruction: EMC+DM
        emc_parameters = {
            "initial_number_of_quaternions": 1,
            "max_number_of_quaternions": 2,
            "max_number_of_iterations": 10,
            "min_error": 1.0e-6,
            "beamstop": True,
            "detailed_output": False,
        }

        dm_parameters = {
            "number_of_trials": 5,
            "number_of_iterations": 2,
            "averaging_start": 15,
            "leash": 0.2,
            "number_of_shrink_cycles": 2,
        }

        reconstructor = S2EReconstruction(parameters={"EMC_Parameters": emc_parameters, "DM_Parameters": dm_parameters})

        # Setup the photon experiment.
        pxs = PhotonExperimentSimulation(
            photon_source=photon_source,
            photon_propagator=photon_propagator,
            photon_interactor=photon_interactor,
            photon_diffractor=photon_diffractor,
            photon_analyzer=reconstructor,
        )

        # Run the experiment.
        pxs.run()

        # Check that all output files and directories are present.
        for directory in expected_dirs:
            print directory
            self.assertTrue(os.path.isdir(directory))
        for f in expected_files:
            print f
            self.assertTrue(os.path.isfile(f))