Exemplo n.º 1
0
 def test_floating_volume_above_scene(self):
     model = Model()
     model.add_node(0, 0, 0)
     model.add_node(0, 1, 0)
     model.add_node(1, 1, 0)
     model.add_node(1, 0, 0)
     model.add_triangle(0, 1, 2)
     model.add_triangle(1, 2, 3)
     intersected_triangles = model.fresnel_zone_intersection(1, 1, Point3D(-0.5, 0, 2),
                                                             Point3D(0.5, 0, 1))
     self.assertEqual(intersected_triangles, [])
Exemplo n.º 2
0
def run_calculations(input_xml, run_first=True):
    """
    Run all calculations
    """

    # load project
    project = Project.from_xml(input_xml)

    for i, calc in enumerate(project.computations):
        if run_first or i > 0:
            print('Select calculation '+str(i)+' :', calc.name)
            project.select_computation(calc)

            print('Update altimetry')
            altim = AltimetryMesh.from_site(project.site)
            project.update_site_altimetry(altim)

            print('Get Solver object from Tympan project located at %s' % ty_solverdir)
            solver = Solver.from_project(project, ty_solverdir)

            print('Build model')
            model = Model.from_project(project, set_sources=True,
                                       set_receptors=True)
            print('Launch solver')
            result = solver.solve(model)

            # Import results to project
            print('Import results')
            project.import_result(model, result)

            # result must be destroyed otherwise it crashes
            del result

    return project
Exemplo n.º 3
0
 def test_with_file(self):
     """
         * For each project, positions (x, y, z) and spectrums (31 values) are
           recorded into 2D np.arrays (1 line = 1 source = 34 rows).
         * There is 1 np.array "expected_sources" for the expected result
           (read from "sources_file") and another one "real_sources"
           containing the actual values that are being checked.
         * These 2 arrays are ordered (first by coordinates, then if necessary
           by values -- see compare_floats())
         * Then the lines are compared 2 by 2
     """
     project = self.load_project(project_file)
     model = Model.from_project(project, set_receptors=False)
     nexpected_sources = sum(1 for line in open(sources_file))
     # Check no sources are missing
     self.assertEqual(nexpected_sources, model.nsources)
     # Read expected result
     expected_sources = np.loadtxt(sources_file)
     # push real values to another nparray
     real_sources = np.array(
         list([source.position.x, source.position.y, source.position.z] +
              source.spectrum.values.tolist() for source in model.sources))
     if model.nsources > 1:
         # Order the two lists to be able to compare them two by two
         expected_sources = sorted(expected_sources,
                                   key=cmp_to_key(compare_floats))
         real_sources = sorted(real_sources, key=cmp_to_key(compare_floats))
     else:
         real_sources = real_sources[0]
     # Compare the sources
     assert_allclose(expected_sources, real_sources, atol=1e-03)
Exemplo n.º 4
0
    def extract_from_model(self, project):
        """ Extract from model """
        data = ([])
        model = Model.from_project(project)
        # Build dict
        dict_id_name = build_dict(project)

        data.append(["Nombre de sources acoustiques:", len(model.sources)])
        self.append_blank_line(data)
        # SourceSolvers ranked by names/then positions:
        source_names = list(
            dict_id_name[src.face_id if src.face_id != "" else src.volume_id]
            for src in model.sources)
        source_positions = list([
            str(src.position.x) + "," + str(src.position.y) + "," +
            str(src.position.z)
        ] for src in model.sources)
        for name, _, source in sorted(zip(source_names, source_positions,
                                          model.sources),
                                      key=itemgetter(0, 1)):
            data.append(["Source acoustique:", ""])
            data.append(["Nom", name])
            self.append_xyz(data, "Position", source.position)
            self.append_spectrum(data, power2db(source.spectrum.values))
            self.append_blank_line(data)

        return data
