Beispiel #1
0
def tmm(materials, wavelength, angle, polarization):
    """
    Calculates fraction of incident power transmitted/reflected for a multi-layer slab bounded on either side by air.
    Assumes slabs are infinite in the x and y directions and bounding layers are semi-infinite in z.
    Calculations are based on the transfer matrix approach; this program builds the matrix M based on the dynamical
    boundary matrices D and propagation matrices P for each slab.
    The output values are pulled from the matrix M.

    :param materials: List of Material objects defining the multi-layer slab.
    :param wavelength: Vacuum wavelength of the wave in nanometres.
    :param angle: Incident angle of the wave.
    :param polarization: Polarization of incoming wave. Can be either 'TE' or 'TM'.
    :return: Fraction of incident power transmitted, fraction of incident power reflected.
    """
    outer_material = Material(
        'Air')  # semi-infinite slabs of air outside the structure
    prev_material = outer_material
    D_0 = prev_material.dynamical_matrix(wavelength, angle, polarization)
    M = np.linalg.inv(D_0)
    for material in materials:
        angle = get_refraction_angle(prev_material, material, wavelength,
                                     angle)
        D_i = material.dynamical_matrix(wavelength, angle, polarization)
        P_i = material.propagation_matrix(wavelength, angle)
        M = M.dot(D_i).dot(P_i).dot(np.linalg.inv(D_i))
        prev_material = material
    angle = get_refraction_angle(prev_material, outer_material, wavelength,
                                 angle)
    D_out = outer_material.dynamical_matrix(wavelength, angle, polarization)
    M = M.dot(D_out)

    T = np.abs((1 / M[0, 0]))**2
    R = np.abs((M[1, 0] / M[0, 0]))**2
    return T, R
Beispiel #2
0
    def testFlatRenderer(self):
        sphere_color = Color(1.0, 2.0, 3.0)
        sphere = Sphere(transformation=translation(Vec(2, 0, 0)) *
                        scaling(Vec(0.2, 0.2, 0.2)),
                        material=Material(brdf=DiffuseBRDF(
                            pigment=UniformPigment(sphere_color))))
        image = HdrImage(width=3, height=3)
        camera = OrthogonalCamera()
        tracer = ImageTracer(image=image, camera=camera)
        world = World()
        world.add_shape(sphere)
        renderer = FlatRenderer(world=world)
        tracer.fire_all_rays(renderer)

        assert image.get_pixel(0, 0).is_close(BLACK)
        assert image.get_pixel(1, 0).is_close(BLACK)
        assert image.get_pixel(2, 0).is_close(BLACK)

        assert image.get_pixel(0, 1).is_close(BLACK)
        assert image.get_pixel(1, 1).is_close(sphere_color)
        assert image.get_pixel(2, 1).is_close(BLACK)

        assert image.get_pixel(0, 2).is_close(BLACK)
        assert image.get_pixel(1, 2).is_close(BLACK)
        assert image.get_pixel(2, 2).is_close(BLACK)
Beispiel #3
0
    def testFurnace(self):
        pcg = PCG()

        # Run the furnace test several times using random values for the emitted radiance and reflectance
        for i in range(5):
            world = World()

            emitted_radiance = pcg.random_float()
            reflectance = pcg.random_float(
            ) * 0.9  # Be sure to pick a reflectance that's not too close to 1
            enclosure_material = Material(
                brdf=DiffuseBRDF(
                    pigment=UniformPigment(Color(1.0, 1.0, 1.0) *
                                           reflectance)),
                emitted_radiance=UniformPigment(
                    Color(1.0, 1.0, 1.0) * emitted_radiance),
            )

            world.add_shape(Sphere(material=enclosure_material))

            path_tracer = PathTracer(pcg=pcg,
                                     num_of_rays=1,
                                     world=world,
                                     max_depth=100,
                                     russian_roulette_limit=101)

            ray = Ray(origin=Point(0, 0, 0), dir=Vec(1, 0, 0))
            color = path_tracer(ray)

            expected = emitted_radiance / (1.0 - reflectance)
            assert pytest.approx(expected, 1e-3) == color.r
            assert pytest.approx(expected, 1e-3) == color.g
            assert pytest.approx(expected, 1e-3) == color.b
