def test_extra(self):
        """test_extra: Test extra values to make sure the code should work with any material
        objects
        """
        known_correct_values = {
            "Ruby": 2,
            "Copper": 7,
            "Diamond": 1,
            "Plastic": 1,
            "Gold": 4
        }

        gold = Material('Gold', 4, 100)
        copper = Material('Copper', 7, 65)
        plastic = Material('Plastic', 15, 50)
        diamond = Material('Diamond', 1, 1000)
        ruby = Material('Ruby', 2, 500)

        materials = [gold, plastic, copper, diamond, ruby]

        lorry1 = Lorry(15)
        lorry1.pickup_delivery(materials)

        self.assertEqual(lorry1.cargo, known_correct_values)
        self.assertEqual(lorry1.load_composition, 2905)
Beispiel #2
0
def create_cube(objects):
    sx = 2
    sy = 2
    shader_type = shaders.TYPE_LIGHT_MAP
    positions = [
        np.array([-1, 1, 1]),
        np.array([1, 1, 1]),
        np.array([0, 1, 0]),
        np.array([0, 1, 2]),
        np.array([0, 0, 1]),
        np.array([0, 2, 1]),
    ]
    n0, n1, n2 = DEFAULT_N0, DEFAULT_N1, DEFAULT_N2
    ns = [n0, -n0, n2, -n2, n1, -n1]
    n0s = [n1, n1, n0, n0, n0, n0]
    colors = [
        material.COLOR_GREEN, material.COLOR_RED, material.COLOR_GRAY,
        material.COLOR_GRAY, material.COLOR_GRAY, material.COLOR_GRAY
    ]
    for i in range(6):
        mtl = Material(colors[i])
        illumination_map = IlluminationTexture()
        mtl.add_illumination_map(illumination_map)
        plane = Plane(positions[i], mtl, shader_type, ns[i], n0s[i], sx, sy)
        objects.append(plane)
Beispiel #3
0
def render():
    (w, h) = (640, 480)
    camera = Camera(w, h, fov=np.pi / 6)

    # Materials
    base_finish = SoftDull
    base_finish.reflection = 0.1
    mat_base = Material(colors.P_Chrome3, finish=base_finish)

    mat_s1 = Material(colors.P_Brass3)

    se_ls = LightSourcePoint([-1., 5., 35.],
                             intensity=200.,
                             emission_color=[2., 2., 2.])
    se_base = SceneElement(Plane([0.0, -4.0, 20.], [0., 1., 0.]), mat_base)

    se_s1 = SceneElement(Sphere([0., 0., 40.], 4.), mat_s1)

    scene = Scene([se_ls, se_base, se_s1])
    # scene = Scene([se_ls, se_base])

    # Render
    rt = RayTracer(camera, scene)
    traced = rt.render()
    plt.imshow(traced)
    plt.show()
Beispiel #4
0
def main():
    """ create window, add shaders & scene objects, then run rendering loop """
    width = 640
    height = 480

    camera = Camera(vec(0, 0, -5), 60, height / width, .3, 1000)
    scene = Scene(camera,
                  light=vec(-.57735026919, -.57735026919, .57735026919) * .5)

    pyramidMesh = Mesh(vertices=np.array(
        ((0, .5, 0), (.5, -.5, 0), (-.5, -.5, 0)), 'f'),
                       normals=np.array(
                           ((0, 0, -1), (0.70710678118, 0, -0.70710678118),
                            (-0.70710678118, 0, -0.70710678118)), 'f'),
                       perVertexColor=np.array(
                           ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
                           'f'),
                       indexes=np.array((0, 1, 2), 'u4'))

    suzanne = Mesh.LoadMeshes("models/suzanne.obj")[0]

    scene.Add3DObject(
        Object3D(0,
                 translate(-1.5, 0, 1) @ rotate(vec(0.0, 1.0, 0.0), -200),
                 suzanne, Material("shaders/rainbow_shaded.frag")))

    scene.Add3DObject(
        Object3D(1,
                 translate(1.5, 0, 1) @ rotate(vec(0.0, 1.0, 0.0), 200),
                 suzanne, Material("shaders/shaded.frag")))

    renderer = Renderer(scene)
    renderer.Run()
Beispiel #5
0
def registrarMaterial():
    material = Material(db)
    data = request.get_json(force=True)
    material.crear(data)
    respuesta = make_response("Hello World")
    respuesta.headers.add("Access-Control-Allow-Origin", "*")
    return respuesta
Beispiel #6
0
    def get_material(self, info):
        name = info["name"]
        if name in self._material_dict:
            print("factory get from gw: ", name)
            return self._material_dict[name]

        if "material" in info["type"]:
            m = Material(name)
            m.init(info)
            self._material_dict[name] = m
            return m
        elif "device" in info["type"]:
            if "furnace" in info["type"]:
                m = Furnace(name)
                m.init(info)
                self._material_dict[name] = m
                self._device_set.add(m)
                return m
            elif "manufactureStation" in info["type"]:
                m = ManufactureStation(name)
                m.init(info)
                self._material_dict[name] = m
                self._device_set.add(m)
                return m
            else:
                raise FactoryError("error device: " + name)
        else:
            raise FactoryError("Error Material: " + name)
Beispiel #7
0
def render():
    (w, h) = (640, 480)
    camera = Camera(w, h, fov=np.pi / 6)
    
    # Materials
    mat_base = Material([1., 1., 1.])

    # mat_s1 = Material(colors.Aquamarine, finish=Finish(diffuse=0.7, ambient=0.1, specular=0.8, roughness=1./120, transparent=True, ior=1.5))
    # mat_s1 = Material(colors.Glass_Winebottle, finish=Finish(diffuse=0.7, ambient=0.1, specular=0.8, roughness=1./120, transparent=True, ior=1.5))
    mat_s1 = Material(colors.P_Silver3, finish=Finish(diffuse=0.7, ambient=0.1, specular=0.8, roughness=1./120, transparent=True, ior=1.5))

    mat_s2 = Material(colors.P_Copper3, finish=Medium, metallic=True)
    mat_s3 = Material(colors.P_Chrome3, finish=Medium, metallic=True)
    mat_s4 = Material(colors.P_Brass3, finish=Medium, metallic=True)


    # Scene Elements + Scene
    se_ls = LightSourcePoint([-5., 15., 20.], intensity=1000., emission_color=[2., 2., 2.])

    se_base = SceneElement(Sphere([0.0, -10004., 20.], 10000.), mat_base)

    se_s1 = SceneElement(Sphere([0., 0., 20.], 4.), mat_s1)
    se_s2 = SceneElement(Sphere([5.0, -1., 15.], 2.), mat_s2)
    se_s3 = SceneElement(Sphere([3.0, 0, 22.], 2.), mat_s3)
    se_s4 = SceneElement(Sphere([-5.5, 0, 15.], 3.), mat_s4)

    scene = Scene([se_ls, se_base, se_s1, se_s2, se_s3, se_s4])

    # Render
    rt = RayTracer(camera, scene, num_bounces=5)
    traced = rt.render()
    plt.imshow(traced); plt.show()
Beispiel #8
0
def build_shielded_geometry():
    air = Material(0.1, color='white')
    u235_metal = Material(1.0, color='green')
    poly = Material(1.0, color='red')
    steel = Material(1.0, color='orange')

    box = create_hollow(create_rectangle(20., 10.), create_rectangle(18., 8.))

    hollow_circle = create_hollow(create_circle(3.9), create_circle(2.9))
    hollow_circle.translate([-9 + 3.9 + 0.1, 0.])

    small_box_1 = create_rectangle(2., 2.)
    small_box_1.translate([6., 2.])

    small_box_2 = create_rectangle(2., 2.)
    small_box_2.translate([6., -2.])

    #sim = Simulation(air, 50., 45., 'arc')
    sim = Simulation(air,
                     100,
                     diameter=50.,
                     detector='plane',
                     detector_width=30.)
    sim.detector.width = 30.
    sim.geometry.solids.append(Solid(box, steel, air))
    sim.geometry.solids.append(Solid(hollow_circle, steel, air))
    sim.geometry.solids.append(Solid(small_box_1, poly, air))
    sim.geometry.solids.append(Solid(small_box_2, steel, air))
    sim.geometry.flatten()

    return sim