Exemplo n.º 5
0
 def test_with_file(self):
     """
         Operates as in make_sources_test_with_file (see above), except here
         we are just dealing with positions and not spetrums.
     """
     project = self.load_project(project_file)
     model = Model.from_project(project, set_sources=False)
     # Check no receptors are missing
     nexpected_receptors = sum(1 for line in open(receptors_file))
     self.assertEqual(nexpected_receptors, model.nreceptors)
     # Read expected result
     expected_receptors = np.loadtxt(receptors_file)
     real_receptors = np.array(
         list([
             receptor.position.x, receptor.position.y, receptor.position.z
         ] for receptor in model.receptors))
     if model.nreceptors > 1:
         # Order the two lists to be able to compare the receptors' positions two by two
         expected_receptors = sorted(expected_receptors,
                                     key=cmp_to_key(compare_floats))
         real_receptors = sorted(real_receptors,
                                 key=cmp_to_key(compare_floats))
     else:
         real_receptors = real_receptors[0]
     # Compare the receptors
     assert_allclose(expected_receptors, real_receptors, atol=1e-03)
Exemplo n.º 6
0
def run_calculations(project):
    ''' Run all calculations
    '''
    ty_solverdir = os.environ.get('TYMPAN_SOLVERDIR')
    if not ty_solverdir:
        raise RuntimeError(
            'Please set the TYMPAN_SOLVERDIR environment variable')

    for calc in project.computations:
        print('Select calculation:', calc.name)
        project.set_current_computation(calc)

        print('Update altimetry')
        altim = AltimetryMesh.from_site(project.site)
        project.update_site_altimetry(altim)

        print('Get Solver object from Tympan project located at %s' %
              ty_solverdir)
        solver = Solver.from_project(project, ty_solverdir)

        print('Build model')
        model = Model.from_project(project,
                                   set_sources=True,
                                   set_receptors=True)
        print('Launch solver')
        result = solver.solve(model)

        # print('Save results')
        # Import results to project
        project.import_result(model, result)

        # result must be destroyed otherwise it crashes
        del result
Exemplo n.º 7
0
 def test_alti_mesh(self):
     proj = self.load_project(osp.join('projects-panel', 'fresnel.xml'))
     model = Model.from_project(proj)
     length = 75
     width = 75
     height = 75
     intersected_triangles = model.fresnel_zone_intersection(width, height,
                                                             Point3D(-length/2., 0, 0),
                                                             Point3D(length/2., 0, 0))
     all_triangles = model.triangles
     self.assertEqual(len(all_triangles), 51)
     for tri_idx, triangle in enumerate(all_triangles):
         node_inside_box = False
         for node in triangle.nodes:
             x, y, z = model.node_coords(node)
             if abs(x) <= length/2 and abs(y) <= width/2 and abs(z) <= height/2:
                 node_inside_box = True
         # If one of the node of the triangle is inside the box, make sure it is part of
         # the intersected triangles
         if node_inside_box:
             self.assertIn(tri_idx, intersected_triangles)
         # If the triangle isn't part of the intersected triangles, make sure it has no node
         # inside the box.
         if tri_idx not in intersected_triangles:
             self.assertFalse(node_inside_box)
Exemplo n.º 8
0
 def test_volume_inside_scene(self):
     """Simple test with a planar scene and a cube on top of it"""
     # build a model with two triangles (z=0)
     model = Model()
     model.add_node(0, 0, 0)
     model.add_node(0, 1, 0)
     model.add_node(1, 1, 0)
     model.add_node(1, 0, 0)
     model.add_triangle(0, 1, 2)
     model.add_triangle(1, 2, 3)
     intersected_triangles = model.fresnel_zone_intersection(1, 1, Point3D(-0.5, 0, 0),
                                                             Point3D(0.5, 0, 0))
     self.assertEqual(intersected_triangles, [0, 1])
Exemplo n.º 9
0
 def test_base(self):
     # XXX This test uses expected bad values provided by the current
     # implementation
     project = self.load_project('solver_export', "base.xml")
     model = Model.from_project(project)
     self.assertEqual(model.npoints, 6)  # OK
     self.assertEqual(model.ntriangles, 5)  # XXX should be 4
     self.assertEqual(model.nmaterials, 5)  # XXX should be 1
Exemplo n.º 10
0
 def _compute_project(self, test_file):
     project = self.load_project(test_file)
     model = Model.from_project(project)
     solver = Solver.from_project(project, TEST_SOLVERS_DIR)
     # avoid segfaults due to multithreading
     solver.nb_threads = 1
     solver_result = solver.solve(model)
     project.import_result(model, solver_result)
     return project