Beispiel #4
0
 def __init__(self, floor=None, fill=None):
     if floor == None:
         floor = Cell.floor
     elif not isinstance(floor, mat):
         if mat.has_material(floor):
             floor = mat.by_name(floor)
         else:
             raise ValueError("Expected a material, got", type(floor))
     if fill == None:
         fill = Cell.fill
     elif not isinstance(fill, mat):
         if mat.has_material(fill):
             fill = mat.by_name(fill)
         else:
             raise ValueError("Expected a material, got", type(fill))
     self.floor = floor
     self.fill = fill
     self.statics = None
    def __init__(self, mat=None):
        super(UiModel, self).__init__()

        if mat == None:
            mat = Material([1., 1., 1.])
            mat.alpha = 0.5

        self.meshes.append(
            Mesh(
                array([[.5, .5, 0.], [-.5, .5, 0.], [-.5, -.5, 0.],
                       [.5, -.5, 0.]],
                      dtype='float32').flatten(),
                array([[1., 1.], [0., 1.], [0., 0.], [1., 0.]],
                      dtype='float32').flatten(),
                array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
                      dtype='float32').flatten(),
                array([[0, 1, 2], [2, 3, 0], [0, 2, 1], [2, 0, 3]],
                      dtype='uint16').flatten(), mat))
Beispiel #6
0
    def createRepresentativeShape(self):
        drawer = LegacyDrawer()
        lightBox = Box()
        lightBox.setDrawer(drawer)
        lightBox.create()

        # material can be defined to match with light color
        lightBox.setMaterial(Material(**MaterialDefs.LIGHT_BOX))
        
        return lightBox
Beispiel #7
0
def parse_material(input_file: InputStream,
                   scene: Scene) -> Tuple[str, Material]:
    name = expect_identifier(input_file)

    expect_symbol(input_file, "(")
    brdf = parse_brdf(input_file, scene)
    expect_symbol(input_file, ",")
    emitted_radiance = parse_pigment(input_file, scene)
    expect_symbol(input_file, ")")

    return name, Material(brdf=brdf, emitted_radiance=emitted_radiance)
    def _setupSpace(self):
        self.space = pymunk.Space()
        self.space.gravity = 0, -1000

        metal = Material(5, "", 1)
        plastic = Material(1, "", 0.2)
        block1 = Block(self.screen, self.space, self.entities, (100, 50), 50,
                       10, metal)
        block2 = Block(self.screen, self.space, self.entities, (500, 50), 20,
                       30, plastic)
        self.entities.append(block1)
        self.entities.append(block2)

        self.floor = pymunk.Segment(self.space.static_body, (0, 5),
                                    (self.screenX, 5), 10)
        self.floor.body.position = 0, 5
        self.floor.elasticity = 0.2
        self.floor.friction = 0.2

        self.space.add(self.floor)
