Beispiel #1
0
async def test_exporter_inclusion(event_loop, exporter, options, tmp_path, dry_run):
    mat1 = Material("Mat1", {79: 0.5, 47: 0.5}, 2.0)
    mat2 = Material("Mat2", {29: 0.5, 30: 0.5}, 3.0)
    options.sample = InclusionSample(mat1, mat2, 10e-6)

    await exporter.export(options, tmp_path, dry_run=dry_run)
    _test_export(tmp_path, 2, 2, dry_run)
Beispiel #2
0
def create_model_sample(data, density_start = None, density_end = None):
    elements_data = get_elements_data(data)
    
    colors = generate_colors(steps = len(data) - 1)
    densities = generate_densities(elements_data, density_start, density_end)
    
    material_start, material_end = generate_end_materials(elements_data, colors, density_start, density_end)
    
    sample = VerticalLayerSample(material_start, material_end)
    
    # Iterate through all regions
    for i in range(1, len(data) - 1): # create the remaining regions (in the middle)
        density = densities[i]
        color = colors[i]
        material = Material(
                            name = f'region_{i}',
                            composition = to_weight_fraction(dict(elements_data.iloc[i])),
                            density_kg_per_m3 = density,
                            color = color)
        sample.add_layer(material, thickness_m = data[THICKNESS].iloc[i] / 1e6) # thickness is in micrometer
        
    # creating dummy materials to match template
    dummy_material = Material.from_formula('H', color = None, density_kg_per_m3 = MIN_DENSITY)
    for i in range(TEMPLATE_NUM_REGIONS - len(data)):
        sample.add_layer(dummy_material, thickness_m = MIN_THICKNESS)
    
    return sample
    def test_convert_geometry(self):
        self.ops.geometry = [Substrate(Material.pure(29)),
                             Inclusion(Material.pure(29), Material.pure(30), 10e-6)]

        opss = self.converter.convert(self.ops)

        self.assertEqual(1, len(opss))
Beispiel #4
0
 def testhorizontallayers5(self):
     sample = HorizontalLayerSample(Material.pure(39))
     sample.add_layer(Material.pure(40), 20e-9)
     sample.add_layer(Material.pure(41), 20e-9)
     sample.add_layer(Material.pure(42), 20e-9)
     sample.add_layer(Material.pure(44), 20e-9)
     self._run_and_test(sample)
Beispiel #5
0
 def testconvert_parse(self):
     handler = KRatioAnalysisHDF5Handler()
     detector = self.create_basic_photondetector()
     standard_materials = {29: Material.from_formula('CuZn'),
                           28: Material.from_formula('NiAl')}
     analysis = KRatioAnalysis(detector, standard_materials)
     analysis2 = self.convert_parse_hdf5handler(handler, analysis)
     self.assertEqual(analysis2, analysis)
Beispiel #6
0
async def test_exporter_verticallayers_couple(
    event_loop, exporter, options, tmp_path, dry_run
):
    mat1 = Material("Mat1", {79: 0.5, 47: 0.5}, 2.0)
    mat2 = Material("Mat2", {29: 0.5, 30: 0.5}, 3.0)
    options.sample = VerticalLayerSample(mat1, mat2)

    await exporter.export(options, tmp_path, dry_run=dry_run)
    _test_export(tmp_path, 2, 2, dry_run)
Beispiel #7
0
    def test__eq__(self):
        m2 = Material('Pure Cu', {29: 1.0}, 8960.0)
        self.assertEqual(m2, self.m)

        m2 = Material('Pure Cu', {29: 1.0}, 8961.0)
        self.assertNotEqual(m2, self.m)

        m2 = Material('Pure Cu', {29: 0.5, 30: 0.5}, 8960.0)
        self.assertNotEqual(m2, self.m)
Beispiel #8
0
def test_material_getparameters_validate(parameter_types, error_count):
    material = Material("TiCrCu", {22: 0.2, 24: 0.2, 29: 0.6})
    parameters = material.get_parameters(lambda options: material)

    # Set parameter types
    for parameter, parameter_type in zip(parameters, parameter_types):
        parameter.type_ = parameter_type

    errors = parameters[0].validate(None)
    assert len(errors) == error_count