Exemplo n.º 11
0
    def test_with_file(self):
        # Load and solve the project
        project = self.load_project(osp.join(TEST_PROBLEM_DIR, test_file))
        model = Model.from_project(project)
        solver = Solver.from_project(project, TEST_SOLVERS_DIR)
        # avoid segfaults due to multithreading
        solver.nthreads = 1
        solver_result = solver.solve(model)
        project.import_result(model, solver_result)
        # Load the expected result
        result_file = osp.join(TEST_RESULT_DIR,
                               test_file).replace('_NO_RESU', '')
        expected_result_project = Project.from_xml(result_file)
        # Compare results
        current_result = project.current_computation.result
        expected_result = expected_result_project.current_computation.result
        # Check we have the same number of receptors
        self.assertEqual(current_result.nreceptors, expected_result.nreceptors)
        # Check if there is a control point (TYPointControl) among the receptors
        # in the project.
        # If not, we are not interested in checking the sources since the
        # control points are the only receptors able to take into account the
        # individual contributions of the sources.
        # The sources here can be user sources, the machines and the buildings
        # (TYUserSourcePonctuelle, TYMachine, TYBatiment)
        check_nsources = False
        for i in xrange(current_result.nreceptors):
            if current_result.receptor(i).is_control_point():
                self.assertTrue(expected_result.receptor(i).is_control_point())
                check_nsources = True
        if check_nsources:
            self.assertEqual(current_result.nsources, expected_result.nsources)
        current_spectra = np.array(
            list(
                current_result.spectrum(current_result.receptors[i],
                                        current_result.sources[j]).values
                for i in xrange(current_result.nreceptors)
                for j in xrange(current_result.nsources)))
        expected_spectra = np.array(
            list(
                expected_result.spectrum(expected_result.receptors[i],
                                         expected_result.sources[j]).values
                for i in xrange(current_result.nreceptors)
                for j in xrange(current_result.nsources)))
        if current_result.nsources + current_result.nreceptors > 1:
            # Order the two spectra lists because spectra are not always kept in the same order
            current_spectra = sorted(current_spectra, cmp=compare_floats)
            expected_spectra = sorted(expected_spectra, cmp=compare_floats)

        for i in xrange(len(current_spectra)):
            # All spectra must have the same number of elements
            self.assertEqual(current_spectra[i].size, expected_spectra[i].size)
            np.testing.assert_almost_equal(current_spectra[i],
                                           expected_spectra[i],
                                           decimal=1)
Exemplo n.º 12
0
 def test_global(self):
     """ Global test """
     project = run_calculations("Projet_Machine_multiBoites.xml")
     model = Model.from_project(project)
     list_src = model.sources
     # Compute the spectrum per face:
     (src_spectrums, src_ids) = calc_surf_spectrum(list_src)
     # Check the spectrum are the sames:
     i = 0
     for val, _ in zip(src_spectrums, src_ids):
         np.testing.assert_array_equal(val, list_src[i].spectrum.values)
         i += 1
Exemplo n.º 13
0
 def test_computation_with_manually_added_source(self):
     power_lvl = np.array([10.0] * 31, dtype=float)
     ref_proj = self.load_project('site_receptor_source.xml')
     ref_model = Model.from_project(ref_proj)
     assert ref_model.nsources == 1
     assert ref_model.nreceptors == 1
     ref_src = ref_model.source(0)
     assert (ref_src.position.x, ref_src.position.y,
             ref_src.position.z) == (3., 3., 2.)
     assert_allclose(ref_src.spectrum.to_dB().values, power_lvl)
     solver = Solver.from_project(ref_proj, TEST_SOLVERS_DIR)
     ref_result = solver.solve(ref_model).spectrum(0, 0).values
     # do the same with a manually added source (the xml project is the same as
     # 'site_receptor_source.xml' except the source has been removed)
     proj = self.load_project('site_receptor.xml')
     model = Model.from_project(proj)
     assert model.nsources == 0
     assert model.nreceptors == 1
     model.add_source((3., 3., 2.), power_lvl, 0)
     solver = Solver.from_project(proj, TEST_SOLVERS_DIR)
     result = solver.solve(model).spectrum(0, 0).values
     assert_allclose(ref_result, result)