Beispiel #9
0
    def __init__(self, name, conf, props, globdat):
        self.name = name
        myConf = conf.makeProps(name)
        myProps = props.getProps(name)

        self.type = myProps.get("type", "Solid")
        self.group = myProps.get("elements", "All")

        myConf.set("type", self.type)
        myConf.set("elements", self.group)

        mesh = globdat.get("mesh")
        self.rank = mesh.rank

        if self.group != "All":
            key = int(re.search(r'\d+', self.group).group())
            group_name = mesh.groupNames[key]
            logging.debug("    Obtaining elements from {}".format(group_name))
            idx = mesh.groupNames.keys().index(key)
            self.ielements = mesh.groups[idx]
            logging.debug("    Elements in mesh.groups[{}]".format(idx))
        else:
            group_name = next(iter(mesh.groupNames.values()))
            self.ielements = mesh.groups[0]
            logging.debug("    Obtaining elements from {}".format(group_name))

    #-----------------------------------------------------------------------
    #   initialize
    #-----------------------------------------------------------------------

    # Add types
        types = ['u', 'v', 'w']
        self.types = [types[x] for x in range(self.rank)]
        mesh.addTypes(self.types)

        # Add dofs
        self.inodes = mesh.getNodeIndices(self.ielements)
        mesh.addDofs(self.inodes, self.types)

        # Add thickness (2D)
        if self.rank == 2:
            self.t = myProps.get("thickness", 1.0)
            myConf.set("thickness", self.t)

        # Create element
        self.shape = Shape.shapeFactory(myConf, myProps)
        localrank = self.shape.ndim
        if localrank != self.rank:
            msg = "Shape ndim = {}. Should be {}".format(localrank, self.rank)
            raise ValueError(msg)

        # Create material
        self.mat = Material.materialFactory(myConf, myProps)
Beispiel #10
0
	def __init__(self, font_file):
		self._glyphs = {}
		self._kern = {}
		self._page = {}

		if "." not in font_file:
			font_file = font_file+".zip"

		with zipfile.ZipFile(font_file,'r') as z:
			if font_file.lower().endswith(".zip"):
				font_file = os.path.basename(font_file)[:-4]

			xml = z.read(font_file+".fnt")
			xroot = ET.fromstring(xml)
			# misc info
			com = xroot.find('common')
			self._line_height = int(com.get("lineHeight"))
			self._base = int(com.get("base"))
			self._imgw = int(com.get("scaleW"))
			self._imgh = int(com.get("scaleH"))
		

			# load the textures
			for page in xroot.find('pages').findall("page"):
				id = int(page.get("id"))
				img_filename = page.get("file")
				img = z.read(img_filename)
				surf = pygame.image.load(StringIO.StringIO(img),img_filename)
				tex = Texture()
				tex.setFromSurface(surf)
				self._page[id] = tex

				assert(id == 0) # for now, we only support single-page fonts
			
			# load the glyph data
			for char in xroot.find("chars").findall("char"):
				d = {}
				for f in self.Glyph._fields:
					d[f] = int(char.get(f))

				g=self.Glyph(**d)
				self._glyphs[g.id] = g

			# load the kerning data
			for kern in xroot.find("kernings").findall("kerning"):
				t = (int(kern.get("first")), int(kern.get("second")))
				self._kern[t] = int(kern.get("amount"))


		self._material = Material()

		self._material.setTexture(0,self._page[0])
Beispiel #11
0
def get_materials():
    """
    Converts input parameters to a list of Material objects.

    :return: List of Material objects
    """
    material_list, metal_model = read_from_input()
    materials = []
    for line in material_list:
        l = line.split(',')
        if len(l) == 2:    # '[name],[thickness]'
            if l[0].capitalize() in INDICES.keys():    # hardcoded material
                materials.append(Material(l[0], thickness=float(l[1])))
            elif metal_model is not None:    # gold or silver
                materials.append(Material(l[0], model=metal_model, thickness=float(l[1])))
            else:
                raise ValueError('No metal model supplied.')
        elif len(l) == 3:    # '[name],[thickness],[index]'
            materials.append(Material(l[0], thickness=float(l[1]), index=complex(l[2])))
        else:
            raise ValueError('Malformed line in input file.')
    return materials