Beispiel #9
0
def render():
    (w, h) = (640, 480)
    camera = Camera(w, h, fov=np.pi / 6)
    
    # Materials
    mat_base = Material([0.2, 0.2, 0.2])

    mat_s1 = Material(colors.P_Brass3, finish=Finish(transparent=True, ior=1.1))
    mat_s2 = Material(colors.CornflowerBlue, finish=Finish(reflection=0.1))
    mat_s3 = Material(colors.ForestGreen, finish=Finish(reflection=0.1))
    mat_s4 = Material(colors.GreenCopper, finish=Finish(reflection=0.1))

    # Scene Elements + Scene
    se_ls = LightSourcePoint([-5., 10., 20.], intensity=1000.)

    se_base = SceneElement(Sphere([0.0, -10004., 20.], 10000.), mat_base)

    se_s1 = SceneElement(Sphere([0., 0., 20.], 4.), mat_s1)
    se_s2 = SceneElement(Sphere([5.0, -1., 15.], 2.), mat_s2)
    se_s3 = SceneElement(Sphere([5.0, 0, 25.], 3.), mat_s3)
    se_s4 = SceneElement(Sphere([-5.5, 0, 15.], 3.), mat_s4)

    scene = Scene([se_ls, se_base, se_s1, se_s2, se_s3, se_s4])

    # Render
    rt = RayTracer(camera, scene)
    traced = rt.render()
    plt.imshow(traced); plt.show()
Beispiel #10
0
def upload_files():
    if request.method == 'POST':
        if 'file[]' not in request.files:
            flash('No file part')
            return redirect(request.url)
        files = request.files.getlist("file[]")
        # if user does not select file, browser also submit an empty part without filename
        import time
        for file in files:
            print(file.filename)
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                type, folder = get_type_folder(file.filename)
                # filename = secure_filename(file.filename)
                filename = str(time.time()).replace(
                    ".", "") + "." + file.filename.rsplit('.', 1)[1].lower()
                material = Material(file, filename,
                                    app.config['UPLOAD_FOLDER'] + "/" + folder)
                material.save()
                print("\n\n2" + str(file.filename) + "->" + filename + "\n\n")
        return redirect(url_for('upload_file', filename=filename))

    return {"error": "405"}
Beispiel #11
0
def materialExists():
    material = Material(db)
    data = request.get_json(force=True)
    numSerie = data['numSerie']
    if(material.exists(numSerie)):
        return jsonify(material.jsonExists(numSerie))
    else:
        return str(False)
Beispiel #12
0
	def setCnc(self):
		self.cnc = Shapeoko()

		self.loadTools()
		self.cnc.setTool(self.toolList[0])

		self.material = Material({})
		self.cnc.setMaterial(self.material)
Beispiel #13
0
def pml(size, delta, thickness=20.0, mode='TMz'):
    """creates a perfectly matched layer as surounding boundary conditions"""
    # get patameter
    sizeX, sizeY = size
    deltaX, deltaY = delta

    # crate material
    shapeX, shapeY = int(sizeX / deltaX), int(sizeY / deltaY)
    sigma = {
        'electricX': numpy.zeros((shapeX, shapeY)),
        'electricY': numpy.zeros((shapeX, shapeY)),
        'magneticX': numpy.zeros((shapeX, shapeY)),
        'magneticY': numpy.zeros((shapeX, shapeY))
    }
    mask = numpy.zeros((shapeX, shapeY))

    # set constant
    c = constants.mu_0 / constants.epsilon_0

    # init PML
    sigmaMax = -(3.0 + 1.0) * constants.epsilon_0 * constants.c \
            * math.log(1.0e-5) / (2.0 * deltaX * thickness)

    for n in range(0, int(thickness + 1.0), 1):
        for j in range(0, int(shapeY), 1):
            sigma['electricY'][n, j] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticY'][n, j] = sigmaMax \
                    * math.pow(float(thickness - n - 0.5) / thickness, 3.0) * c
            mask[n, j] = 1.0

            sigma['electricY'][shapeX - 1 - n, j] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticY'][shapeX - 1 - n, j] = sigmaMax \
                    * math.pow(float(thickness - n + 0.5) / thickness, 3.0) * c
            mask[shapeX - 1 - n, j] = 1.0

        for i in range(0, int(shapeX), 1):
            sigma['electricX'][i, n] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticX'][i, n] = sigmaMax \
                    * math.pow(float(thickness - n - 0.5) / thickness, 3.0) * c
            mask[i, n] = 1.0

            sigma['electricX'][i, shapeY - 1 - n] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticX'][i, shapeY - 1 - n] = sigmaMax \
                    * math.pow(float(thickness - n + 0.5) / thickness, 3.0) * c
            mask[i, shapeY - 1 - n] = 1.0

    # create layer
    electric = (Material.epsilon(1.0, sigma['electricX']),
                Material.epsilon(1.0, sigma['electricY']))
    magnetic = (Material.mu(1.0, sigma['magneticX']),
                Material.mu(1.0, sigma['magneticY']))

    return electric, magnetic, mask
 def test_shadow7(self):
     eyev = Vector(0, 0, -1)
     normalv = Vector(0, 0, -1)
     light = Light(Point(0, 0, -10), Color(1, 1, 1))
     in_shadow = True
     m = Material()
     result = m.lighting(Sphere(), light, Point(0, 0, 0), eyev, normalv,
                         in_shadow)
     self.assertTrue(result.equals(Color(0.1, 0.1, 0.1)))
Beispiel #15
0
    def __init__(self, name="graphite"):
        """Initalizes a material

        :param name: The name of the material (i.e., "fuel" or "cool")
        :type name: str.
        """
        Material.__init__(
            self, name=name, k=self.thermal_conductivity(), cp=self.specific_heat_capacity(), dm=self.density()
        )
Beispiel #16
0
def pml(size, delta, thickness=20.0, mode='TMz'):
    """creates a perfectly matched layer as surounding boundary conditions"""
    # get patameter
    sizeX, sizeY = size
    deltaX, deltaY = delta

    # crate material
    shapeX, shapeY = int(sizeX / deltaX), int(sizeY / deltaY)
    sigma = {
            'electricX': numpy.zeros((shapeX, shapeY)),
            'electricY': numpy.zeros((shapeX, shapeY)),
            'magneticX': numpy.zeros((shapeX, shapeY)),
            'magneticY': numpy.zeros((shapeX, shapeY))}
    mask = numpy.zeros((shapeX, shapeY))

    # set constant
    c = constants.mu_0 / constants.epsilon_0

    # init PML
    sigmaMax = -(3.0 + 1.0) * constants.epsilon_0 * constants.c \
            * math.log(1.0e-5) / (2.0 * deltaX * thickness)

    for n in range(0, int(thickness + 1.0), 1):
        for j in range(0, int(shapeY), 1):
            sigma['electricY'][n, j] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticY'][n, j] = sigmaMax \
                    * math.pow(float(thickness - n - 0.5) / thickness, 3.0) * c
            mask[n, j] = 1.0

            sigma['electricY'][shapeX - 1 - n, j] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticY'][shapeX - 1 - n, j] = sigmaMax \
                    * math.pow(float(thickness - n + 0.5) / thickness, 3.0) * c
            mask[shapeX - 1 - n, j] = 1.0

        for i in range(0, int(shapeX), 1):
            sigma['electricX'][i, n] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticX'][i, n] = sigmaMax \
                    * math.pow(float(thickness - n - 0.5) / thickness, 3.0) * c
            mask[i, n] = 1.0

            sigma['electricX'][i, shapeY - 1 - n] = sigmaMax \
                    * math.pow(float(thickness - n) / thickness, 3.0)
            sigma['magneticX'][i, shapeY - 1 - n] = sigmaMax \
                    * math.pow(float(thickness - n + 0.5) / thickness, 3.0) * c
            mask[i, shapeY - 1 - n] = 1.0

    # create layer
    electric = (Material.epsilon(1.0, sigma['electricX']),
            Material.epsilon(1.0, sigma['electricY']))
    magnetic = (Material.mu(1.0, sigma['magneticX']),
            Material.mu(1.0, sigma['magneticY']))

    return electric, magnetic, mask
    def setUp(self):
        mat10 = Material(E11=38000., E22=9000., G12=3600., nu12=0.32, t=1.)
        mat15 = Material(E11=38000., E22=9000., G12=3600., nu12=0.32, t=1.5)

        self.lam = clt.Laminate([(15, mat15), (-30, mat10), (-15, mat15),
                                 (30, mat10)])

        # mload = np.array([2000, 1000, 500, 0, 0, 0]) # used in text
        mload = np.array([1000, 500, 250, 0, 0, 0])  # used in calculations
        self.sol = self.lam.get_linear_response(mload)