Exemplo n.º 14
0
 def test_value(self):
     proj = self.load_project('site_receptor.xml')
     model = Model.from_project(proj)
     power_lvl = np.array(
         [10., 10., 10., 15., 15., 15., 20., 20., 20., 20., 50.],
         dtype=float)
     model.add_source((3., 3., 2.), power_lvl, 0)
     assert model.nsources == 1
     source = model.source(0)
     self.assertAlmostEqual(source.value(16.0), 1e-11)
     self.assertAlmostEqual(source.value(63.0), 1e-11)
     self.assertAlmostEqual(source.value(100.0), 1e-10)
     self.assertEqual(source.value(160.0), 1e-7)
Exemplo n.º 15
0
 def test_triangle_container(self):
     """Check the id of the volume containing the acoustic triangles from the topography"""
     proj = self.load_project(osp.join('projects-panel', 'site_with_single_machine.xml'))
     model = Model.from_project(proj)
     found_a_topography_triangle = False
     for triangle in model.triangles:
         # triangles can come from the topography or the altimetry. The ones from the altimetry
         # don't possess any volume id.
         if triangle.volume_id:
             self.assertEqual(triangle.volume_id, "{91ed858c-8434-467a-bf14-bac2447a0ee7}")
             found_a_topography_triangle = True
     # make sure we checked at least one topography triangle volume id, otherwise the test
     # doesn't stand for anything.
     self.assertTrue(found_a_topography_triangle)
Exemplo n.º 16
0
 def test_source_altimetry(self):
     fpath = osp.join(
         TEST_PROBLEM_DIR,
         '14_PROJET_GRAND_SITE_VIDE_AVEC_SOUS_SITE_Deplace_et_tourne.xml')
     project = Project.from_xml(fpath)
     # Compute altimetry and retrieve the resulting mesh
     altimesh = AltimetryMesh.from_site(project.site)
     # Apply new altimetry on the site infrastructure
     project.update_site_altimetry(altimesh)
     # Build solver model and check source altimetry
     model = Model.from_project(project, set_receptors=False)
     # 1 source
     self.assertEqual(model.nsources, 1)
     # source is on the hillock, which is 25 m high. It is at 2m high above the ground
     self.assertAlmostEqual(model.source(0).position.z, 27)
Exemplo n.º 17
0
 def test_source_container(self):
     """Check the id of the surface and volume containing the source"""
     proj = self.load_project(
         osp.join('projects-panel', 'site_with_single_machine.xml'))
     model = Model.from_project(proj)
     for source in model.sources:
         self.assertEqual(source.volume_id,
                          "{91ed858c-8434-467a-bf14-bac2447a0ee7}")
         # Face must be one of the 6 of the volume
         self.assertIn(source.face_id, [
             "{70420c97-5b97-4c5b-b429-ec2aaf801f0d}",
             "{14ce2c62-75d2-4173-b99d-b8a2d1a13da0}",
             "{cfdf78a8-bc89-4583-afff-f238b6752f18}",
             "{805043e8-7698-4c71-9516-f4ae9447c441}",
             "{0c4a96f8-3b43-4313-9eae-af2a2237a2f4}",
             "{e6f1e3a1-f45a-4d2c-bea0-1b3618343738}"
         ])
Exemplo n.º 18
0
def tympan(output_xml):
    """
        Extract results for the plot
    """
    global calc_number
    project = Project.from_xml(output_xml)
    max_calc_number = len(project.computations)
    calc_name = ""
    while not calc_name.startswith("Position") and not calc_name.startswith(
            "Average"):
        calc_number += 1
        # Reset
        if calc_number >= max_calc_number:
            calc_number = 1
        calc = project.computations[calc_number]
        calc_name = calc.name
    # Select the computation
    project.select_computation(calc)
    csv_file = "map" + str(calc_number) + ".csv"
    mesh = project.meshes[0]
    # Export the map:
    mesh.export_csv(csv_file)

    # Read the map:
    x, y, z, values = np.loadtxt(
        csv_file, skiprows=1,
        delimiter=";").T  # Transposed for easier unpacking
    # Look for number of rows and cols
    for nrows in range(1, len(x)):
        if x[nrows] < x[nrows - 1]:
            break
    ncols = int(len(values) / nrows)
    data = values.reshape((nrows, ncols))
    # Show sources:
    src_x = []
    src_y = []
    model = Model.from_project(project)
    for src in model.sources:
        src_x.append(src.position.x)
        src_y.append(src.position.y)
    # Select unit:
    unit = 'dBA' if mesh.getDataType == 0 else 'dBZ'
    print("calc_number ", calc_number)
    print(calc.name)
    print("Spectre min=", values.min(), " max=", values.max())
    return x, y, z, data, src_x, src_y, "Calculation: " + calc.name, unit