Beispiel #9
0
async def test_exporter_horizontallayers(
    event_loop, exporter, options, tmp_path, dry_run
):
    mat1 = Material("Mat1", {79: 0.5, 47: 0.5}, 2.0)
    mat2 = Material("Mat2", {29: 0.5, 30: 0.5}, 3.0)
    options.sample = HorizontalLayerSample(mat1)
    options.sample.add_layer(mat2, 10e-9)

    await exporter.export(options, tmp_path, dry_run=dry_run)
    _test_export(tmp_path, 2, 2, dry_run)
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.h = SubstrateXMLHandler()

        self.obj = Substrate([Material.pure(29), Material.pure(30)], 1.1, 2.2)

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:substrate xmlns:mc="http://pymontecarlo.sf.net" rotation="2.2" tilt="1.1"><materials><mc:material _index="1" density="8960.0" name="Copper"><composition><element weightFraction="1.0" z="29" /></composition></mc:material><mc:material _index="2" density="7140.0" name="Zinc"><composition><element weightFraction="1.0" z="30" /></composition></mc:material></materials><body material="1,2" /></mc:substrate>')
        self.element = etree.parse(source).getroot()
Beispiel #11
0
    def testbuild(self):
        b = LayeredSampleBuilderMock()
        b.add_layer(Material.pure(29), 10)
        b.add_layer(Material.pure(30), 20)

        samples = b.build()
        self.assertEqual(1, len(samples))

        sample = samples[0]
        self.assertEqual(2, len(sample.layers))
Beispiel #12
0
 def testverticallayers10(self):
     sample = VerticalLayerSample(Material.pure(39), Material.pure(40))
     sample.add_layer(Material.pure(41), 20e-9)
     sample.add_layer(Material.pure(42), 20e-9)
     sample.add_layer(Material.pure(44), 20e-9)
     sample.add_layer(Material.pure(45), 20e-9)
     sample.add_layer(Material.pure(46), 20e-9)
     sample.add_layer(Material.pure(47), 20e-9)
     sample.add_layer(Material.pure(48), 20e-9)
     sample.add_layer(Material.pure(49), 20e-9)
     self._run_and_test(sample)
Beispiel #13
0
def test_layeredsamplebuilderbase_twomaterials(layeredbuilder):
    layerbuilder = layeredbuilder.add_layer(Material.pure(29), 10)
    layerbuilder.add_material(Material.pure(30))

    samples = layeredbuilder.build()
    assert len(layeredbuilder) == 2
    assert len(samples) == 2

    sample = samples[0]
    assert len(sample.layers) == 1
    assert sample.layers[0].thickness_m == pytest.approx(10.0, abs=1e-4)
Beispiel #14
0
    def testset_color_set(self):
        Material.set_color_set(['#00FF00', '#0000FF'])

        m = Material.pure(13)
        self.assertEqual('#00FF00', m.color)

        m = Material.pure(14)
        self.assertEqual('#0000FF', m.color)

        m = Material.pure(15)
        self.assertEqual('#00FF00', m.color)
Beispiel #15
0
    def testbuild2(self):
        b = LayeredSampleBuilderMock()
        bl = b.add_layer(Material.pure(29), 10)
        bl.add_material(Material.pure(30))

        samples = b.build()
        self.assertEqual(2, len(samples))

        sample = samples[0]
        self.assertEqual(1, len(sample.layers))
        self.assertAlmostEqual(10, sample.layers[0].thickness_m, 4)
Beispiel #16
0
def test_layeredsamplebuilderbase(layeredbuilder):
    layeredbuilder = LayeredSampleBuilderMock()
    layeredbuilder.add_layer(Material.pure(29), 10)
    layeredbuilder.add_layer(Material.pure(30), 20)

    samples = layeredbuilder.build()
    assert len(layeredbuilder) == 1
    assert len(samples) == 1

    sample = samples[0]
    assert len(sample.layers) == 2
Beispiel #17
0
def test_material_pure_widget(qtbot, material_pure_widget):
    button = material_pure_widget.wdg_periodic_table._group.button(13)
    qtbot.mouseClick(button, QtCore.Qt.LeftButton)

    button = material_pure_widget.wdg_periodic_table._group.button(29)
    qtbot.mouseClick(button, QtCore.Qt.LeftButton)

    materials = material_pure_widget.materials()

    assert len(materials) == 2
    assert Material.pure(13) in materials
    assert Material.pure(29) in materials