Beispiel #12
0
def view_spectrum():
    conn = sqlite3.connect(os.path.join(BASE_DIR, 'data.db'))
    c = conn.cursor()
    materials = c.execute(
        """SELECT DISTINCT material FROM main ORDER BY material;""")
    materials = dict(
        enumerate([material[0] for material in materials.fetchall()], start=1))
    print("Select a Material:")
    for number, material in materials.items():
        print('{} - {}'.format(number, material))
    spectrum = raw_input("Enter Selection: ")
    print('\n')
    if spectrum.isdigit() and int(spectrum) in materials.keys():
        rs.plot({'material': Material(materials[int(spectrum)])})
    def test_getitem(self):
        """Unit test for __getitem__"""
        # Setup
        yaml_dict = {
            'density': {
                'default_value': 1000.,
                'units': 'kg m^-3',
                'reference': 'mmpds'
            }
        }
        matl = Material('name', properties_dict=yaml_dict)

        # Action
        prop = matl['density']

        # Verification
        self.assertTrue(issubclass(type(prop), Property))
    def test_init(self):
        # Setup
        yaml_dict = {
            'density': {
                'default_value': 1000.,
                'units': 'kg m^-3',
                'reference': 'mmpds'
            }
        }

        # Action
        matl = Material('name', properties_dict=yaml_dict)

        # Verification
        self.assertTrue(hasattr(matl, 'properties'))
        self.assertTrue('density' in matl.properties)
        self.assertEqual(matl.name, 'name')
        self.assertTrue(matl.category is None)
Beispiel #15
0
    def __init__(self):
        self.__shapeName = ""
    
        # I am thinking to turn all of them protected
        self.__verticesList = []
        self.__faceList = []
        self.__size = 0

        # I will fix their logic later
        self.__matrix_stack = []
        self.__finalTransformMatrix = 0

        self.__drawer = 0

        self.__subdivider = None

        self.__color = None
        self.__wireColor = None
        self.__wireWidth = None

        self.__shapeMaterial = Material("default")
Beispiel #16
0
 def __init__(self,
              transformation=Transformation(),
              material: Material = Material()):
     """Create a unit sphere, potentially associating a transformation to it"""
     super().__init__(transformation, material)
Beispiel #17
0
    """The in-plane fourier transform of a circle"""
    def __init__(self, **kwargs):
        self.r = Float(1.0, help="The radius of the circle")
        Func.__init__(self, **kwargs)

    def function(self, **kwargs):
        q = kwargs['q']
        r = self.r(**kwargs)
        q_r = np.sqrt(q[0]**2 + q[1]**2)
        return 2 * np.pi * r**2 * grating.jinc(q_r * r)


if __name__ == '__main__':
    radius = Float(1.0)
    slope = Float(1)
    mat_Fe = Material('Fe', density=7.87)
    Fe = Layer(d=rep * 0.1 + 10.0,
               sld=mat_Fe.sld_x * FCircle(r=radius + z * slope))
    Fe.d = 20.0
    q = np.array([0, 0, 0])
    print Fe.sld(q=q)
    print Fe.d()
    ML = Stack(reps=10, layers=[
        Fe,
    ])

    s = Sample(stacks=[
        ML,
    ])
    print isinstance(s, HasParameters), s.__class__.__name__
    inst = Instrument()
Beispiel #18
0
    menu_count = 1
    for s in scenarii:
        print("{} - {}".format(menu_count, s.name))
        menu_count += 1
    print("{} - View Spectrum".format(menu_count))
    print("Q - quit")

    selection = raw_input("Enter a selection: ")
    print('\n')
    if selection.isdigit() and selection in valid_scenarios:
        scenario = scenarii[int(selection) - 1]
        print("Launching {}".format(scenario.name))
        scenario.execute()
    elif selection.isdigit() and selection == '5':
        conn = sqlite3.connect('data.db')
        c = conn.cursor()
        materials = c.execute(
            """SELECT DISTINCT material FROM main ORDER BY material;""")
        materials = dict(
            enumerate([material[0] for material in materials.fetchall()],
                      start=1))
        print("Select a Material:")
        for number, material in materials.items():
            print('{} - {}'.format(number, material))
        spectrum = raw_input("Enter Selection: ")
        print('\n')
        if spectrum.isdigit() and int(spectrum) in materials.keys():
            sensing.plot({'material': Material(materials[int(spectrum)])})

print("Done!\n")
Beispiel #19
0
 def __init__(self,
              transformation: Transformation = Transformation(),
              material: Material = Material()):
     """Create a shape, potentially associating a transformation to it"""
     self.transformation = transformation
     self.material = material