Exemplo n.º 19
0
 def test_directivity_vector(self):
     proj = self.load_project(
         osp.join('projects-panel', 'site_with_single_machine.xml'))
     model = Model.from_project(proj)
     vectors = {
         '{cfdf78a8-bc89-4583-afff-f238b6752f18}': [(-1, 0, 0), None],
         '{70420c97-5b97-4c5b-b429-ec2aaf801f0d}': [(1, 0, 0), None]
     }
     for source in model.sources:
         if source.face_id in vectors:
             vectors[source.face_id][1] = (source.directivity_vector.vx,
                                           source.directivity_vector.vy,
                                           source.directivity_vector.vz)
     for key, value in vectors.items():
         if value[1] is None:
             self.fail('No directivity vector found for face %s' % key)
         self.assertEqual(value[0], value[1])
Exemplo n.º 20
0
 def test_combined_spectra(self):
     project = self.load_project(
         osp.join('projects-panel', 'TEST_CUBE_NO_RESU.xml'))
     model = Model.from_project(project, set_sources=False)
     model.add_source(Source((-20, -30, 2), Spectrum.constant(100.0)))
     model.add_source(Source((10, 50, 2), Spectrum.constant(150.0)))
     solver = Solver.from_project(project, solverdir=TEST_SOLVERS_DIR)
     result = solver.solve(model)
     combined_spectra = result.combined_spectra()
     expected_spectra = np.array([
         2.0602e-03, 1.9806e-03, 1.8942e-03, 1.8005e-03, 1.6987e-03,
         1.5867e-03, 1.4610e-03, 1.3166e-03, 1.1486e-03, 9.5532e-04,
         7.4293e-04, 5.2950e-04, 3.4102e-04, 1.9865e-04, 1.0676e-04,
         5.4570e-05, 2.7016e-05, 1.2721e-05, 5.3064e-06, 1.7143e-06,
         3.4595e-07, 3.1354e-08, 7.6832e-10, 2.3192e-12, 2.5400e-16,
         1.6487e-22, 1.3216e-23, 1.3216e-23, 1.3216e-23, 1.3216e-23,
         1.3216e-23
     ])
     for rec in range(result.nreceptors):
         np.testing.assert_almost_equal(combined_spectra[rec, :],
                                        expected_spectra,
                                        decimal=4)
Exemplo n.º 21
0
 def test_add_sources_to_model(self):
     project = self.load_project('projects-panel',
                                 'TEST_SOURCE_PONCTUELLE_NO_RESU.xml')
     model = Model.from_project(project)
     self.assertEqual(model.nsources, 1)
     self.assertEqual(model.nreceptors, 6)
     freq = np.array([100.0] * 31, dtype=float)
     sources = [((1., 1., 0.), freq, 0), ((2., 2., 10.), freq * 2, 0)]
     src_ids = []
     for (pos, spec, shift) in sources:
         src_ids.append(model.add_source(pos, spec, shift))
     self.assertEqual(model.nsources, 3)
     self.assertEqual(model.nreceptors, 6)
     src1 = model.source(src_ids[0])
     self.assertEqual(src1.position.x, 1.)
     self.assertEqual(src1.position.y, 1.)
     self.assertEqual(src1.position.z, 0.)
     assert_allclose(src1.spectrum.to_dB().values, freq)
     src2 = model.source(src_ids[1])
     self.assertEqual(src2.position.x, 2.)
     self.assertEqual(src2.position.y, 2.)
     self.assertEqual(src2.position.z, 10.)
     assert_allclose(src2.spectrum.to_dB().values, freq * 2)
