Beispiel #1
0
def test_src_mir_det():
	'''This tests that source, multilayer mirror, and detector run without producing any errors.
	'''
	string1 = 'marxs/optics/data/A12113.txt'
	string2 = 'marxs/optics/data/ALSpolarization2.txt'
	a = 2**(-0.5)
	rotation1 = np.array([[a, 0, -a],
						  [0, 1, 0],
						  [a, 0, a]])
	rotation2 = np.array([[0, 0, 1],
						  [0, 1, 0],
						  [-1, 0, 0]])

	source = LabPointSource([10., 0., 0.], flux=100., energy=-1.)
	mirror = MultiLayerMirror(string1, string2, position=np.array([0., 0., 0.]), orientation=rotation1)
	detector = FlatDetector(1., position=np.array([0., 0., 10.]), orientation=rotation2, zoom = np.array([1, 100, 100]))

	photons = source.generate_photons(100)
	photons = mirror.process_photons(photons)
	photons = detector.process_photons(photons)
Beispiel #2
0
def test_src_mir_det():
    '''This tests that source, multilayer mirror, and detector run without producing any errors.
	'''
    string1 = 'marxs/optics/data/A12113.txt'
    string2 = 'marxs/optics/data/ALSpolarization2.txt'
    a = 2**(-0.5)
    rotation1 = np.array([[a, 0, -a], [0, 1, 0], [a, 0, a]])
    rotation2 = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])

    source = LabPointSource([10., 0., 0.], flux=100., energy=-1.)
    mirror = MultiLayerMirror(string1,
                              string2,
                              position=np.array([0., 0., 0.]),
                              orientation=rotation1)
    detector = FlatDetector(1.,
                            position=np.array([0., 0., 10.]),
                            orientation=rotation2,
                            zoom=np.array([1, 100, 100]))

    photons = source.generate_photons(100)
    photons = mirror.process_photons(photons)
    photons = detector.process_photons(photons)
    def defaultMirror(self, reflFile, testedPolarization):
        #mirrorData Defaults - reference files
        self.reflFile = reflFile
        self.testedPolarization = testedPolarization

        #mirror Defauls
        self.defaultMirrorOrientation = euler2mat(-np.pi / 4, 0, 0, 'syxz')
        self.defaultMirrorOrientation = np.dot(
            euler2mat(0, -np.pi / 2, 0, 'syxz'), self.defaultMirrorOrientation)

        self.defaultMirrorPosition = np.array([0, 0, 0])

        self.defaultMirrorPos4d = compose(self.defaultMirrorPosition,
                                          self.defaultMirrorOrientation,
                                          np.array([1, 24.5, 12]), np.zeros(3))

        mirror = MultiLayerMirror(self.reflFile,
                                  self.testedPolarization,
                                  pos4d=self.defaultMirrorPos4d)
        return mirror
Beispiel #4
0
def test_src_mir_det():
    '''This tests that source, multilayer mirror, and detector run without producing any errors.
    '''
    string1 = get_pkg_data_filename('data/A12113.txt', package='marxs.optics')
    string2 = get_pkg_data_filename('data/ALSpolarization2.txt',
                                    package='marxs.optics')
    a = 2**(-0.5)
    rotation1 = np.array([[a, 0, -a], [0, 1, 0], [a, 0, a]])
    rotation2 = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])

    source = LabPointSourceCone([10., 0., 0.], flux=100. / u.s)
    mirror = MultiLayerMirror(reflFile=string1,
                              testedPolarization=string2,
                              position=np.array([0., 0., 0.]),
                              orientation=rotation1)
    detector = FlatDetector(1.,
                            position=np.array([0., 0., 10.]),
                            orientation=rotation2,
                            zoom=np.array([1, 100, 100]))

    photons = source.generate_photons(100 * u.s)
    photons = mirror(photons)
    photons = detector(photons)