Beispiel #18
0
def generate_end_materials(elements_data, colors, density_start = None, density_end = None):
    material_start = Material(
                                name = 'substrate_start',
                                composition = to_weight_fraction(dict(elements_data.iloc[0])), # create the first region
                                density_kg_per_m3 = density_start,
                                color = colors[0] if colors else None)
    material_end = Material(
                                name = 'substrate_end',
                                composition = to_weight_fraction(dict(elements_data.iloc[-1])), # create the last region
                                density_kg_per_m3 = density_end,
                                color = colors[-1] if colors else None)
    return material_start, material_end
    def setUp(self):
        TestCase.setUp(self)

        self.g1 = VerticalLayers(Material.pure(29), Material.pure(30))
        self.g1.add_layer(Material.pure(31), 500.0)

        self.g2 = VerticalLayers(Material.pure(29), Material.pure(30))
        self.g2.add_layer(Material.pure(29), 100.0)
        self.g2.add_layer(Material.pure(32), 200.0)

        self.g3 = VerticalLayers(Material.pure(29), Material.pure(30))
        self.g3.add_layer(Material.pure(31), 500.0)
        self.g3.depth_m = 400.0
Beispiel #20
0
    def testexport_multilayers2(self):
        # Options
        mat1 = Material('Mat1', {79: 0.5, 47: 0.5}, 2.0)
        mat2 = Material('Mat2', {29: 0.5, 30: 0.5}, 3.0)
        mat3 = Material('Mat3', {13: 0.5, 14: 0.5}, 4.0)

        sample = HorizontalLayerSample()
        sample.add_layer(mat1, 15e-9)
        sample.add_layer(mat2, 25e-9)
        sample.add_layer(mat3, 55e-9)
        self.options.sample = sample

        # Export
        self.e.export(self.options, self.tmpdir)

        # Test
        filepaths = glob.glob(os.path.join(self.tmpdir, '*.sim'))
        self.assertEqual(1, len(filepaths))

        casfile = File()
        casfile.readFromFilepath(filepaths[0])
        simdata = casfile.getOptionSimulationData()
        regionops = simdata.getRegionOptions()

        self.assertEqual(3, regionops.getNumberRegions())

        region = regionops.getRegion(0)
        elements = list(map(operator.attrgetter('Z'), region.getElements()))
        self.assertAlmostEqual(mat1.density_kg_per_m3 / 1000.0, region.Rho, 4)
        self.assertEqual('Mat1', region.Name)
        self.assertEqual(2, len(elements))
        self.assertTrue(79 in elements)
        self.assertTrue(47 in elements)

        region = regionops.getRegion(1)
        elements = list(map(operator.attrgetter('Z'), region.getElements()))
        self.assertAlmostEqual(mat2.density_kg_per_m3 / 1000.0, region.Rho, 4)
        self.assertEqual('Mat2', region.Name)
        self.assertEqual(2, len(elements))
        self.assertTrue(29 in elements)
        self.assertTrue(30 in elements)

        region = regionops.getRegion(2)
        elements = list(map(operator.attrgetter('Z'), region.getElements()))
        self.assertAlmostEqual(mat3.density_kg_per_m3 / 1000.0, region.Rho, 4)
        self.assertEqual('Mat3', region.Name)
        self.assertEqual(2, len(elements))
        self.assertTrue(13 in elements)
        self.assertTrue(14 in elements)
Beispiel #21
0
def test_material_getparameters_parametertype(parameter_types,
                                              expected_composition):
    material = Material("TiCrCu", {22: 0.2, 24: 0.2, 29: 0.6})
    parameters = material.get_parameters(lambda options: material)

    # Set parameter types
    for parameter, parameter_type in zip(parameters, parameter_types):
        parameter.type_ = parameter_type

    # Set titanium concentration
    parameters[0].set_value(None, 0.5)

    # Test
    for z, expected_wf in expected_composition.items():
        assert material.composition[z] == pytest.approx(expected_wf, abs=1e-6)