Exemplo n.º 22
0
 def test_add_sources_to_model(self):
     project = self.load_project('projects-panel',
                                 'TEST_SOURCE_PONCTUELLE_NO_RESU.xml')
     model = Model.from_project(project)
     self.assertEqual(model.nsources, 1)
     self.assertEqual(model.nreceptors, 6)
     spectrum = Spectrum.constant(100.0)
     sources = [
         Source((1., 1., 0.), spectrum),
         Source((2., 2., 10.), spectrum * 2),
     ]
     src_ids = [model.add_source(s) for s in sources]
     self.assertEqual(model.nsources, 3)
     self.assertEqual(model.nreceptors, 6)
     src1 = model.source(src_ids[0])
     self.assertEqual(src1.position.x, 1.)
     self.assertEqual(src1.position.y, 1.)
     self.assertEqual(src1.position.z, 0.)
     assert_allclose(src1.spectrum.to_dB().values, spectrum.values)
     src2 = model.source(src_ids[1])
     self.assertEqual(src2.position.x, 2.)
     self.assertEqual(src2.position.y, 2.)
     self.assertEqual(src2.position.z, 10.)
     assert_allclose(src2.spectrum.to_dB().values, spectrum.values * 2)
Exemplo n.º 23
0
def run_calculations(project):
    ''' Run all calculations
    '''
    for calc in project.computations:
        print('Select calculation:', calc.name)
        project.select_computation(calc)

        print('Get Solver object from Tympan project located at %s' %
              ty_solverdir)
        solver = Solver.from_project(project, ty_solverdir)

        print('Build model')
        model = Model.from_project(project,
                                   set_sources=True,
                                   set_receptors=True)
        print('Launch solver')
        result = solver.solve(model)

        # print('Save results')
        # Import results to project
        project.import_result(model, result)

        # result must be destroyed otherwise it crashes
        del result
Exemplo n.º 24
0
def create_calculations(fichier_xml, objects, output_xml):
    """
        Place the objects at the positions
        and save the project in output_xml file
    """

    # load project
    project = Project.from_xml(fichier_xml, verbose=False)

    # altimetry must be updated to get right the source position.z
    altim = AltimetryMesh.from_site(project.site)
    project.update_site_altimetry(altim)

    # Get the calculation
    Model.from_project(project, set_sources=True, set_receptors=True)

    # Get the initial number of computations in the project:
    nb_computations = len(project.computations)
    nb_points = 0
    # Get data from the list of objects
    for object_type, object_xml, object_positions in objects:
        # Import element (engine or building) from XML file:
        elements = import_infra(object_xml, object_type)
        element = elements.engines[
            0] if object_type == "engine" else elements.buildings[0]
        element_name = element.name

        # Get the mesh
        meshes = project.meshes
        if len(meshes) == 0:
            print("Error, no mesh found in the XML file !")
            sys.exit(-1)

        # Retrieve positions from CSV file and direction vect and
        # add the element and do the calculation at each step
        position_x, position_y, position_z, position_angle = import_xyz_angle_csv(
            object_positions, project)

        # Loop on points:
        point = 0
        print("Number of points in " + object_positions + ": " +
              str(len(position_x)))
        if nb_points != 0 and nb_points != len(position_x):
            print(
                "Error, the number of points in CSV files should be the same !"
            )
            sys.exit(-1)
        nb_points = len(position_x)
        for point in range(nb_points):

            x = position_x[point]
            y = position_y[point]
            z = position_z[point]
            angle = position_angle[point]

            # Create the position for the element on the current position:
            pos_element = Point3D()
            pos_element.set_x(x)
            pos_element.set_y(y)
            pos_element.set_z(z)

            rot_element = Point3D()
            rot_element.set_z(angle)  # rotation sur l'axe z

            # Add a computation if necessary
            num_computation = nb_computations + point
            if num_computation >= len(project.computations):
                # New computation needed
                project.add_computation()
                print("Add computation number ", num_computation)
                last_calc = project.computations[num_computation]
                last_calc.add_noise_map(meshes[0])
                project.select_computation(last_calc)
                project.current_computation.set_name(
                    'Position {0}'.format(point))
            else:
                last_calc = project.computations[num_computation]
                project.select_computation(last_calc)
                print("Select computation number ", )

            # select receptors in the current calculation
            for rec in project.user_receptors:
                last_calc.addReceptor(rec)

            # Add a element at the current position pos_element
            site = project.site
            # Change name
            element.setName(element_name + " at position " + str(point))
            if object_type == "engine":
                print("Adding an engine...")
                site.add_engine(element, pos_element, rot_element, 0.)
            elif object_type == "building":
                print("Adding a building...")
                site.add_building(element, pos_element, rot_element, 0.)
            else:
                print("Error: Unknown object type: ", object_type)
                sys.exit(-1)
            print("Point ", point, " :", x, y, angle)

    project.to_xml(output_xml)
    print('Project saved to', output_xml)
