コード例 #1
0
ファイル: test_all.py プロジェクト: ziotom78/pytracer
    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)
コード例 #2
0
ファイル: test_all.py プロジェクト: ziotom78/pytracer
    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
コード例 #3
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
コード例 #4
0
ファイル: PointLight.py プロジェクト: feyil/CENG487
    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
コード例 #5
0
ファイル: scene_file.py プロジェクト: ziotom78/pytracer
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)
コード例 #6
0
    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)
コード例 #7
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
コード例 #8
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)])})
コード例 #9
0
    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))
コード例 #10
0
    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))
コード例 #11
0
    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)
コード例 #12
0
ファイル: Shape.py プロジェクト: feyil/CENG487
    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")
コード例 #13
0
ファイル: shapes.py プロジェクト: ziotom78/pytracer
 def __init__(self,
              transformation=Transformation(),
              material: Material = Material()):
     """Create a unit sphere, potentially associating a transformation to it"""
     super().__init__(transformation, material)
コード例 #14
0
ファイル: shapes.py プロジェクト: ziotom78/pytracer
 def __init__(self,
              transformation: Transformation = Transformation(),
              material: Material = Material()):
     """Create a shape, potentially associating a transformation to it"""
     self.transformation = transformation
     self.material = material
コード例 #15
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")
コード例 #16
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()