Beispiel #22
0
def create_homogeneous_sample(data, density_start = None, density_end = None):
    '''
    Function to create a list of substrate samples for Xray signal reference
    input: dataframe of atomic fractions at various positions
    output: list[Substrate]
    '''
    elements_data = get_elements_data(data)
    
    colors = generate_colors(steps = len(data) - 1)
    densities = generate_densities(elements_data, density_start, density_end)

    # 1. Creating materials at both ends
    material_start, material_end = generate_end_materials(elements_data, colors, density_start, density_end)
    materials = [material_start, material_end]
    
     # 2. Iterate through all regions, create the material representations
    for i in range(1, len(data) - 1):
        density = densities[i]
        color = colors[i]
        material = Material(
                            name = f'region_{i}',
                            composition = to_weight_fraction(dict(elements_data.iloc[i])),
                            density_kg_per_m3 = density,
                            color = color)
        materials.append(material)
        
    # 3. Creating substrate sample from the materials
    substrate_list = [SubstrateSample(mat) for mat in materials]

    return substrate_list
    def __init__(self, tilt, rotation):
        _Geometry.__init__(self, tilt, rotation)

        mat = Material.pure(29)
        self.bodies = [_Body(self, mat),
                       _Body(self, VACUUM),
                       _Body(self, mat)]
Beispiel #24
0
    def testexport_spectrum(self):
        # Create options
        mat = Material({
            79: 0.5,
            47: 0.5
        },
                       'Mat1',
                       absorption_energy_eV={ELECTRON: 123.0})

        ops = Options()
        ops.beam.energy_eV = 1234
        ops.beam.diameter_m = 25e-9
        ops.geometry.body.material = mat
        ops.limits.add(ShowersLimit(5678))
        ops.detectors['spectrum'] = \
            PhotonSpectrumDetector((radians(30), radians(40)), (0, radians(360.0)),
                                   500, (0, 1234))

        # Export to WinX-Ray options
        wxrops = self.e.export_wxroptions(ops)

        # Test
        self.assertTrue(wxrops.isXrayCompute())
        self.assertTrue(wxrops.isXrayComputeCharacteristic())
        self.assertAlmostEqual(35.0, wxrops.getTOA_deg(), 4)
        self.assertAlmostEqual(55, wxrops.getAngleThetaDetector_deg(), 4)
        self.assertAlmostEqual(180.0, wxrops.getAnglePhiDetector_deg(), 4)
        self.assertEqual(EvPerChannel.TYPE_5, wxrops.getTypeEVChannel())
        self.assertEqual(246, wxrops.getNumberChannel())
 def pure(cls, z, absorption_energy_eV=None, elastic_scattering=(0.0, 0.0),
          cutoff_energy_inelastic_eV=50.0, cutoff_energy_bremsstrahlung_eV=50.0,
          interaction_forcings=None, maximum_step_length_m=1e20):
     mat = _Material.pure(z, absorption_energy_eV)
     return cls(mat.composition, mat.name, mat.density_kg_m3, mat.absorption_energy_eV,
                elastic_scattering, cutoff_energy_inelastic_eV, cutoff_energy_bremsstrahlung_eV,
                interaction_forcings, maximum_step_length_m)
Beispiel #26
0
def estimated_builder(builder):
    program_mock_added = False
    if not builder.programs:
        builder.add_program(ProgramMock())
        program_mock_added = True

    beam_mock_added = False
    if not builder.beams:
        builder.add_beam(PencilBeam(10e3))
        beam_mock_added = True

    sample_mock_added = False
    if not builder.samples:
        builder.add_sample(SubstrateSample(Material.pure(26)))
        sample_mock_added = True

    try:
        yield builder

    finally:
        if program_mock_added:
            builder.programs.clear()
        if beam_mock_added:
            builder.beams.clear()
        if sample_mock_added:
            builder.samples.clear()
Beispiel #27
0
def simulation():
    program = ProgramMock()
    beam = GaussianBeam(15e3, 10e-9)
    sample = SubstrateSample(Material.pure(29))
    detector = PhotonDetector("xray", math.radians(40.0))
    analyses = [PhotonIntensityAnalysis(detector)]
    tags = ["basic", "test"]
    options = Options(program, beam, sample, analyses, tags)

    results = []

    analysis = PhotonIntensityAnalysis(detector)
    builder = EmittedPhotonIntensityResultBuilder(analysis)
    builder.add_intensity((29, "Ka1"), 1.0, 0.1)
    builder.add_intensity((29, "Ka2"), 2.0, 0.2)
    builder.add_intensity((29, "Kb1"), 4.0, 0.5)
    builder.add_intensity((29, "Kb3"), 5.0, 0.7)
    builder.add_intensity((29, "Kb5I"), 1.0, 0.1)
    builder.add_intensity((29, "Kb5II"), 0.5, 0.1)
    builder.add_intensity((29, "Ll"), 3.0, 0.1)
    results.append(builder.build())

    analysis = KRatioAnalysis(detector)
    builder = KRatioResultBuilder(analysis)
    builder.add_kratio((29, "Ka1"), 1.0, 1.0)
    builder.add_kratio((29, "Ka2"), 2.0, 1.0)
    builder.add_kratio((29, "Kb1"), 0.5, 1.0)
    builder.add_kratio((29, "Kb3"), 1.5, 1.0)
    builder.add_kratio((29, "Kb5I"), 1.0, 1.0)
    builder.add_kratio((29, "Kb5II"), 0.5, 1.0)
    builder.add_kratio((29, "Ll"), 2.0, 1.0)
    results.append(builder.build())

    return Simulation(options, results)