Beispiel #18
0
def main():
    """main: Driver code to show working implimentation of labsheet question
    """
    gold = Material('Gold', 4, 100)
    copper = Material('Copper', 7, 65)
    plastic = Material('Plastic', 15, 50)

    materials = [gold, plastic, copper]
    lorry1 = Lorry(10)
    lorry1.pickup_delivery(materials)
    print(lorry1)
Beispiel #19
0
    def assign_defaultData(self):
        
        #assign default data 
        newMaterial = Material()
        newMaterial.assign_defaultData()
        newThickness = 0.2

        #create and append layer to member list
        newLayer = Layer( newMaterial, newThickness )
        self.__listOfLayers = []
        self.__listOfLayers.append( newLayer )
def main():
    print('Reading ...')
    start = datetime.datetime.now()

    # data source name
    data_source_name = 'better-ball.d'
    # shading type:
    #   0 - no shading (framework)
    #   1 - constant shading
    #   2 - Gouraud shading
    #   3 - Phong shading
    shading = 3

    world_space = Space()
    world_space.append_by_file(data_source_name + '.txt')  # geometry data

    camera = Camera()
    camera.set_by_file(data_source_name + '.camera.txt')  # camera profile

    light = Light()
    light.set_by_file(data_source_name + '.light.txt')  # light profile

    material = Material()
    material.set_by_file(data_source_name +
                         '.material.txt')  # material profile

    illumination = Illumination()
    illumination.set(camera, light, material, shading)

    display = Display()
    display.set(800)  # change window size

    cost = datetime.datetime.now() - start
    print('Finish. (cost = ' + str(cost) + ')\n')

    print('Calculating: transform ...')
    start = datetime.datetime.now()

    view_space = copy.deepcopy(world_space)
    view_space.transform(world_to_view, camera)

    screen_space = copy.deepcopy(view_space)
    screen_space.transform(view_to_screen, camera)

    device_space = copy.deepcopy(screen_space)
    device_space.transform(screen_to_device, display)

    cost = datetime.datetime.now() - start
    print('Finish. (cost = ' + str(cost) + ')\n')

    window = Window()
    window.set(world_space, device_space, illumination, display)

    window.show()
    def test_material6(self):
        position = Point(0, 0, 0)
        m = Material()

        eyev = Vector(0, 0, -1)
        normalv = Vector(0, 0, -1)
        light = Light(Point(0, 0, 10), Color(1, 1, 1))
        in_shadow = False
        result = m.lighting(Sphere(), light, position, eyev, normalv,
                            in_shadow)
        self.assertTrue(Color(0.1, 0.1, 0.1).equals(result))
Beispiel #22
0
    def assign_defaultData(self):
        
        #assign default data 
        newMaterial = Material()
        newMaterial.assign_defaultData()
        newThickness = 0.2

        #create and append layer to member list
        newLayer = Layer( newMaterial, newThickness )
        self.__listOfLayers = []
        self.__listOfLayers.append( newLayer )
Beispiel #23
0
    def __init__(self, name="graphite"):
        """Initalizes a material

        :param name: The name of the material (i.e., "fuel" or "cool")
        :type name: str.
        """
        Material.__init__(self,
                          name=name,
                          k=self.thermal_conductivity(),
                          cp=self.specific_heat_capacity(),
                          dm=self.density())
Beispiel #24
0
def create_material(files, directory):
    material = Material()
    valid_material = False
    for file_path in files:
        for regex_type, data in PARSER_DATA.items():
            file_name = get_file_name_from_path(file_path)
            if data.get_regex().match(file_name):
                valid_material = True
                material.set_material_path(regex_type, file_path)
                set_material_name(material, directory, file_name)
                break
    return material if valid_material else None
Beispiel #25
0
def deleteMaterial():
    material = Material(db)
    data = request.get_json(force=True)
    numSerie = data['numSerie']
    if(material.borrarMaterial(numSerie)):
        respuesta = make_response("Borrado exitoso")
        respuesta.headers.add("Access-Control-Allow-Origin", "*")
        return respuesta
    else:
        respuesta = make_response("Error")
        respuesta.headers.add("Access-Control-Allow-Origin", "*")
        return respuesta
Beispiel #26
0
    def load_materials(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.materials)

        for material_id in self.materials:
            material = self.materials[material_id]
            material = Material(material_id, **material)
            self.materials[material_id] = material

            material.color = yamlhelp.load_color(material.color)
Beispiel #27
0
def ray_trace_test_geometry():
    air = Material(0.0, color='white')
    steel = Material(1.0, color='red')

    box = create_hollow(create_rectangle(12., 12.), create_rectangle(10., 10.))
    ring = create_hollow(create_circle(12.), create_circle(10.))
    box.rotate(45.)

    sim = Simulation(air, diameter=50.)
    sim.detector.width = 30.
    sim.geometry.solids.append(Solid(ring, steel, air))
    sim.geometry.flatten()

    return sim
Beispiel #28
0
def set_scene():
    pos = np.array([0.0, 0.0, 0])
    mat = Material(material_type=TYPE_TEXTURED)
    texture = ImageTexture("../textures/checkers.png")
    mat.add_texture(texture)
    # Normal of the plane
    n = np.array([0.0, 1.0, 0.0])
    # n0 vector of the plane (vector lying in the plane)
    n0 = np.array([1.0, 0.0, 0.0])
    # Scale for the texture in x and y
    sx = 4
    sy = 4
    plane = Plane(pos, mat, shaders.TYPE_FLAT, n, n0, sx, sy)
    cameras = [set_camera()]
    return Scene(cameras, [], [plane])
Beispiel #29
0
    def test_labsheet(self):
        """test_labsheet: Test labsheet values
        """
        known_correct_values = {"Gold": 4, "Copper": 6}

        gold = Material('Gold', 4, 100)
        copper = Material('Copper', 7, 65)
        plastic = Material('Plastic', 15, 50)

        materials = [gold, plastic, copper]
        lorry1 = Lorry(10)
        lorry1.pickup_delivery(materials)

        self.assertEqual(lorry1.cargo, known_correct_values)
        self.assertEqual(lorry1.load_composition, 790)
Beispiel #30
0
def render():
    # with open('examples/cube.obj') as f:
    with open('examples/teapot.obj') as f:
        lines = f.readlines()

    # simple (read stupid) parser for obj files
    V = []
    F = []
    for line in lines:
        line = line.replace('  ', ' ')
        if line[0:2] == "v ":
            V.append(map(float, line.strip().split(' ')[1:]))
        elif line[0:2] == "f ":
            f = line.strip().split(' ')[1:]
            f = map(lambda x: int(x.split('/')[0])-1, f)
            F.extend(f)

    n_polys = len(F) / 3
    fi = [3 for _ in range(n_polys)]

    # n_polys, fi, V, F = down_sample(n_polys, fi, V, F)

    tm = TriangleMesh(n_polys, fi, F, np.array(V).T, clockwise=True)

    (w, h) = (640, 480)
    camera = Camera(w, h, fov=np.pi / 2)
    camera.translate([0, 0, -100])
    # camera = Camera(w, h, fov=np.pi / 3)
    
    # Materials
    mat_base = Material([0.2, 0.2, 0.2])

    # mat_s1 = Material(colors.NeonPink, diffuse=0.7, ambient=0.1, specular=0.8, roughness=1./120, reflection=0.)
    mat_s1 = Material(colors.NeonPink, finish=VerySoftDull)

    se_ls = LightSourceDirectional([1, -1, 0], intensity=2., emission_color=[1., 1., 1.])
    se_base = SceneElement(Sphere([0.0, -10004., 20.], 10000.), mat_base)

    se_tm = SceneElement(tm, mat_s1)

    scene = Scene([se_ls, se_tm])

    # Render
    rt = RayTracer(camera, scene, num_bounces=0, background_color=0.5*np.ones((3, 1)))
    traced = rt.render()
    plt.imshow(traced); plt.show()

    import ipdb; ipdb.set_trace()