Beispiel #5
0
def sourceMirrorDetector(mirror='A12113', sourceAngle=0, time=1., sourceOffset=0, detOffset=0, source='C',
		apDims=[0.125, 0.125], V=10., I=0.1):
    '''Sets up and runs the following simulation.
    
    Layout:
    --------------------------------------
    Source                        Detector
      |                              ^
      |                             /|\
     \|/                             |
      v                              |
    Mirror  ->   (Grating)   ->   Mirror
    --------------------------------------
    
    
    Parameters
	----------
	mirror: string
		the serial number of the mirror (in the mirror reflectivity file's name)
	sourceAngle: float
		the angle the source is rotated from the +z axis (counter-clockwise looking from the +x axis)
	time: float
		the amount of time that is being simulated
	sourceOffset: float
		the distance between the center of the first mirror and the photons beam axis
		(in the direction of the +y axis before rotation)
	detOffset: float
		the distance between the center of the second mirror and the photons beam axis
		(in the direction of the +y axis before rotation)
	source: string OR 1D array of length 2
		if string: the chemical symbol/formula for the material of the source (ex: 'C' for carbon, or 'AlO' for aluminum oxide)
		if array: the mean and std. deviation for a normal energy distribution
	apDims: 1D array of length 2 OR None
		NOTE: the type of input to this parameter determines whether FarLabPointSource or LabPointSource is used
		if array: the y and z dimensions of the aperture for a far lab source
		if None: None is the input, this causes the program to use the slightly more realistic, but much slower, lab source
	V: float
		the voltage of the source in kV
	I: float
		the current of the source in mA
    '''
    
    # paths to mirror files
    string1 = './mirror_files/' + mirror + '.txt'
    string2 = './mirror_files/ALSpolarization.txt'
    
    # inputs not accounted for by parameters
    sourceDist = 8149.7
    sourceRadius = 192.
    apertureRadius = 20.
    sourceAngle *=  np.pi/180
    detDist = -9532.5
    detRadius = 50.
    detAngle = 0 * np.pi/180    # from the +z axis, counter-clockwise looking from the +x axis
    
    # calculate rotation matrices
    # looking from the axis of rotation the rotation is counter-clockwise
    r1 = euler2mat(np.pi/4, sourceAngle, 0, 'syxz')
    r2 = euler2mat(-np.pi/4, detAngle, 0, 'syxz')
    r3 = euler2mat(np.pi/2, detAngle, 0, 'syxz')
    r4 = euler2mat(np.pi/2, sourceAngle, 0, 'syxz')
    
    # choose an energy distribution based on the source
    if isinstance(source, basestring):
        energies = createEnergyTable(source, V_kV = V, I_mA = I)   # photons/sec/steradian
        rate = sum(energies[1])   # photons/sec/steradian
    elif hasattr(source, 'shape') and (source.shape == np.array([0,0]).shape):
        energies = normalEnergyFunc(source[0], source[1])
    else:
        print 'source must be a string describing the source material or a 1D array of length 2'

    # choose a model for the source based on whether aperture dimensions were given
    if apDims != None:
        solidAngle = apDims[0] * apDims[1] / (sourceRadius - apertureRadius)**2
        rate *= solidAngle
        source = FarLabPointSource([sourceDist, sourceRadius * np.sin(-sourceAngle), sourceRadius * np.cos(-sourceAngle)],
            position = [sourceDist, apertureRadius * np.sin(-sourceAngle), apertureRadius * np.cos(-sourceAngle)],
            energy = energies, flux = rate, orientation = r4, zoom = [1, apDims[0], apDims[1]])
    else:
        source = LabPointSource([sourceDist, sourceRadius * np.sin(sourceAngle), sourceRadius * np.cos(sourceAngle)],
            direction='-z', energy = energies, flux = 1e9)
    
    # initialize both mirrors and the detector
    mirror1 = MultiLayerMirror(string1, string2,
        position=np.array([sourceDist, sourceOffset * np.cos(sourceAngle), sourceOffset * np.sin(sourceAngle)]), orientation=r1)
    mirror2 = MultiLayerMirror(string1, string2,
        position=np.array([detDist, detOffset * np.cos(detAngle), detOffset * np.cos(detAngle)]), orientation=r2)
    detector = FlatDetector(pixsize=24.576e-3,
        position = np.array([detDist, detRadius * np.sin(-detAngle), detRadius * np.cos(-detAngle)]),
        zoom = np.array([1, 12.288, 12.288]), orientation = r3)
    #preDetector = FlatDetector(pixsize=24.576e-3, position = np.array([detDist + 20, 0, 0]), zoom = np.array([1, 100, 100]))
    #testDetector = FlatDetector(pixsize=24.576e-3, position = np.array([detDist + 1e4, 0, 0]), zoom = np.array([1, 50, 50]))
    '''
    photons = source.generate_photons(time)
    #photons = generateTestPhotons([sourceDist, sourceRadius * np.sin(sourceAngle), sourceRadius * np.cos(sourceAngle)])
    photons = mirror1.process_photons(photons)
    photons = photons[photons['probability'] > 0]
    photons = mirror2.process_photons(photons)
    photons = photons[photons['probability'] > 0]
    photons = detector.process_photons(photons)
    
    return photons
    '''
    # run the simulation
    parts = 8
    for i in range(0, parts):
        photons = source.generate_photons(time / parts)
        photons = mirror1.process_photons(photons)
        photons = photons[photons['probability'] > 0]
        #photons = testDetector.process_photons(photons)
        #photons = preDetector.process_photons(photons)
        #if i == 0:
        #   pre_all_photons = photons.copy()
        #else:
        #   pre_all_photons = vstack([pre_all_photons, photons])
        photons = mirror2.process_photons(photons)
        photons = photons[photons['probability'] > 0]
        photons = detector.process_photons(photons)
        if i == 0:
            all_photons = photons.copy()
        else:
            all_photons = vstack([all_photons, photons])
            #print all_photons
            
    #plotPoints(pre_all_photons, 50, 40, 'path_', angle = sourceAngle, all = False)

    return all_photons