Beispiel #28
0
def test_substratesample_getparameters(sample):
    parameters = sample.get_parameters(lambda options: sample)
    assert len(parameters) == 1

    sample.material = Material.from_formula("CaSiO3")
    parameters = sample.get_parameters(lambda options: sample)
    assert len(parameters) == 4
Beispiel #29
0
def test_lazylowestenergyxrayline(options, z, beam_energy_eV,
                                  minimum_energy_eV, expected):
    options.beam.energy_eV = beam_energy_eV
    options.sample.material = Material.pure(z)

    assert LazyLowestEnergyXrayLine(minimum_energy_eV).apply(
        None, options) == expected
Beispiel #30
0
 def testvalidate_analysis_kratio(self):
     detector = PhotonDetector('det', 1.1, 2.2)
     analysis = KRatioAnalysis(detector)
     analysis.add_standard_material(13, Material.pure(13))
     analysis2 = self.v.validate_analysis(analysis, self.options)
     self.assertEqual(analysis2, analysis)
     self.assertIsNot(analysis2, analysis)
    def testcalculate_composition(self):
        # Wildcard
        composition = Material.calculate_composition({29: 0.7, 30: '?'})

        self.assertIn(29, composition)
        self.assertAlmostEqual(0.7, composition[29], 4)
        self.assertIn(30, composition)
        self.assertAlmostEqual(0.3, composition[30], 4)

        # Multiple wildcards
        composition = Material.calculate_composition({29: '?', 30: '?'})

        self.assertIn(29, composition)
        self.assertAlmostEqual(0.5, composition[29], 4)
        self.assertIn(30, composition)
        self.assertAlmostEqual(0.5, composition[30], 4)
Beispiel #32
0
    def testvalidate_material_exception(self):
        material = Material(' ', {120: 0.5}, -1.0, 'blah')
        self.assertRaises(ValidationError, self.v.validate_material, material,
                          self.options)

        errors = set()
        self.v._validate_material(material, self.options, errors)
        self.assertEqual(5, len(errors))
Beispiel #33
0
    def get_standard_material(self, z):
        if z in self.standard_materials:
            return self.standard_materials[z]

        if z in self.DEFAULT_NONPURE_STANDARD_MATERIALS:
            return self.DEFAULT_NONPURE_STANDARD_MATERIALS[z]

        return Material.pure(z)
Beispiel #34
0
def options():
    program = Casino2Program(number_trajectories=50)
    beam = GaussianBeam(15e3, 10e-9)
    sample = SubstrateSample(Material.pure(29))
    detector = PhotonDetector("xray", math.radians(40.0))
    analyses = [PhotonIntensityAnalysis(detector)]
    tags = ["basic", "test"]
    return Options(program, beam, sample, analyses, tags)
Beispiel #35
0
 def materials(self):
     try:
         formula = self.field_formula.formula()
         density_kg_per_m3 = self.field_density.density_kg_per_m3()
         color = self.field_color.color()
         return (Material.from_formula(formula, density_kg_per_m3, color), )
     except:
         return ()