Beispiel #31
0
    def __init__(self,
                 name,
                 height=DEFAULT_HEIGHT,
                 width=DEFAULT_WIDTH,
                 depth=DEFAULT_DEPTH,
                 start_pos=Vector3(0, 0, 0),
                 color=Color(0, 1, 0, 1)):

        self.height = height
        self.width = width
        self.depth = depth
        self.name = name
        self.position = start_pos
        self.rotation = Quaternion.identity()
        self.scale = Vector3(1, 1, 1)
        if (height == self.DEFAULT_HEIGHT) and (
                width == self.DEFAULT_WIDTH) and (depth == self.DEFAULT_DEPTH):
            self.mesh = self.BLOCK_MESH
        else:
            self.mesh = Mesh.create_cube((self.width, self.height, self.depth))

        self.material = Material(color, "Block Material")
        self.children = []
        self.my_collider = AABB_Collider(
            Vector3(self.width, self.height, self.depth))
Beispiel #32
0
def main():
    WIDTH = 800
    HEIGHT = 400
    camera = Vector(0, 0, -1)
    objects = [
        Sphere(Point(0, 0, 0), 0.5, Material(Color.fromHEX("#FF0000"))),
        Sphere(Point(1, 0, 0), 0.5, Material(Color(0, 1, 0))),
        Sphere(Point(-1, 0, 0), 0.5, Material(Color(0, 0, 1)))
    ]
    lights = [Light(Point(10, 5, -10.0), Color.fromHEX("#FFFFFF"))]
    scene = Scene(camera, objects, lights, WIDTH, HEIGHT)
    engine = RenderEngine()
    image = engine.render(scene)

    with open("test.ppm", "w") as img_file:
        image.writePPM(img_file)
Beispiel #33
0
    def __init__(self):
        if Missile.missile_mesh is None:
            Missile.missile_mesh = Missile.create_missile_mesh()
            Missile.missile_material = Material(Color(1, 0, 0, 1),
                                                "MissileMaterial")

        super().__init__("Missile")

        # Determine the spawn position. There's 33% chance it comes from the right, 33% that it
        # comes from behind the mountains, and 34% chance it comes from the left
        self.position = Vector3(0, random.uniform(0, 3), 12)
        r = random.uniform(0, 100)
        if r > 66:
            self.position.x = 7
            self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0),
                                                 math.radians(-90))
        elif r > 33:
            self.position.y = -2
            self.position.x = random.uniform(-4, 4)
            self.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                 math.radians(-90))
        else:
            self.position.x = -7
            self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0),
                                                 math.radians(90))

        # Set the mesh and material of the missile
        self.mesh = Missile.missile_mesh
        self.material = Missile.missile_material
        # Sets the missile linear speed
        self.missile_speed = 2
        # Sets the rotation speed (in radians per second)
        self.missile_rotation_speed = 0.75
 def test_material1(self):
     m = Material()
     self.assertTrue(Color(1, 1, 1).equals(m.color))
     self.assertEqual(0.1, m.ambient)
     self.assertEqual(0.9, m.diffuse)
     self.assertEqual(0.9, m.specular)
     self.assertEqual(200.0, m.shininess)
Beispiel #35
0
def readMaterial(fh):
    """
    Read in material data on fh starting from first line (usually Na23)
    of data and return it in a Material instance.
    """

    mat = Material()
    while True:
        words = fh.readline().split()
        if len(words) == 1: break
        name = words[1]
        if name == "Am242g":
            name = "Am242"
        original_mass = float(words[3])
        if name[0:3] == "sfp":
            mat.isotopes[name] = FissionProduct(name,original_mass)
        else:
            mat.isotopes[name] = Isotope(name, original_mass)
    return mat
Beispiel #36
0
    def __init__(self, name="kernel"):
        """Initalizes a material based on the fuel kernel in a TRISO particle.
        A material has intensive (as opposed to extensive) material properties.

        :param name: The name of the material (i.e., "fuel" or "cool")
        :type name: str.
        :param vol: The volume of the material
        :param T0: The initial temperature of the material
        :type T0: float.
        :param alpha_temp: temperature coefficient of reactivity
        :type alpha_temp: float
        :param timer: The timer instance for the sim
        :type timer: Timer object
        :param heatgen: is this material a heat generator (fuel)
        :type heatgen: bool
        """
        Material.__init__(self,
                          name=name,
                          k=self.thermal_conductivity(),
                          cp=self.specific_heat_capacity(),
                          dm=self.density())
Beispiel #37
0
    def __init__(self, name="ss316"):
        """Initalizes a material based on stainless steel 316, a common nuclear
        grade steel.

        :param name: The name of the material (i.e., "fuel" or "cool")
        :type name: str.
        :param vol: The volume of the material
        :param T0: The initial temperature of the material
        :type T0: float.
        :param alpha_temp: temperature coefficient of reactivity
        :type alpha_temp: float
        :param timer: The timer instance for the sim
        :type timer: Timer object
        :param heatgen: is this material a heat generator (fuel)
        :type heatgen: bool
        """
        Material.__init__(self,
                          name=name,
                          k=self.thermal_conductivity(),
                          cp=self.specific_heat_capacity(),
                          dm=self.density())
Beispiel #38
0
def getMaterialPropertys(element):
    """Gets the material propertys like
    Mirror, Transparency Depth
    Texture propertys...

    Arguments:
    - `element`:
    """
    materials = []
    for meshMaterial in element.data.materials:
        name = meshMaterial.name
        transparencyRT = False
        transparencyDepth = 0
        mirrorRT = False
        mirrorDepth = 0
        tmpMaterial = None

        if meshMaterial.transparency_method == 'RAYTRACE':
            transparencyRT = True
            transparencyDepth = meshMaterial.raytrace_transparency.depth
        if meshMaterial.raytrace_mirror.use == True:
            mirrorRT = True
            mirrorDepth = meshMaterial.raytrace_mirror.depth

        tmpMaterial = Material(name, transparencyRT, transparencyDepth,
                               mirrorRT, mirrorDepth)

        for materialTexture in meshMaterial.texture_slots:
            if materialTexture:
                if materialTexture.texture.type == 'IMAGE':
                    if materialTexture.texture.image:
                        tmpMaterial.setImageTextureData(materialTexture.texture.image.name,
                                                        materialTexture.texture.image.size[0],
                                                        materialTexture.texture.image.size[1])
        materials.append(tmpMaterial)

    return materials
Beispiel #39
0
    def __init__(self, field, mode='TMz'):
        # save arguments
        self.field = field
        self.mode = mode

        # create sources
        self.source = Material(field.size, field.delta)

        # create listeners
        self.listener = []

        # create materials
        self.material = {}
        self.material['electric'] = Material(field.size, field.delta)
        self.material['magnetic'] = Material(field.size, field.delta)

        # add free space layer
        self.material['electric'][:, :] = Material.epsilon()
        self.material['magnetic'][:, :] = Material.mu()

        # add pml layer
        electric, magnetic, mask = pml(field.size, field.delta, mode=mode)
        self.material['electric'][mask] = electric
        self.material['magnetic'][mask] = magnetic
