Пример #1
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()
Пример #2
0
def main():

    analyzer = DiffractionAnalysis(input_path=input_path,
                                   pattern_indices=pattern_indices,
                                   poissonize=True)

    parameters = diffractionParameters(input_path)
    nx, ny = parameters["geom"]["mask"].shape
    mask = parameters["geom"]["mask"]
    nx, ny = mask.shape
    beamstop = 20
    mask[nx // 2 - beamstop // 2:nx // 2 + beamstop // 2 + 1,
         ny // 2 - beamstop // 2:ny // 2 + beamstop // 2 + 1]
    analyzer.mask = mask

    pattern = numpy.mean([p for p in analyzer.patterns_iterator], axis=0)
    qs, intensities = azimuthalIntegration(pattern,
                                           diffractionParameters(input_path))

    plt.plot(qs, intensities)

    plt.xlabel(r"$2\theta$ (deg)")
    plt.ylabel("Intensity (arb. units)")
    plt.tight_layout()

    plt.show()
Пример #3
0
 def testPlotOnePattern(self):
     """ Check we can plot one diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                    pattern_indices=4)
     analyzer.plotPattern()
     if RENDER_PLOT:
         plt.show()
Пример #4
0
def main(args=None):

    # Setup the object.
    analyzer = DiffractionAnalysis(
        input_path=args.input_path,
        pattern_indices=eval(args.pattern_indices),
        poissonize=eval(args.poissonize),
    )

    # Plot if requested.
    if args.plot:
        analyzer.plotPattern(
            logscale=args.logscale,
            operation=eval(args.operation),
        )
    # Plot if requested.
    if args.radial:
        analyzer.plotRadialProjection(
            logscale=args.logscale,
            operation=eval(args.operation),
        )

    if args.statistics:
        analyzer.statistics()

    plt.show()

    # Animate if requested.
    if args.animation_filename:
        analyzer.animatePatterns(output_path=args.animation_filename)

        print "Animated gif saved to %s." % (
            analyzer._DiffractionAnalysis__animation_output_path)
Пример #5
0
 def testPlotSumPatternLogscale(self):
     """ Check we can plot one diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                    poissonize=False)
     analyzer.plotPattern(operation=numpy.sum, logscale=True)
     if RENDER_PLOT:
         plt.show()
Пример #6
0
 def testPlotAvgSequenceInt(self):
     """ Check we can plot the avg over a subset of patterns given as list of ints."""
     analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                    pattern_indices=[1, 3, 6])
     analyzer.plotPattern(operation=numpy.mean)
     if RENDER_PLOT:
         plt.show()
Пример #7
0
 def testPlotOnePatternLegacy(self):
     """ Check we can plot one diffraction pattern from a v0.1 dir as a color map. """
     analyzer = DiffractionAnalysis(
         input_path=TestUtilities.generateTestFilePath('diffr_0.1'),
         pattern_indices=4)
     analyzer.plotPattern(operation=None)
     if RENDER_PLOT:
         plt.show()
Пример #8
0
    def testShannonPixelPhoton(self):
        """ Check if we can get the average number of photons per shannon pixel at a certain resolution"""
        analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                       pattern_indices="all",
                                       poissonize=True)

        # Get the number of photons per shannon pixel at the resolution of 10 angstrom
        analyzer.shannonPixelPhoton(10)
Пример #9
0
    def testOneNumpyPattern(self):
        """ Check if we can getting the numpy array of one snapshot """
        analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                       pattern_indices=1,
                                       poissonize=True)

        self.assertEqual(analyzer.npattern, 1)
        pattern_one = analyzer.numpyPattern()
        self.assertEqual(pattern_one.shape, (81, 81))
Пример #10
0
    def testWholeNumpyPattern(self):
        """ Check if we can getting the numpy array of the whole set of diffraction patterns """
        analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                       pattern_indices="all",
                                       poissonize=True)

        self.assertEqual(analyzer.npattern, 1000)
        patterns = analyzer.numpyPattern()
        self.assertEqual(patterns.shape, (1000, 81, 81))
    def testRadialProjection(self):
        """ Check that we can get two plots (resetting the iterator works.)"""
        analyzer = DiffractionAnalysis(input_path=self.__test_data, pattern_indices="all", poissonize=True)

        analyzer.logscale = False
        analyzer.plotRadialProjection()
        analyzer.plotRadialProjection(logscale=True)
        analyzer.plotRadialProjection(operation=numpy.std)