Beispiel #36
0
def options():
    program = PenepmaProgram(number_trajectories=100)
    program.exporter.dump_interval_s = 2
    beam = CylindricalBeam(15e3, 10e-9)
    sample = SubstrateSample(Material.pure(29))
    detector = PhotonDetector("xray", math.radians(40.0))
    analyses = [PhotonIntensityAnalysis(detector)]
    tags = ["basic", "test"]
    return Options(program, beam, sample, analyses, tags)
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.h = SphereXMLHandler()

        self.obj = Sphere(Material.pure(29), 123.456, 1.1, 2.2)

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:sphere xmlns:mc="http://pymontecarlo.sf.net" rotation="2.2" tilt="1.1"><materials><mc:material _index="1" density="8960.0" name="Copper"><composition><element weightFraction="1.0" z="29" /></composition></mc:material></materials><body diameter="123.456" material="1" /></mc:sphere>')
        self.element = etree.parse(source).getroot()
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.ops = Options()
        self.ops.beam = PencilBeam(15e3)
        self.ops.geometry = Substrate(Material.pure(29))
        self.ops.detectors['det1'] = TimeDetector()
        self.ops.limits.add(ShowersLimit(5678))
        self.ops.models.add(ELASTIC_CROSS_SECTION.rutherford)
        self.ops.models.add(MASS_ABSORPTION_COEFFICIENT.henke1993)

        self.converter = MockConverter()
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.h = HorizontalLayersXMLHandler()

        self.obj1 = HorizontalLayers(Material.pure(29), None, 1.1, 2.2)
        self.obj1.add_layer(Material.pure(30), 123.456)
        self.obj1.add_layer(Material.pure(31), 456.789)

        self.obj2 = HorizontalLayers()
        self.obj2.add_layer(Material.pure(30), 123.456)
        self.obj2.add_layer(VACUUM, 50.0)
        self.obj2.add_layer(Material.pure(31), 456.789)

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:horizontalLayers xmlns:mc="http://pymontecarlo.sf.net" rotation="2.2" tilt="1.1"><materials><mc:material _index="1" density="7140.0" name="Zinc"><composition><element weightFraction="1.0" z="30" /></composition></mc:material><mc:material _index="2" density="5910.0" name="Gallium"><composition><element weightFraction="1.0" z="31" /></composition></mc:material><mc:material _index="3" density="8960.0" name="Copper"><composition><element weightFraction="1.0" z="29" /></composition></mc:material></materials><substrate material="3" /><layers><layer material="1" thickness="123.456" /><layer material="2" thickness="456.789" /></layers></mc:horizontalLayers>')
        self.element1 = etree.parse(source).getroot()

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:horizontalLayers xmlns:mc="http://pymontecarlo.sf.net" rotation="0.0" tilt="0.0"><materials><mc:material _index="1" density="7140.0" name="Zinc"><composition><element weightFraction="1.0" z="30" /></composition></mc:material><mc:material _index="2" density="5910.0" name="Gallium"><composition><element weightFraction="1.0" z="31" /></composition></mc:material></materials><layers><layer material="1" thickness="123.456" /><layer material="0" thickness="50.0" /><layer material="2" thickness="456.789" /></layers></mc:horizontalLayers>')
        self.element2 = etree.parse(source).getroot()
    def setUp(self):
        TestCase.setUp(self)

        self.outputdir = tempfile.mkdtemp()
        self.workdir = tempfile.mkdtemp()

        ops = Options('test')
        ops.beam.energy_keV = 10
        ops.geometry.body.material = Material.pure(29)
        ops.detectors['fraction'] = ElectronFractionDetector()
        ops.limits.add(ShowersLimit(1))
        self.ops = Converter().convert(ops)[0]

        self.worker = Worker(program)
    def setUp(self):
        TestCase.setUp(self)

        self.g1 = HorizontalLayers(Material.pure(29))
        self.g2 = HorizontalLayers(None) # No substrate
        self.g3 = HorizontalLayers(Material.pure(29)) # Empty layer

        self.g1.add_layer(Material.pure(30), 123.456)
        self.g1.add_layer(Material.pure(31), 456.789)

        self.g2.add_layer(Material.pure(30), 123.456)
        self.g2.add_layer(Material.pure(31), 456.789)

        self.g3.add_layer(Material.pure(30), 123.456)
        self.g3.add_layer(Material.pure(31), 456.789)
        self.g3.add_layer(VACUUM, 456.123)
    def testcomposition_from_formula(self):
        weightFractionAl = 0.21358626371988801
        weightFractionNa = 0.27298103136883051
        weightFractionB = 0.51343270491128157

        comp = Material.composition_from_formula('Al2Na3B12')
        self.assertAlmostEqual(weightFractionAl, comp[13], 4)
        self.assertAlmostEqual(weightFractionNa, comp[11], 4)
        self.assertAlmostEqual(weightFractionB, comp[5], 4)

        comp = Material.composition_from_formula('Al 2 Na 3 B 12')
        self.assertAlmostEqual(weightFractionAl, comp[13], 4)
        self.assertAlmostEqual(weightFractionNa, comp[11], 4)
        self.assertAlmostEqual(weightFractionB, comp[5], 4)

        comp = Material.composition_from_formula('Al2 Na3 B12')
        self.assertAlmostEqual(weightFractionAl, comp[13], 4)
        self.assertAlmostEqual(weightFractionNa, comp[11], 4)
        self.assertAlmostEqual(weightFractionB, comp[5], 4)

        self.assertRaises(ValueError, Material.composition_from_formula, 'Aq2 Na3 B12')

        comp = Material.composition_from_formula('Al2')
        self.assertAlmostEqual(1.0, comp[13], 4)
    def testpure(self):
        m = Material.pure(29)

        self.assertEqual('Copper', str(m))

        self.assertIn(29, m.composition)
        self.assertAlmostEqual(1.0, m.composition[29], 4)

        self.assertIn(29, self.m.composition_atomic)
        self.assertAlmostEqual(1.0, self.m.composition_atomic[29], 4)

        self.assertAlmostEqual(8.96, m.density_kg_m3 / 1000.0, 4)
        self.assertAlmostEqual(8.96, m.density_g_cm3, 4)

        self.assertAlmostEqual(50, m.absorption_energy_eV[ELECTRON], 4)
        self.assertAlmostEqual(50, m.absorption_energy_eV[PHOTON], 4)
    def test_convert_geometry_substrate(self):
        # Base options
        ops = Options(name="Test")
        mat = Material.pure(29, absorption_energy_eV={POSITRON: 63.4})
        ops.geometry = Substrate(mat)
        ops.limits.add(TimeLimit(100))

        # Convert
        self.converter._convert_geometry(ops)

        # Test
        self.assertEqual('Copper', str(ops.geometry.body.material))

        for material in ops.geometry.get_materials():
            self.assertAlmostEqual(0.1, material.elastic_scattering[0], 4)
            self.assertAlmostEqual(0.2, material.elastic_scattering[1], 4)
            self.assertAlmostEqual(51.2, material.cutoff_energy_inelastic_eV, 4)
            self.assertAlmostEqual(53.4, material.cutoff_energy_bremsstrahlung_eV, 4)
            self.assertAlmostEqual(63.4, material.absorption_energy_eV[POSITRON], 4)
            self.assertAlmostEqual(1e20, material.maximum_step_length_m, 4)
    def setUp(self):
        unittest.TestCase.setUp(self)

        self.h = VerticalLayersXMLHandler()

        self.obj1 = VerticalLayers(Material.pure(29), Material.pure(30), None,
                                   tilt_rad=1.1, rotation_rad=2.2)
        self.obj1.add_layer(Material.pure(31), 500.0)

        self.obj2 = VerticalLayers(Material.pure(29), Material.pure(30))
        self.obj2.add_layer(Material.pure(31), 500.0)
        self.obj2.depth_m = 400.0

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:verticalLayers xmlns:mc="http://pymontecarlo.sf.net" depth="inf" rotation="2.2" tilt="1.1"><materials><mc:material _index="1" density="5910.0" name="Gallium"><composition><element weightFraction="1.0" z="31" /></composition></mc:material><mc:material _index="2" density="8960.0" name="Copper"><composition><element weightFraction="1.0" z="29" /></composition></mc:material><mc:material _index="3" density="7140.0" name="Zinc"><composition><element weightFraction="1.0" z="30" /></composition></mc:material></materials><leftSubstrate material="2" /><rightSubstrate material="3" /><layers><layer material="1" thickness="500.0" /></layers></mc:verticalLayers>')
        self.element1 = etree.parse(source).getroot()

        etree.register_namespace('mc', 'http://pymontecarlo.sf.net')
        source = BytesIO(b'<mc:verticalLayers xmlns:mc="http://pymontecarlo.sf.net" depth="400.0" rotation="0.0" tilt="0.0"><materials><mc:material _index="1" density="8960.0" name="Copper"><composition><element weightFraction="1.0" z="29" /></composition></mc:material><mc:material _index="2" density="5910.0" name="Gallium"><composition><element weightFraction="1.0" z="31" /></composition></mc:material><mc:material _index="3" density="7140.0" name="Zinc"><composition><element weightFraction="1.0" z="30" /></composition></mc:material></materials><leftSubstrate material="1" /><rightSubstrate material="3" /><layers><layer material="2" thickness="500.0" /></layers></mc:verticalLayers>')
        self.element2 = etree.parse(source).getroot()
    def setUp(self):
        TestCase.setUp(self)

        self.g = Inclusion(Material.pure(29), Material.pure(30), 123.456)
 def testmaterial(self):
     self.g.body.material = [Material.pure(14), Material.pure(15)]
     self.assertEqual(2, len(self.g.body.material))
    def setUp(self):
        TestCase.setUp(self)

        self.g = Substrate(Material.pure(29))
    def setUp(self):
        TestCase.setUp(self)

        self.g = Sphere(Material.pure(29), 123.456)
    def testexpand(self):
        self.assertEqual(1, len(expand(self.g1)))

        self.g1.add_layer(Material.pure(79), [1.0, 2.0])
        self.assertEqual(2, len(expand(self.g1)))
    def __init__(self, composition, name=None, density_kg_m3=None, absorption_energy_eV=None,
                 elastic_scattering=(0.0, 0.0),
                 cutoff_energy_inelastic_eV=50.0, cutoff_energy_bremsstrahlung_eV=50.0,
                 interaction_forcings=None, maximum_step_length_m=1e15, *args, **kwargs):
        """
        Creates a new material.

        :arg name: name of the material
        :type name: :class:`str`

        :arg composition: composition in weight fraction.
            The composition is specified by a list of tuples.
            The first element of each tuple can either be the atomic number or
            the symbol of the element.
            It will automatically be converted to the atomic number.
            The second is the weight fraction between ]0.0, 1.0] or ``?``
            indicating that the weight fraction is unknown and shall be
            automatically calculated to make the total weight fraction equal
            to 1.0.
        :type composition: :class:`list`

        :arg density_kg_m3: material's density in kg/m3.
            If the density is ``None`` or less than 0 (default), it will be
            automatically calculated based on the density of the elements and
            their weight fraction.
        :type density_kg_m3: :class:`float`

        :arg elastic_scattering: elastic scattering coefficients.
            They can either be specified as a :class:`tuple`: ``(C1, C2)`` or
            as a single :class:`float` value, where ``C1=C2``.
            The value of C1 or C2 must be between 0.0 and 0.2 inclusively.
        :type elastic_scattering: :class:`tuple` or :class:`float`

        :arg cutoff_energy_inelastic_eV: cutoff energy for inelastic collisions
            (in eV).

        :arg cutoff_energy_bremsstrahlung_eV: cutoff energy for Bremsstrahlung
            emission (in eV).

        :arg interaction_forcings: interaction forcing(s)

        :arg maximum_step_length_m: maximum length of an electron trajectory
        """
        _Material.__init__(self, composition, name, density_kg_m3, absorption_energy_eV)

        elastic_scattering = ElasticScattering(*elastic_scattering)
        if elastic_scattering.c1 < 0.0 or elastic_scattering.c1 > 0.2:
            raise ValueError('C1 must be between [0.0, 0.2]')
        if elastic_scattering.c2 < 0.0 or elastic_scattering.c2 > 0.2:
            raise ValueError('C2 must be between [0.0, 0.2]')
        self._elastic_scattering = elastic_scattering

        if cutoff_energy_inelastic_eV < 0.0:
            raise ValueError('Cutoff energy for inelastic collisions must be greater or equal to 0.0')
        self._cutoff_energy_inelastic_eV = cutoff_energy_inelastic_eV

        if cutoff_energy_inelastic_eV < 0.0:
            raise ValueError('Cutoff energy for Bremsstrahlung emission must be greater or equal to 0.0')
        self._cutoff_energy_bremsstrahlung_eV = cutoff_energy_bremsstrahlung_eV

        if interaction_forcings is None:
            interaction_forcings = set()
        self._interaction_forcings = frozenset(interaction_forcings)

        if maximum_step_length_m < 0.0:
            raise ValueError("Length must be greater than 0.0")
        if maximum_step_length_m > 1e20:
            warnings.warn('Maximum step length set to maximum value: 1e20')
            maximum_step_length_m = 1e20
        self._maximum_step_length_m = maximum_step_length_m
 def testphoton_range(self):
     material = Material.pure(29)
     transition = Transition(29, siegbahn='Ka1')
     self.assertAlmostEqual(8.4064e-7, photon_range(20e3, material, transition), 10)