Beispiel #40
0
class Solver:
    """Solves FDTD equations on given field, with given materials and ports"""
    def __init__(self, field, mode='TMz'):
        # save arguments
        self.field = field
        self.mode = mode

        # create sources
        self.source = Material(field.size, field.delta)

        # create listeners
        self.listener = []

        # create materials
        self.material = {}
        self.material['electric'] = Material(field.size, field.delta)
        self.material['magnetic'] = Material(field.size, field.delta)

        # add free space layer
        self.material['electric'][:, :] = Material.epsilon()
        self.material['magnetic'][:, :] = Material.mu()

        # add pml layer
        electric, magnetic, mask = pml(field.size, field.delta, mode=mode)
        self.material['electric'][mask] = electric
        self.material['magnetic'][mask] = magnetic

    def solve(self, duration, starttime=0.0, deltaT=0.0,
            progressfunction=None, finishfunction=None):
        """Iterates the FDTD algorithm in respect of the pre-defined ports"""
        # get parameter
        deltaX, deltaY = self.field.delta

        # calc deltaT
        if deltaT == 0.0:
            deltaT = 1.0 / (constants.c * math.sqrt(1.0 / \
                    deltaX ** 2 + 1.0 / deltaY ** 2))

        # create constants
        kx = deltaT / deltaX
        ky = deltaT / deltaY

        # material aliases
        material1 = 'electric'
        material2 = 'magnetic'

        # apply mode
        if self.mode == 'TEz':
            kx, ky = -ky, -ky
            material1, material2 = material2, material1

        # iterate
        for t in numpy.arange(starttime, starttime + duration, deltaT):
            # do step
            self._step(deltaT, t, kx, ky, material1, material2)

            # call all listeners
            for listener in self.listener:
                listener.update(self.field)

            # call progress function
            if progressfunction:
                progressfunction(t, deltaT, self.field)

        # call finish function
        if finishfunction:
            finishfunction()

    def _step(self, deltaT, t, kx, ky, material1, material2):
        # calc oddField
        self.field.oddFieldY['flux'][:-1, :-1] += kx * \
                (self.field.evenFieldY['field'][1:, :-1] - \
                self.field.evenFieldY['field'][:-1, :-1])
        self.field.oddFieldX['flux'][:-1, :-1] -= ky * \
                (self.field.evenFieldX['field'][:-1, 1:] - \
                self.field.evenFieldX['field'][:-1, :-1])

        # apply sources
        sourceX, sourceY = self.source.apply((self.field.oddFieldX['flux'],
            self.field.oddFieldY['flux']), deltaT, t)
        self.field.oddFieldX['flux'] += sourceX
        self.field.oddFieldY['flux'] += sourceY

        # apply material
        self.field.oddFieldX['field'], self.field.oddFieldY['field'] = \
                self.material[material1].apply(
                        (self.field.oddFieldX['flux'],
                            self.field.oddFieldY['flux']), deltaT, t)

        # calc evenField
        self.field.evenFieldX['flux'][:-1, 1:-1] -= ky * \
                (self.field.oddFieldX['field'][:-1, 1:-1] + \
                self.field.oddFieldY['field'][:-1, 1:-1] - \
                self.field.oddFieldX['field'][:-1, :-2] - \
                self.field.oddFieldY['field'][:-1, :-2])
        self.field.evenFieldY['flux'][1:-1, :-1] += kx * \
                (self.field.oddFieldX['field'][1:-1, :-1] + \
                self.field.oddFieldY['field'][1:-1, :-1] - \
                self.field.oddFieldX['field'][:-2, :-1] - \
                self.field.oddFieldY['field'][:-2, :-1])

        # apply material
        self.field.evenFieldX['field'], self.field.evenFieldY['field'] = \
                self.material[material2].apply(
                        (self.field.evenFieldX['flux'],
                            self.field.evenFieldY['flux']), deltaT, t)
Beispiel #41
0
U235 = Isotope(ace_path + 'U_235_293.6K.ace')
H1 = Isotope(ace_path + 'H_001_293.6K.ace')

# -------------------------------
# parameters  
# -------------------------------
tau = 1.0e-3  
T = 293.5  
N = 2000 # # of neutrons want to sample  

E = pre_computing(tau)

#--------------------------------------------------------
# case 1,  1000 / 1
#--------------------------------------------------------
mat = Material(E) 
mat.addIsotope(U235, 1.0)
mat.addIsotope(H1, 1000.0)
mat.normalize_numdensity()  

mc = mc_sampling(E, mat, T, N)
E_for_flux, flux, deviation = mc.solver()
np.savetxt('../results/E_flux.txt', E_for_flux)
np.savetxt('../results/flux1000to1.txt', flux)
np.savetxt('../results/deviation1000to1.txt', deviation)

#--------------------------------------------------------
# case 2, 100 / 1
#--------------------------------------------------------

mat = Material(E)  
Beispiel #42
0

objects = json.loads(itemcontents)
for mat in matstatics:
    if matstatics[mat]["textures"]:
        for texname in matstatics[mat]["textures"]:
            matpath = "./blocks/" + texname + ".png"
            if os.path.exists(matpath) and texname not in textures:
                with open(matpath, "rb") as image_file:
                    textures[texname] = base64.b64encode(image_file.read())


for aobject in objects:
    tofind = (aobject['type'],aobject['meta'])
    if tofind in avgcolors:
        material = Material(color=avgcolors[tofind][0:3],alpha=avgcolors[tofind][3],blockid=(aobject['type'], aobject['meta']),name=aobject['name'].encode('ascii','ignore'), blandname=aobject['name'].encode('ascii','ignore'))
    else:
        print str(tofind) + ' not in there !'
        material = Material(blockid=(aobject['type'], aobject['meta']),name=aobject['name'].encode('ascii','ignore'), blandname=aobject['name'].encode('ascii','ignore'))

    materials.update({tofind:material.getDict()})

materials.update( material.addRest(materials) )

print "length of materials found on site: " + str(len(materials))

matsandtex = {"materials":materials,"textures":textures}

toformat = repr(matsandtex).replace("}", "}\n")