Пример #12
0
    def testGetQMap(self):
        """ Check the 2D reciprocal space mapping """
        analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                       pattern_indices="all",
                                       poissonize=True)

        qMap = analyzer.qMap
Пример #13
0
    def testSolidAngles(self):
        """ Check getting solid angles mapping """
        analyzer = DiffractionAnalysis(input_path=self.__test_data,
                                       pattern_indices="all",
                                       poissonize=True)

        sa = analyzer.solidAngles
    def testPlotAndStatistics(self):
        """ Check that we can get two plots (resetting the iterator works.)"""
        analyzer = DiffractionAnalysis(input_path=self.__test_data, pattern_indices="all", poissonize=True)

        analyzer.logscale = True
        analyzer.plotPattern(logscale=True)
        analyzer.statistics()
Пример #15
0
    def testShapedConstructionDefaults(self):
        """ Testing the construction of the class with non-default parameters. """

        # Construct the object.
        analyzer = DiffractionAnalysis(input_path=self.__test_data, )

        self.assertIsInstance(analyzer, DiffractionAnalysis)
        self.assertIsInstance(analyzer, AbstractAnalysis)
        self.assertIsInstance(analyzer, object)

        self.assertIsInstance(analyzer.input_path, str)
        self.assertEqual(analyzer.input_path, self.__test_data)
        self.assertTrue(analyzer.poissonize)
        self.assertEqual(analyzer.pattern_indices, "all")
Пример #16
0
    def testAnimatePatterns(self):
        """ Test the animation feature. """

        # Setup the analyser with a sequence of patterns.
        analyzer = DiffractionAnalysis(
            input_path=self.__test_data,
            pattern_indices=list(range(1, 11)),
        )

        # Check exceptions on faulty path.
        self.assertRaises(TypeError,
                          analyzer.animatePatterns,
                          output_path=["not", "a", "path"])
        self.assertRaises(IOError,
                          analyzer.animatePatterns,
                          output_path="/users/home/myself/animation.gif")

        # Check default behaviour.
        analyzer.animatePatterns(output_path=None)

        # Check output is present.
        animation_out_path = 'animated_patterns.gif'
        self.__files_to_remove.append(animation_out_path)
        self.assertIn(animation_out_path, os.listdir(os.getcwd()))

        # Check path is stored on object.
        self.assertEqual(analyzer._DiffractionAnalysis__animation_output_path,
                         os.path.join(os.getcwd(), animation_out_path))

        # Check exception on overwrite.
        self.assertRaises(IOError,
                          analyzer.animatePatterns,
                          output_path=animation_out_path)

        # Execute with parameter.
        animation_out_path = 'animation2.gif'
        self.__files_to_remove.append(animation_out_path)

        analyzer.animatePatterns(output_path=animation_out_path)

        # Check path is stored on object.
        self.assertEqual(analyzer._DiffractionAnalysis__animation_output_path,
                         os.path.join(os.getcwd(), animation_out_path))

        # Check file is present.
        self.assertIn(animation_out_path, os.listdir(os.getcwd()))