class SourceMLMirror(OpticalElement):
	'''
	This is a point-cone source combined with a multilayer mirror. Its purpose is to simulate a polarized light source.

	Z+ is out of the screen. X+ is to the right. Y+ is upwards.

		   Source
		   	|
		   	|
		   	|
		   	MLMirror------>

		   	self.pos4d is a record of all the transformations on the ENTIRE setup as a whole.
		   	The source comes in by default from the local y direction.
		   	The photons exit by default in the local x direction

	Parameters
	----------
	reflFile:
		This is the pathway to the data file for the multiLayerMirror. 
	testedPolarization:
		This is the pathway to the polarization data file for the multilayer.
	openningAngle:
		steradians that span the range of directions for which the photons will randomly be generated
	sourceDistance:
		distance between the source and multilayer (mm)
	'''

	def defaultSource(self, openningAngle, sourceDistance):

		self.defaultSourcePosition = [0, sourceDistance,0]
		self.defaultSourceDirection = [0,-1,0]

		# Generate Source
		flux=100
		V=10
		I=0.1
		energies = createEnergyTable('C', V_kV = V, I_mA = I)
		source = LabPointSourceCone(self.defaultSourcePosition, delta = openningAngle , energy= energies, direction = self.defaultSourceDirection, flux = flux) # Generate photons from original source
		return source

	def defaultMirror(self,reflFile, testedPolarization):
		#mirrorData Defaults - reference files
		self.reflFile = reflFile
		self.testedPolarization = testedPolarization

		#mirror Defauls
		self.defaultMirrorOrientation = euler2mat(-np.pi/4, 0, 0, 'syxz')
		self.defaultMirrorOrientation = np.dot(euler2mat(0,-np.pi/2,0,'syxz'),self.defaultMirrorOrientation)


		self.defaultMirrorPosition = np.array([0,0,0])

		self.defaultMirrorPos4d = compose(self.defaultMirrorPosition, self.defaultMirrorOrientation, np.array([1, 24.5, 12]), np.zeros(3))

		mirror = MultiLayerMirror(self.reflFile, self.testedPolarization,
        pos4d = self.defaultMirrorPos4d); return mirror


	def __init__(self, reflFile, testedPolarization, openningAngle = 0.05, sourceDistance = 100, **kwargs):
		super(SourceMLMirror, self).__init__(**kwargs)
		self.defaultApparatusPos4d = self.pos4d

		# Generate Default Mirror
		self.mirror = self.defaultMirror(reflFile, testedPolarization)
		self.source = self.defaultSource(openningAngle, sourceDistance)
		'''Default Setup:
		Z+ is out of the screen. X+ is to the right. Y+ is upwards.

		   Source
		   	|
		   	|
		   	|
		   	MLMirror------>

		   	self.pos4d is a record of all the transformations on the ENTIRE setup as a whole.
		   	The source comes in by default from the local y direction.
		   	The photons exit by default in the local x direction
		'''

	def updateSource(self, position=None, openningAngle = None, direction = None):
		if position is None:
			position = self.source.position
		if openningAngle is None:
			openningAngle = self.source.deltaphi
		if direction is None:
			direction = self.source.dir
		flux = 100
		V = 10
		I = 0.1
		energies = createEnergyTable('C', V_kV = V, I_mA = I)
		self.source = LabPointSourceCone(position, delta = openningAngle, energy = energies, direction = direction, flux = flux)


	def updateMirror(self, positionMatrix):
		# Generate Mirror
		self.mirror = MultiLayerMirror(self.reflFile, self.testedPolarization, pos4d = positionMatrix)


	def __str__(self):

		report = "APPARATUS GEOMETRY ****************** (Global Coordinates) \n"
		report += "    -transformation record: \n" + str(self.pos4d)


		report += "\n \n"
		report += "CURRENT SETUP ****************** (Local Coordinates)\n"

		report += "Mirror:\n"

		report += "    -center: " + str(self.mirror.geometry['center']) + "\n"
		report += "    -norm: "+ str(self.mirror.geometry['plane']) + "\n"

		report += " \n \n"
		report += "Source:\n"
		report += "    -position: " + str(self.source.position) + "\n"
		report += "    -direction: " + str(self.source.dir) + "\n"
		report += "    -solid angle: " + str(self.source.deltaphi) + "\n"

		report += "\n \n RAW_mirror: \n"
		report += str(self.mirror.geometry)

		return report



	def generate_photons(self, exposureTime, probability_limit=5e-10):
                '''Generate Initial Photons

                Parameters
                ----------
                exposureTime : float
                probability_limit : float
                    Photons with a probability below this value will be discarded.
                    Set to a negative number ot keep all.
                '''
		photons = self.source.generate_photons(exposureTime)
		reflectedPhotons = self.mirror.process_photons(photons)# Removing photons with zero probability


		reflectedPhotons = reflectedPhotons[reflectedPhotons['probability'] > probability_limit]

		# Transform the reflected photons from the local coordinate system to the global coordinate system

		reflectedPhotons['dir'] = np.dot(self.pos4d, reflectedPhotons['dir'].T).T

		reflectedPhotons['pos'] = np.dot(self.pos4d, reflectedPhotons['pos'].T).T

		reflectedPhotons['polarization'] = np.dot(self.pos4d, reflectedPhotons['polarization'].T).T


		return reflectedPhotons



	def offset_mirror(self, offsetMatrix):
		# This is how we offset the mirror relative to its default position

		positionMatrix = np.dot(offsetMatrix, self.defaultMirrorPos4d)

		self.updateMirror(positionMatrix)

		# RESET SOURCE TO DO

	def move_mirror(self, moveMatrix):
		#This is how we move the mirror relative to its current position

		positionMatrix = np.dot(moveMatrix, self.mirror.pos4d)

		self.updateMirror(positionMatrix)

	def offset_source(self, offsetVector):
		# This is how we offset the source from its default position
		position = self.defaultSourcePosition + np.array(offsetVector)

		self.updateSource(position = position)

	def move_source(self,offsetVector):
		# This is how we move the mirror relative to its current position

		position = self.source.position + np.array(offsetVector)

		self.updateSource(position = position)

	def offset_apparatus(self,offsetMatrix):
		self.pos4d = np.dot(offsetMatrix, self.defaultApparatusPos4d)

	def move_apparatus(self, moveMatrix):
		self.pos4d = np.dot(moveMatrix, self.pos4d)
	def updateMirror(self, positionMatrix):
		# Generate Mirror
		self.mirror = MultiLayerMirror(self.reflFile, self.testedPolarization, pos4d = positionMatrix)