Beispiel #43
0
 def __init__(self, filePath):
     self.width = 0
     self.height = 0
     self.materials = []
     self.lights = []
     self.spheres = []
     f = open(filePath)
     section = ''
     for line in f:
         l = line.strip()
         if section == '':
             if len(l) != 0:
                 if l[:2] != '//':
                     section = l
         else:
             if section.find('Scene') != -1:
                 if l == '{':
                     pass
                 elif l == '}':
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Width':
                         self.width = convertStr(words[1])
                     elif words[0] == 'Height':
                         self.height = convertStr(words[1])
             elif section.find('Material') != -1:
                 if l == '{':
                     tempMat = Material()
                 elif l == '}':
                     self.materials.append(tempMat)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Diffuse':
                         params = words[1].split()
                         tempMat.setDiffuse(Color(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Reflection':
                         tempMat.setReflection(convertStr(words[1]))
                     elif words[0] == 'Id':
                         tempMat.setId(convertStr(words[1]))
             elif section.find('Sphere') != -1:
                 if l == '{':
                     tempSphere = Sphere()
                 elif l == '}':
                     self.spheres.append(tempSphere)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Center':
                         params = words[1].split()
                         tempSphere.setPosition(Point(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Size':
                         tempSphere.setSize(convertStr(words[1]))
                     elif words[0] == 'Material':
                         tempSphere.setMaterial(convertStr(words[1]))
             elif section.find('Light') != -1:
                 if l == '{':
                     tempLight = Light()
                 elif l == '}':
                     self.lights.append(tempLight)
                     section = ''
                 else:
                     words = l.split('=')
                     if words[0] == 'Position':
                         params = words[1].split()
                         tempLight.setPosition(Point(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
                     elif words[0] == 'Intensity':
                         params = words[1].split()
                         tempLight.setIntensity(Color(convertStr(params[0]),convertStr(params[1]),convertStr(params[2])))
Beispiel #44
0
    def return_modifiedZoneObject(self, currentZoneObject, key ):

        #check initialization
        if (self.__xmlFileInitialized == False):
            print("SimulationMatrix:ReturnModifiedZoneObject: simulation matrix xml file must be initialized correctly before calling this function.")
        
        #copy submitted zone object
        newZoneObject = currentZoneObject

        #get list of variable reference ids
        varRefList = []
        for entry in self.__combObjectList:
            if(key == entry.return_ID()):
                varRefList = list( entry.return_VariableAssignmentDict().keys() )

        #check database directories and get name list of available entries
        
        
        #loop over variable id list and go through xml structure to find the referenced element
        for varRef in varRefList:

            #go through xml structure to find referenced id in different types of variable variants
            
            #check if this is a construction modification reference
            for conTypeNode in self.__file_xml_tree.getElementsByTagName("ConstructionType"):
                
                #get only last part of source identification
                conSource = ""
                conSource_long = conTypeNode.getAttribute("source")
                if(os.sep in conSource_long): conSource = conSource_long.split(os.sep)[-1]
                elif("/" in conSource_long): conSource = conSource_long.split("/")[-1]
                elif("\\" in conSource_long): conSource = conSource_long.split("\\")[-1]
                else: conSource = conSource_long
                
                #go through const variants to compare reference id with defined ids
                for conTypeVarNode in conTypeNode.getElementsByTagName("ConstructionTypeVariant"):
                    conTypeVarId = conTypeVarNode.getAttribute("id")
                    if( varRef == conTypeVarId ):
                        
                        #go through all constructions of this file to get the matching source attribute(s)
                        for conObject in newZoneObject.return_ConsList():
                            conSourceRef = ""
                            conSourceRef_long = conObject.return_source()
                            if(os.sep in conSourceRef_long): conSourceRef = conSourceRef_long.split(os.sep)[-1]
                            elif("/" in conSourceRef_long): conSourceRef = conSourceRef_long.split("/")[-1]
                            elif("\\" in conSourceRef_long): conSourceRef = conSourceRef_long.split("\\")[-1]
                            else: conSourceRef = conSourceRef_long

                            #check if both ids are equal and modify constructions due to xml specifications
                            if ( conSourceRef == conSource ):

                                #list which keeps all new layers
                                newLayers_List = []

                                #create new layer structure for this construction
                                for layNode in conTypeVarNode.getElementsByTagName("Layer"):

                                    #get layer thickness
                                    d = float( layNode.getAttribute("thickness"))

                                    #get material path and extract file name 
                                    matFilePath = layNode.firstChild.nodeValue
                                    matFileName = ""
                                    if(os.sep in matFilePath): matFileName = matFilePath.split(os.sep)[-1]
                                    elif("/" in matFilePath): matFileName = matFilePath.split("/")[-1]
                                    elif("\\" in matFilePath): matFileName = matFilePath.split("\\")[-1]
                                    else: matFileName = matFilePath
                                    
                                    #check if this material is included in target directory (Materials)
                                    if( matFileName not in os.listdir(self.__matDir_T)):
                                        print("SimulationMatrix: ReturnModifiedZoneObject: Material %s (defined in SimMa) is not included in target directory." % matFileName)
                                        #call ResCon here
    
                                    #parse material properties if material is available
                                    matFilePath = self.__matDir_T + os.sep + matFileName
                                    matObject = Material()
                                    if( matObject.read_DelphinDataSet(matFilePath) == False):
                                        matObject.assign_defaultData()
                                        print("SimulationMatrix: ReturnModifiedZoneObject: Material %s can't be parsed. Default data is assumed." % matFileName)

                                    #create new layer from this and keep it
                                    newLayer = Layer( matObject, d)
                                    newLayers_List.append(newLayer)

                                #remove all layers from current construction and submit new layer structure
                                conObject.remove_allLayers()
                                for layerObject in newLayers_List:
                                    conObject.add_layer( layerObject.mat , layerObject.d, 0 )


            #check if this is a construction modification reference
            for winTypeNode in self.__file_xml_tree.getElementsByTagName("WindowType"):
                
                #get only last part of source identification
                winSource = ""
                winSource_long = winTypeNode.getAttribute("source")
                if(os.sep in winSource_long): winSource = winSource_long.split(os.sep)[-1]
                elif("/" in winSource_long): winSource = winSource_long.split("/")[-1]
                elif("\\" in winSource_long): winSource = winSource_long.split("\\")[-1]
                else: winSource = winSource_long
                
                #go through const variants to compare reference id with defined ids
                for winTypeVarNode in winTypeNode.getElementsByTagName("WindowTypeVariant"):
                    winTypeVarId = winTypeVarNode.getAttribute("id")
                    if( varRef == winTypeVarId ):
                        #go through all windows of this file to get the matching source attribute(s)
                        for conObject in newZoneObject.return_ConsList():
                            winSourceRef = ""
                            if (conObject.return_numberOfEmbObjects() > 0):
                                #get id 
                                winSourceRef_long = conObject.return_embObject(0).source
                                #get only file name from id if possible
                                if(os.sep in winSourceRef_long): winSourceRef = winSourceRef_long.split(os.sep)[-1]
                                elif("/" in winSourceRef_long): winSourceRef = winSourceRef_long.split("/")[-1]
                                elif("\\" in winSourceRef_long): winSourceRef = winSourceRef_long.split("\\")[-1]
                                else: winSourceRef = winSourceRef_long

                                #check if both ids are equal and modify window due to xml specifications
                                if ( winSourceRef == winSource ):
                                    
                                    #get copy of existing embedded object and modify all specified values
                                    newEmbeddedObject = conObject.return_embObject(0)
                                    
                                    if( len(winTypeVarNode.getElementsByTagName("GlassFraction")) > 0):
                                        #get Value and submit it to construction - embedded object properties
                                        newEmbeddedObject.fGlass = (1.0, float(winTypeVarNode.getElementsByTagName("GlassFraction")[0].firstChild.nodeValue))
                                    if( len(winTypeVarNode.getElementsByTagName("FrameFraction")) > 0):
                                        #get Value and submit it to construction - embedded object properties
                                        newEmbeddedObject.fGlass = (1.0 - float(winTypeVarNode.getElementsByTagName("FrameFraction")[0].firstChild.nodeValue))
                                    if( len(winTypeVarNode.getElementsByTagName("ThermalTransmittance")) > 0):
                                        #get Value and submit it to construction - embedded object properties
                                        newEmbeddedObject.uValue = float(winTypeVarNode.getElementsByTagName("ThermalTransmittance")[0].firstChild.nodeValue)
                                    if( len(winTypeVarNode.getElementsByTagName("SolarHeatGainCoefficient")) > 0):
                                        #get Value and submit it to construction - embedded object properties
                                        newEmbeddedObject.shgc = float(winTypeVarNode.getElementsByTagName("SolarHeatGainCoefficient")[0].firstChild.nodeValue)

                                    #submit embedded object to current construction
                                    conObject.replace_embObject(newEmbeddedObject)
                            #else:
                                #print("SimulationMatrix: ReturnModifiedZoneObject: Requested construction object does not include a window object which can be modified.")


        return newZoneObject
Beispiel #45
0
    def __init__(self,
                 name="Material3DS",
                 ambient = (0,0,0,0),
                 diffuse = (1.0, 1.0, 1.0, 1.0),
                 specular = (1.0, 1.0, 1.0, 1.0),
                 shininess = 1,
                 shin_strength = 0,
                 use_blur = 0,
                 transparency = 0.0,
                 falloff = 0,
                 additive = 0,
                 use_falloff = 0,
                 self_illum = False,
                 self_ilpct = 0.0,
                 shading = 0,
                 soften = 0,
                 face_map = 0,
                 two_sided = 0,
                 map_decal = 0,
                 use_wire = 0,
                 use_wire_abs = 0,
                 wire_size = 0,
                 density = 1.0,
                 texture1_map = None,
                 texture1_mask = None,
                 texture2_map = None,
                 texture2_mask = None,
                 opacity_map = None,
                 opacity_mask = None,
                 bump_map = None,
                 bump_mask = None,
                 specular_map = None,
                 specular_mask = None,
                 shininess_map = None,
                 shininess_mask = None,
                 self_illum_map = None,
                 self_illum_mask = None,
                 reflection_map = None,
                 reflection_mask = None,

                 bump_size = 1.0   # Extra parameter to control the bump map
                 ):

        Material.__init__(self, name=name, density=density)

        self.ambient = ambient
        self.diffuse = diffuse
        self.specular = specular
        self.shininess = shininess
        self.shin_strength = shin_strength
        self.transparency = transparency
        self.self_illum = self_illum
        self.self_ilpct = self_ilpct
        self.texture1_map = texture1_map
        self.texture1_mask = texture1_mask
        self.texture2_map = texture2_map
        self.texture2_mask = texture2_mask
        self.opacity_map = opacity_map
        self.opacity_mask = opacity_mask
        self.bump_map = bump_map
        self.bump_mask = bump_mask
        self.specular_map = specular_map
        self.specular_mask = specular_mask
        self.shininess_map = shininess_map
        self.shininess_mask = shininess_mask
        self.self_illum_map = self_illum_map
        self.self_illum_mask = self_illum_mask
        self.reflection_map = reflection_map
        self.reflection_mask = reflection_mask
        self.bump_size = bump_size

        if texture1_map==None:
            self._gltexture = None
            glambient = ambient
            gldiffuse = diffuse
        else:
            map = texture1_map
            T = mat4(1,0,0,-map.offset[0]-0.5, 0,-1,0,0.5-map.offset[1], 0,0,1,0, 0,0,0,1)
            a = sl.radians(map.rotation)
            ca = math.cos(a)
            sa = math.sin(a)
            R = mat4(ca,-sa,0,0, sa,ca,0,0, 0,0,1,0, 0,0,0,1)
            S = mat4(map.scale[0],0,0,0.5, 0,map.scale[1],0,0.5, 0,0,1,0, 0,0,0,1)
            self._gltexture = GLTexture(imagename = map.name,
                                        mode = GL_MODULATE,
#                                        transform = mat4().scaling(vec3(1,-1,1))
                                        transform = S*R*T
                                        )
            glambient = map.percent*vec4(1,1,1,1) + (1-map.percent)*vec4(ambient)
            gldiffuse = map.percent*vec4(1,1,1,1) + (1-map.percent)*vec4(diffuse)

        self._glmaterial = GLMaterial(ambient = glambient,
                                      diffuse = gldiffuse,
                                      specular = shin_strength*specular,
                                      shininess = 25*shininess,
                                      texture = self._gltexture
                                      )
Beispiel #46
0
    def read_DelphinDataSet(self, stringFilePathName_d6p, stringFilePath_m6 ):
        
        #try to read file and replace invalid prefix in delphin project file
        print("Reading of Delphin construction file.")
        try:
            fileString = open(stringFilePathName_d6p, "r").read()
        except Exception:
            print("Invalid file or file access not possible: %s" % stringFilePathName_d6p)
        else:
            buggyString = "xsi:schemaLocation" #undefined prefix causes error in xml parsing function
            newString = "schemaLocation"
            #find false string
            if (buggyString in fileString):
                newFileString = fileString.replace( buggyString, newString )
                newFile = open(stringFilePathName_d6p, "w")
                newFile.write(newFileString)
                newFile.close()

        #read xml project file
        try:
            xml_fileTreeObject = DOM.parse( stringFilePathName_d6p )
        except Exception:
            print("XML file reading of file %s failed. Invalid xml file structure." % stringFilePathName_d6p)
            return False
        else:
            #init properties temporary property/ element lists
            materialList = []           #container for material objects specified in this file
            layerThickList = []         #contains string values with layer thicknesses in m

            #construction file reading successful, now try to parse included material files
            for matTag in xml_fileTreeObject.getElementsByTagName("MaterialReference"):
                print("Getting of material references and parameters:")
                #get tag properties
                matName = matTag.getAttribute("displayName")
                print("display name: "+matName)
                matFileString = matTag.firstChild.nodeValue
                print("material file String: "+matFileString)
                #get file location for material file
                placeHolder = "${Material Database}/"
                folder = stringFilePath_m6 + os.sep
                
                matFileLocation = matFileString.replace( placeHolder , folder )
                print("Material file location: "+matFileLocation)
                #print("Identified and submitted file string is %s." % matFileLocation )
                
                #read data set and create material object with specific name
                newMaterial = Material()
                
                if (newMaterial.read_DelphinDataSet(matFileLocation) == True):
                    
                    print("Material %s identified." % matName)
                    newMaterial.set_matName(matName)
                    materialList.append(newMaterial)
                else:
                    
                    print("One or several materials in delivered construction file %s are invalid." % stringFilePathName_d6p)
                    return False
                
            #now get layer thicknesses
            allSteps = xml_fileTreeObject.getElementsByTagName("XSteps")[0].firstChild.nodeValue
            
            for step in allSteps.split():
                layerThickList.append(step)
                #print("Layer thickness %s identified." % step)

            #read layer order and create layers for this construction
            layerCounter = 0
            
            for assTag in xml_fileTreeObject.getElementsByTagName("Assignment"):
                
                if ( assTag.getAttribute("type") == "Material" ):
                    
                    tempMatName = assTag.getElementsByTagName("Reference")[0].getAttribute("displayName")
                    print("Referenced material name %s identified." % tempMatName)
                    
                    for matObject in materialList:
                        
                        print("checked name for material: %s" % matObject.return_name() )
                        
                        if (matObject.return_name() == tempMatName):
                            #matching material, create layer
                            self.add_layer( matObject, layerThickList[ layerCounter ], layerCounter )
                            #print("Matching material %s identified. Layer created." % matObject.return_name() )
                            layerCounter = layerCounter + 1
                            print layerCounter
                            
                        else:
                            
                            print("Material layer was not added: ")
                else:
                    
                    print("Delphin project file parsing of file %s failed. Invalid layer definiton." % stringFilePathName_d6p)
                    return False
            
            return True
Beispiel #47
0
def loadData(filename, parent=None, gui=True):
    """
    Loads material data from an ERANOS output file.

    Returns a list 'cycles' with all the Cycle instances.
    """

    # Open file
    eranosFile = open(filename, "r")
    cycles = []

    # Find the names of all the fuel regions
    fuelNames = []
    m = fileReSeek(eranosFile, "^->LISTE_MILIEUX.*")
    fuelNames += re.findall("'(FUEL\d+)'", m.group())
    while True:
        line = eranosFile.readline().strip()
        fuelNames += re.findall("'(FUEL\d+)'", line)
        if line[-1] == ";": break

    # Determine if there is a blanket material
    m = fileReSeek(eranosFile, "^->BLANKET.*")
    if m:
        fuelNames += ["BLANK"]
    else:
        eranosFile.seek(0)
    
    # Determine default cooling period
    position = eranosFile.tell()
    m = fileReSeek(eranosFile, "^->COOLINGTIME\s+(\S+).*")
    if m:
        try:
            if m.groups()[0][:6] == "(PASSE":
                auto_cooling = True
            else:
                auto_cooling = False
                cooling_time = float(m.groups()[0])
        except:
            cooling_time = 30
    else:
        cooling_time = None
        eranosFile.seek(position)

    # Determine cycle information
    while True:
        m = fileReSeek(eranosFile, ".*->CYCLE\s+(\d+).*")
        if not m: break
        n = int(m.groups()[0])
        m = fileReSeek(eranosFile, "^->PASSE\s\((\d+)\).*")
        if not m: break
        timestep = int(m.groups()[0])
        m = fileReSeek(eranosFile, "^->ITER\s(\d+).*")
        iterations = int(m.groups()[0])
        # Determine cooling period
        if auto_cooling:
            cooling_time = timestep*iterations*0.15/0.85
        cycles.append(Cycle(n, timestep, iterations, cooling_time))
    eranosFile.seek(0)

    # Determine how many materials to read total
    n_materials = 0
    for cycle in cycles:
        n_materials += len(cycle.times())*len(fuelNames)
    
    # Create progress bar
    if gui:
        progress = QProgressDialog("Loading ERANOS Data...",
                                   "Cancel", 0, n_materials, parent)
        progress.setWindowModality(Qt.WindowModal)
        progress.setWindowTitle("Loading...")
        progress.setMinimumDuration(0)
        progress.setValue(0)
        
    pValue = 0
    for cycle in cycles:
        print("Loading Cycle {0}...".format(cycle.n))

        # Determine critical mass
        fileReSeek(eranosFile, " ECCO6.*")
        xsDict = {}
        for i in fuelNames:
            m = fileReSeek(eranosFile, "\sREGION :(FUEL\d+|BLANK)\s*")
            name = m.groups()[0]
            m = fileReSeek(eranosFile,
                           "\s*TOTAL\s+(\S+)\s+(\S+)\s+\S+\s+(\S+).*")
            nuSigmaF = float(m.groups()[0])
            SigmaA = float(m.groups()[1])
            Diff = float(m.groups()[2])
            xsDict[name] = (nuSigmaF, SigmaA, Diff)

        # Find beginning of cycle
        m = fileReSeek(eranosFile, ".*M A T E R I A L   B A L A N C E.*")

        # Find TIME block and set time
        for node, time in enumerate(cycle.times()):
            # Progress bar
            if gui:
                QCoreApplication.processEvents()
                if (progress.wasCanceled()):
                    return None

            # Loop over fuel names
            for i in fuelNames:
                m = fileReSeek(eranosFile,"\s+MATERIAL\s(FUEL\d+|BLANK)\s+")
                name = m.groups()[0]
                volume = float(eranosFile.readline().split()[-1])
                for n in range(5): eranosFile.readline()
                # Read in material data
                material = readMaterial(eranosFile)
                material.volume = volume
                if time == 0:
                    material.nuFissionRate = xsDict[name][0]
                    material.absorptionRate = xsDict[name][1]
                    material.diffRate = xsDict[name][2]
                cycle.materials[(node,name)] = material
                #print (node,name)
                # Set progress bar value
                pValue += 1
                if gui:
                    progress.setValue(pValue)
                #print((cycle.n, time, name)) # Only for debugging

        # Read uranium added/required feed
        for i in range(3):
            # Determine if there is additional mass or not enough
            regexList = [" 'REQUIRED FEED FOR FUEL (\d).*",
                         " 'ADDITIONAL FEED FOR FUEL (\d).*"]

            m, index = fileReSeekList(eranosFile,regexList)

            if index == 0:
                # We don't have enough fissile material
                cycle.extraMass = False
                mat = "FUEL{0}".format(m.groups()[0])
                m = fileReSeek(eranosFile," ->REPLMASS2\s+(\S+).*")
                cycle.requiredFeed += float(m.groups()[0])
                m = fileReSeek(eranosFile," ->REPLMASS1\s+(\S+).*")
                cycle.uraniumAdded[mat] = float(m.groups()[0])
                m = fileReSeek(eranosFile," ->POWER\d\s+(\S+).*")
                cycle.materials[(5,mat)].power = float(m.groups()[0])
            else:
                # Additional mass was produced
                cycle.extraMass = True
                mat = "FUEL{0}".format(m.groups()[0])
                m = fileReSeek(eranosFile," ->EXTRA\s+(\S+).*")
                cycle.additionalFeed[mat] = float(m.groups()[0])
                m = fileReSeek(eranosFile," ->REPLMASS\s+(\S+).*")
                cycle.uraniumAdded[mat] = float(m.groups()[0])
                m = fileReSeek(eranosFile," ->POWER\d\s+(\S+).*")
                cycle.materials[(5,mat)].power = float(m.groups()[0])
        
        posb = eranosFile.tell()
        for i in range(4):
            # Get DPA information
            regexList = [" 'DPA of FUEL (\d).*",
                         " 'DPA of BLANKET'.*"]

            m, index = fileReSeekList(eranosFile,regexList)

            if index == 0:
                # We don't have enough fissile material
                mat = "FUEL{0}".format(m.groups()[0])
                m = fileReSeek(eranosFile," ->DPA\dC\s+(\S+).*")
                #print (m.group(), m.groups())
                #print (mat)
                cycle.materials[(5,mat)].dpa = float(m.groups()[0])
            else:
                # Additional mass was produced
                mat = "BLANK"
                m = fileReSeek(eranosFile," ->DPABC\s+(\S+).*")
                #print (m.group(), m.groups())
                cycle.materials[(5,mat)].dpa = float(m.groups()[0])
                #cycle.materials[(0,mat)].dpa = float(m.groups()[0])


    eranosFile.seek(posb)
    # Read charge and discharge vectors at end of ERANOS output file
    charge = Material()
    discharge = Material()
    onestreamch = Material()
    onestreamdis = Material()

    listeiso = ['Th232','Pa231','Pa233','U232','U233','U234','U235','U236','U238','Np237',
                'Np239','Np238','Pu238','Pu239','Pu240','Pu241','Pu242','Am241','Am242g',
                'Am242m','Am243','Cm242','Cm243','Cm244','Cm245','Cm246','Cm247','Cm248',
                'Bk249','Cf249','Cf250','Cf251','Cf252','sfpU234','sfpU235','sfpU236',
                'sfpU238','sfpNp237','sfpPu238','sfpPu239','sfpPu240','sfpPu241','sfpPu242',
                'sfpAm241','sfpAm242m','sfpAm243','sfpCm243','sfpCm244','sfpCm245']

    m = fileReSeek(eranosFile," ->CHARGE\s+(\S+).*")
    words = m.group().split()
    words.pop(0)
    value = [float(val) for val in words]
    
    for i in range(10):
      words = eranosFile.readline().split()
      value.extend([float(val) for val in words])
    for iso in range(33):
      charge.addMass(listeiso[iso],value[iso])
      onestreamch.addMass(listeiso[iso],value[iso])
    for iso in range(16):  
      charge.addMass(listeiso[iso+33],value[iso+33],True)
      onestreamch.addMass(listeiso[iso+33],value[iso+33],True)
    charge.expandFPs()
    
    m = fileReSeek(eranosFile," ->DISCHARGE\s+(\S+).*")

    words = m.group().split()
    words.pop(0)
    value = [float(val) for val in words]
    
    for i in range(10):
      words = eranosFile.readline().split()
      value.extend([float(val) for val in words])
    for iso in range(33):
      discharge.addMass(listeiso[iso],value[iso])
      onestreamdis.addMass(listeiso[iso],value[iso])
    for iso in range(16):  
      discharge.addMass(listeiso[iso+33],value[iso+33],True)
      onestreamdis.addMass(listeiso[iso+33],value[iso+33],True)
    discharge.expandFPs()

    chblank = Material()
    disblank = Material()
    
    m = fileReSeek(eranosFile," ->CHBLANK\s+(\S+).*")
    words = m.group().split()
    words.pop(0)
    value = [float(val) for val in words]
    
    for i in range(10):
      words = eranosFile.readline().split()
      value.extend([float(val) for val in words])
    for iso in range(33):
      chblank.addMass(listeiso[iso],value[iso])
      onestreamch.addMass(listeiso[iso],value[iso])
    for iso in range(16):  
      chblank.addMass(listeiso[iso+33],value[iso+33],True)
      onestreamch.addMass(listeiso[iso+33],value[iso+33],True)
    chblank.expandFPs()
    onestreamch.expandFPs()

    m = fileReSeek(eranosFile," ->DISBLANK\s+(\S+).*")    
    
    words = m.group().split()
    words.pop(0)
    value = [float(val) for val in words]
    
    for i in range(10):
      words = eranosFile.readline().split()
      value.extend([float(val) for val in words])
    for iso in range(33):
      disblank.addMass(listeiso[iso],value[iso])
      onestreamdis.addMass(listeiso[iso],value[iso])
    for iso in range(16):  
      disblank.addMass(listeiso[iso+33],value[iso+33],True)
      onestreamdis.addMass(listeiso[iso+33],value[iso+33],True)
    disblank.expandFPs()
    onestreamdis.expandFPs()

    #posb = eranosFile.tell()
    eranosFile.seek(posb)
    try:
        mat = "BLANK"
        m = fileReSeek(eranosFile," ->POWERB\s+(\S+).*")
        n = len(cycles)
        #print (n, float(m.groups()[0]))
        cycle.materials[(5,mat)].power = float(m.groups()[0])
    except:
        print('WARNING: No Blanket Discharge Power')

    eranosFile.seek(posb)
    try:
        # Determine reaction rates for FUEL3, FUEL6, FUEL9, and
        # BLANK. First we need to load material balance data. Is this
        # just reading the same data as the last timestep of the last
        # cycle???
        n = len(cycles) + 1
        cycle = Cycle(n, 0, 0, 0)
        cycles.append(cycle)
        for i in fuelNames:
            m = fileReSeek(eranosFile,"\s+MATERIAL\s(FUEL\d+|BLANK)\s+")
            name = m.groups()[0]
            volume = float(eranosFile.readline().split()[-1])
            for n in range(5): eranosFile.readline()
            # Read in material data
            material = readMaterial(eranosFile)
            material.volume = volume
            cycle.materials[(0,name)] = material

        # Now read fission, absorption, and diffusion rates to be able to
        # determine the critical mass
        fuelNames = ['FUEL3', 'FUEL6', 'FUEL9', 'BLANK']
        fileReSeek(eranosFile, " ECCO6.*")
        for name in fuelNames:
            m = fileReSeek(eranosFile, "\sREGION :(FUEL\d+|BLANK)\s*")
            name = m.groups()[0]
            m = fileReSeek(eranosFile,
                           "\s*TOTAL\s+(\S+)\s+(\S+)\s+\S+\s+(\S+).*")
            cycle.materials[(0,name)].nuFissionRate = float(m.groups()[0])
            cycle.materials[(0,name)].absorptionRate = float(m.groups()[1])
            cycle.materials[(0,name)].diffRate = float(m.groups()[2])
            m = fileReSeek(eranosFile, "\s*TOTAL FLUX =\s+(\S+)\s*")
            cycle.materials[(0,name)].flux = float(m.groups()[0])
            #print(m.groups()[0])
    except:
        # No ECCO calculation at end?
        print('WARNING: No ECCO_BLANK calculation at end of run?')

    # Create progress bar
    if gui:
        progress = QProgressDialog("Expanding fission products...",
                                   "Cancel", 0, n_materials, parent)
        progress.setWindowModality(Qt.WindowModal)
        progress.setWindowTitle("Loading...")
        progress.setMinimumDuration(0)
        progress.setValue(0)
        
    pValue = 0
    # Expand all fission products
    for cycle in cycles:
        # Progress bar
        if gui:
            QCoreApplication.processEvents()
            if (progress.wasCanceled()):
                return None

        print("Expanding fission products for Cycle {0}...".format(cycle.n))
        for mat in cycle.materials.values():
            mat.expandFPs()

            # Set progress bar value
            pValue += 1
            if gui:
                progress.setValue(pValue)


    # Close file and return
    eranosFile.close()
    return cycles, charge, discharge, chblank, disblank, onestreamch, onestreamdis