Пример #17
0
    def plot_diffr_vs_detector(self):
        """ Compare patterns before and after detector sim. """

        # Cleanup.
        #self.__files_to_remove.append('5mzd.pdb')
        #self.__files_to_remove.append('diffr.h5')
        #self.__dirs_to_remove.append('diffr')

        # Avoid crash due to multiple instances of G4RunManager
        del self._detector

        # Setup detector geometry.
        detector_panel = DetectorPanel(
            ranges={
                'fast_scan_min': 0,
                'fast_scan_max': 511,
                'slow_scan_min': 0,
                'slow_scan_max': 511
            },
            pixel_size=2.2e-4 * Units.meter,
            photon_response=1.0,
            distance_from_interaction_plane=0.13 * Units.meter,
            corners={
                'x': -256,
                'y': -256
            },
        )

        detector_geometry = DetectorGeometry(panels=[detector_panel])

        # Setup photon beam.
        beam = PhotonBeamParameters(
            photon_energy=4.96e3 * Units.electronvolt,
            beam_diameter_fwhm=1.0e-6 * Units.meter,
            pulse_energy=1.0e-3 * Units.joule,
            photon_energy_relative_bandwidth=0.001,
            divergence=1e-3 * Units.radian,
            photon_energy_spectrum_type="SASE",
        )

        # Setup and run the diffraction sim.
        diffraction_parameters = SingFELPhotonDiffractorParameters(
            uniform_rotation=None,
            calculate_Compton=False,
            number_of_diffraction_patterns=1,
            detector_geometry=detector_geometry,
            beam_parameters=beam,
            sample="5mzd.pdb",
            forced_mpi_command='mpirun -np 1',
        )

        photon_diffractor = SingFELPhotonDiffractor(
            parameters=diffraction_parameters,
            output_path='diffr',
        )

        photon_diffractor.backengine()
        photon_diffractor.saveH5()

        analysis1 = DiffractionAnalysis(photon_diffractor.output_path,
                                        pattern_indices=[1],
                                        poissonize=True)
        analysis1.plotPattern(
            operation=None,
            logscale=False,
        )

        parameters = XCSITPhotonDetectorParameters(
            detector_type="AGIPDSPB",
            patterns=[0],
        )

        detector = XCSITPhotonDetector(
            parameters=parameters,
            input_path="diffr.h5",
            output_path="detector_out.h5",
        )

        detector._readH5()
        detector.backengine()
        detector.saveH5()

        # Weak test Check we have photons in the signal.
        pattern = h5py.File("detector_out.h5", 'r')['data/0000001/data'].value

        analysis2 = DiffractionAnalysis(detector.output_path,
                                        pattern_indices=[1],
                                        poissonize=True)
        analysis2.plotPattern(
            operation=None,
            logscale=False,
        )

        mpl.pyplot.show()
Пример #18
0
    sig_arr = linear(diffr_data, *sigs_popt)
    diffr_noise = np.random.normal(diffr_data * mu, sig_arr)
    return diffr_noise


def getPopt(sigs):
    """Get the fitting parametters for predicting sigmas"""
    xdata = np.arange(len(sigs))
    ydata = sigs
    my_fitting = curve_fitting(linear, xdata, ydata)
    return my_fitting.popt


# %%
diffr_data = '/gpfs/exfel/data/user/juncheng/EMCProject/src/controller/s10/diffr.h5'
diffr_analyzer = DiffractionAnalysis(diffr_data, 1, poissonize=False)
diffr_pattern = diffr_analyzer.numpyPattern()


# %%
def linear(x, a, b):
    return a * x + b


def func_sq(x, a, b, c):
    return a * x**2 + b * x + c


# mu, sigs_popt, diffr_fn, emc_out
fwhms = np.array([49.3, 56.4, 66.4])
sigs = fwhms / 2.355
 def testPlotRMSPattern(self):
     """ Check we can plot the rms diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data)
     analyzer.plotPattern(operation=numpy.std)
     plt.show()
 def testPlotPatternDefault(self):
     """ Check we the sum image of all patterns is plotted by default. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data)
     analyzer.plotPattern()
     plt.show()
 def testPlotOnePatternPoissonized(self):
     """ Check we can plot one diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data, pattern_indices=1)
     analyzer.plotPattern()
     plt.show()
Пример #22
0
 def testPlotAvgPattern(self):
     """ Check we can plot the average diffraction pattern as a color map. """
     analyzer = DiffractionAnalysis(input_path=self.__test_data)
     analyzer.plotPattern(operation=numpy.mean)
     if RENDER_PLOT:
         plt.show()
Пример #23
0
def SimExRead(idxs):
    diffr_analyzer = DiffractionAnalysis(diffr_data, idxs, poissonize=False)
    diffr_pattern = diffr_analyzer.numpyPattern()