Exemplo n.º 25
0
 def test_volume_on_scene(self):
     """Simple test with a squared planar scene and a cube on top of it"""
     model = Model()
     model.add_node(0, 0, 0)
     model.add_node(0, 1, 0)
     model.add_node(1, 1, 0)
     model.add_node(2, 1, 0)
     model.add_node(1, 2, 0)
     model.add_triangle(0, 1, 2)
     model.add_triangle(2, 3, 4)
     # It is on the first triangle but not on the second one
     intersected_triangles = model.fresnel_zone_intersection(1, 1, Point3D(-0.5, 0, 0),
                                                             Point3D(0.5, 0, 0))
     self.assertEqual(intersected_triangles, [0])
Exemplo n.º 26
0
def solve(input_project,
          output_project,
          output_mesh,
          solverdir,
          parameters={},
          multithreading_on=True,
          interactive=False,
          verbose=False,
          altimetry_parameters={}):
    """ Solve an acoustic problem with Code_TYMPAN from

        Keywords arguments:
        input_project -- XML file containing the serialized project with the
            "calcul" to solve
        output_project -- XML file where to put the project updated with the
            results of the computation
        output_mesh -- a file in which to put the altimetry mesh once computed (ply format)
        solverdir -- directory containing the solver plugin
        -------
        optional :
        parameters -- Dictionary containing the solver parameters the user wants to change from their
        default value in the form {'parameter_name':value,...}.
        The possible parameters are: atmos_pressure, atmos_temperature, atmos_hygrometry, wind_direction,
        analytic_gradC, analytic_gradV, ray_tracing_order, discretization, nb_rays_per_source, max_length,
        size_receiver, accelerator, max_tree_depth, angle_diff_min, cylindre_thick, max_profondeur, use_sol,
        max_reflexion, max_diffraction, diffraction_use_random_sampler, nb_ray_with_diffraction, diffraction_drop_down_nb_rays,
        diffraction_filter_ray_at_creation, use_path_dif_validation, max_path_difference, diffraction_use_distance_as_filter,
        keep_debug_ray, use_post_filters, curve_ray_sampler, initial_angle_theta, final_angle_theta, initial_angle_phi, final_angle_phi,
        analytic_nb_ray, analytic_tMax, analyticH, analytic_dMax, analytic_type_transfo, mesh_element_size_max, show_scene, minSR_distance,
        nb_threads, use_real_ground, use_screen, use_lateral_diffraction, use_reflection, propa_conditions, h1parameter, mod_summation, use_meteo,
        use_fresnel_area, anime3D_sigma, anime3D_forceC, anime3D_keep_rays, debug_use_close_event_selector, debug_use_diffraction_angle_selector,
        debug_use_diffraction_path_selector, debug_use_fermat_selector, debug_use_face_selector
    -------
        optional (debug):
        multithreading_on -- set it to False to solve the acoustic problem with only
            one thread
        interactive -- if True, pdb debugger will be invoked before running solving
            the acoustic problem, so that the program can be executed in interactive
            mode.
        The execution is logged into 'tympan.log', created in the directory of
        the input XML project (the one opened from the Code_TYMPAN GUI)
    """
    if interactive:
        import pdb
        pdb.set_trace()

    # Load an existing project and retrieve its calcul to solve it
    try:
        logging.info("Trying to load project ...")
        project = Project.from_xml(input_project,
                                   verbose=verbose,
                                   **altimetry_parameters)
    except RuntimeError:
        logging.exception("Couldn't load the acoustic project from %s file",
                          input_project)
        raise
    logging.info("Project loaded !")
    # Export altimetry
    project.export_altimetry(output_mesh)
    # Solver model
    model = Model.from_project(project)
    logging.info(
        "Solver model built.\nNumber of sources: %d\nNumber of receptors: %d",
        model.nsources, model.nreceptors)
    # Load solver plugin and run it on the current computation
    logging.info("Trying to load solver ...")
    solver = Solver.from_project(project, solverdir, verbose)
    # Setting the parameters chosen by the user
    for parameter in parameters:
        setattr(solver, parameter, parameters[parameter])
    if not multithreading_on:
        solver.nb_threads = 1
    logging.info("Checking solver model ...")
    _check_solver_model(model, project.site)
    logging.debug("Calling C++ SolverInterface::solve() method")
    try:
        solver_result = solver.solve(model)
    except RuntimeError as exc:
        logging.error(str(exc))
        logging.info("It doesn't work", str(exc))
        raise
    logging.info("Solver computation done !")
    # Export solver results to the business model
    logging.info("Loading results from solver ...")
    project.import_result(model, solver_result)
    # Reserialize project
    try:
        logging.info("Trying to export result project to xml ...")
        project.to_xml(output_project)
    except ValueError:
        logging.exception("Couldn't export the acoustic results to %s file",
                          output_project)
        raise