Beispiel #8
0
        return np.random.normal(mean, stdDev, n)
    return energyFunc


string1 = '../marxs/optics/data/A12113.txt'
string2 = '../marxs/optics/data/ALSpolarization2.txt'
a = 2**(-0.5)
rotation1 = np.array([[a, 0, -a],
					  [0, 1, 0],
					  [a, 0, a]])
rotation2 = np.array([[0, 0, 1],
					  [0, 1, 0],
					  [-1, 0, 0]])

source = LabPointSource([100., 0., 0.], direction='-x', energy = normalEnergyFunc(0.31, 0.003), flux = 1e9)
mirror = MultiLayerMirror(string1, string2, position=np.array([0., 0., 0.]), orientation=rotation1)
detector = FlatDetector(1., position=np.array([0., 0., 25.]), orientation=rotation2, zoom = np.array([1, 100, 100]))

photons = source.generate_photons(0.01)
photons = mirror.process_photons(photons)
photons = detector.process_photons(photons)

p = photons[photons['probability'] > 0]
r = np.random.uniform(size=len(p))

q = p[p['probability'] > r]

plt.clf()
fig = plt.figure()
ax = fig.gca()
ax.plot(q['det_x'], q['det_y'], '.')
class SourceMLMirror(OpticalElement):
    #this will also alllow the elements to wiggle later. RN it goes light source --> MLMirror
    # The mirror is at the center of this object

    def defaultSource(self, openningAngle, sourceDistance):

        self.defaultSourcePosition = [0, sourceDistance, 0]
        self.defaultSourceDirection = [0, -1, 0]

        # Generate Source
        flux = 100
        V = 10
        I = 0.1
        energies = createEnergyTable('C', V_kV=V, I_mA=I)
        source = LabPointSourceCone(
            self.defaultSourcePosition,
            delta=openningAngle,
            energy=energies,
            direction=self.defaultSourceDirection,
            flux=flux)  # Generate photons from original source
        return source

    def defaultMirror(self, reflFile, testedPolarization):
        #mirrorData Defaults - reference files
        self.reflFile = reflFile
        self.testedPolarization = testedPolarization

        #mirror Defauls
        self.defaultMirrorOrientation = euler2mat(-np.pi / 4, 0, 0, 'syxz')
        self.defaultMirrorOrientation = np.dot(
            euler2mat(0, -np.pi / 2, 0, 'syxz'), self.defaultMirrorOrientation)

        self.defaultMirrorPosition = np.array([0, 0, 0])

        self.defaultMirrorPos4d = compose(self.defaultMirrorPosition,
                                          self.defaultMirrorOrientation,
                                          np.array([1, 24.5, 12]), np.zeros(3))

        mirror = MultiLayerMirror(self.reflFile,
                                  self.testedPolarization,
                                  pos4d=self.defaultMirrorPos4d)
        return mirror

    def __init__(self,
                 reflFile,
                 testedPolarization,
                 openningAngle=0.05,
                 sourceDistance=500,
                 **kwargs):
        super(SourceMLMirror, self).__init__(**kwargs)
        self.defaultApparatusPos4d = self.pos4d

        # Generate Default Mirror
        self.mirror = self.defaultMirror(reflFile, testedPolarization)
        self.source = self.defaultSource(openningAngle, sourceDistance)
        '''Default Setup:
		Z+ is out of the screen. X+ is to the right. Y+ is upwards.

		   Source
		   	|
		   	|
		   	|
		   	MLMirror------>

		   	self.pos4d is a record of all the transformations on the ENTIRE setup as a whole.
		   	The source comes in by default from the local y direction.
		   	The photons exit by default in the local x direction
		'''

    def updateSource(self, position=None, openningAngle=None, direction=None):
        if position is None:
            position = self.source.position
        if openningAngle is None:
            openningAngle = self.source.deltaphi
        if direction is None:
            direction = self.source.dir
        flux = 100
        V = 10
        I = 0.1
        energies = createEnergyTable('C', V_kV=V, I_mA=I)
        self.source = LabPointSourceCone(position,
                                         delta=openningAngle,
                                         energy=energies,
                                         direction=direction,
                                         flux=flux)

    def updateMirror(self, positionMatrix):
        # Generate Mirror
        self.mirror = MultiLayerMirror(self.reflFile,
                                       self.testedPolarization,
                                       pos4d=positionMatrix)

    def __str__(self):

        report = "APPARATUS GEOMETRY ****************** (Global Coordinates) \n"
        report += "    -transformation record: \n" + str(self.pos4d)

        report += "\n \n"
        report += "CURRENT SETUP ****************** (Local Coordinates)\n"

        report += "Mirror:\n"

        report += "    -center: " + str(self.mirror.geometry['center']) + "\n"
        report += "    -norm: " + str(self.mirror.geometry['plane']) + "\n"

        report += " \n \n"
        report += "Source:\n"
        report += "    -position: " + str(self.source.position) + "\n"
        report += "    -direction: " + str(self.source.dir) + "\n"
        report += "    -solid angle: " + str(self.source.deltaphi) + "\n"

        report += "\n \n RAW_mirror: \n"
        report += str(self.mirror.geometry)

        return report

    def generate_photons(self, exposureTime):
        # Generate Initial Photons
        photons = self.source.generate_photons(exposureTime)
        reflectedPhotons = self.mirror.process_photons(
            photons)  # Removing photons with zero probability
        rowsToRemove = []

        for i in range(0, len(reflectedPhotons)):

            # Remove Photons that Miss
            if (reflectedPhotons[i]['probability'] == 0):
                rowsToRemove.append(i)

            # Remove negligible Photons
            if (reflectedPhotons[i]['probability'] <= (5e-10)):
                rowsToRemove.append(i)

        rowsToRemove = np.array(rowsToRemove)
        reflectedPhotons.remove_rows(rowsToRemove)

        # Transform the reflected photons from the local cooridinate system to the global coordinate system

        reflectedPhotons['dir'] = np.dot(self.pos4d,
                                         reflectedPhotons['dir'].T).T

        reflectedPhotons['pos'] = np.dot(self.pos4d,
                                         reflectedPhotons['pos'].T).T

        return reflectedPhotons

    def offset_mirror(self, offsetMatrix):
        # This is how we offset the mirror relative to its default position

        positionMatrix = np.dot(offsetMatrix, self.defaultMirrorPos4d)

        self.updateMirror(positionMatrix)

        # RESET SOURCE TO DO

    def move_mirror(self, moveMatrix):
        #This is how we move the mirror relative to its current position

        positionMatrix = np.dot(moveMatrix, self.mirror.pos4d)

        self.updateMirror(positionMatrix)

    def offset_source(self, offsetVector):
        # This is how we offset the source from its default position
        position = self.defaultSourcePosition + np.array(offsetVector)

        self.updateSource(position=position)

    def move_source(self, offsetVector):
        # This is how we move the mirror relative to its current position

        position = self.source.position + np.array(offsetVector)

        self.updateSource(position=position)

    def offset_apparatus(self, offsetMatrix):
        self.pos4d = np.dot(offsetMatrix, self.defaultApparatusPos4d)
 def updateMirror(self, positionMatrix):
     # Generate Mirror
     self.mirror = MultiLayerMirror(self.reflFile,
                                    self.testedPolarization,
                                    pos4d=positionMatrix)