Exemplo n.º 27
0
def solve(input_project,
          output_project,
          output_mesh,
          solverdir,
          multithreading_on=True,
          interactive=False,
          verbose=False):
    """ Solve an acoustic problem with Code_TYMPAN from

        Keywords arguments:
        input_project -- XML file containing the serialized project with the
            "calcul" to solve
        output_project -- XML file where to put the project updated with the
            results of the computation
        output_mesh -- a file in which to put the altimetry mesh once computed (ply format)
        solvedir -- directory containing the solver plugin
        -------
        optional (debug):
        multithreading_on -- set it to False to solve the acoustic problem with only
            one thread
        interactive -- if True, pdb debugger will be invoked before running solving
            the acoustic problem, so that the program can be executed in interactive
            mode.

        The execution is logged into 'tympan.log', created in the directory of
        the input XML project (the one opened from the Code_TYMPAN GUI)
    """
    if interactive:
        import pdb
        pdb.set_trace()
    ret = False
    # Load an existing project and retrieve its calcul to solve it
    try:
        logging.info("Trying to load project ...")
        project = Project.from_xml(input_project, verbose)
    except RuntimeError:
        logging.exception("Couldn't load the acoustic project from %s file",
                          input_project)
        raise
    logging.info("Project loaded !")
    # Recompute and export altimetry
    altimesh = AltimetryMesh.from_site(project.site)
    altimesh.to_ply(output_mesh)
    # Update site and the project before building the solver model
    logging.info("Updating site ...")
    project.update_site_altimetry(altimesh, verbose)
    # Solver model
    model = Model.from_project(project)
    logging.info(
        "Solver model built.\nNumber of sources: %d\nNumber of receptors: %d",
        model.nsources, model.nreceptors)
    # Load solver plugin and run it on the current computation
    logging.info("Trying to load solver ...")
    solver = Solver.from_project(project, solverdir, verbose)
    if not multithreading_on:
        solver.nthread = 1
    logging.info("Checking solver model ...")
    _check_solver_model(model, project.site)
    logging.debug("Calling C++ SolverInterface::solve() method")
    try:
        solver_result = solver.solve(model)
    except RuntimeError as exc:
        logging.error(str(exc))
        logging.info("It doesn't work", str(exc))
        raise
    logging.info("Solver computation done !")
    # Export solver results to the business model
    logging.info("Loading results from solver ...")
    project.import_result(model, solver_result)
    # Reserialize project
    try:
        logging.info("Trying to export result project to xml ...")
        project.to_xml(output_project)
    except ValueError:
        logging.exception("Couldn't export the acoustic results to %s file",
                          output_project)
        raise