Example #1
0
def compare_xml_results(result_xml, reference_xml, testobj):
    """
    Compare the results to expected results extracted from XML files
    """
    project = Project.from_xml(result_xml)
    expected_project = Project.from_xml(reference_xml)
    compare_project_results(project, expected_project, testobj)
Example #2
0
    def test_global(self):
        """ Global test """
        # Building a project by adding sources, receptors, engines, buildings
        project_xml = "Final_project.xml"

        # Create a new project with sources located on positions from Spirale_log.csv:
        main([""], ["Spirale_log.csv"], ["source"], ["MySource"], "",
             project_xml)

        # Update the project by adding several objects:
        main(["", "Machine.xml", "Building.xml"],
             ["Recepteur.csv", "Machine.csv", "Building.csv"],
             ["receptor", "engine", "building"],
             ["MyReceptor", "MyEngine", "MyBuilding"], project_xml,
             project_xml)

        # Check all objects are here in the final project
        # based on the number of lines in CSV file minus 1, the header
        project = Project.from_xml("Final_project.xml")
        nsources = line_count('Spirale_log.csv') - 1
        self.assertEqual(len(project.site.user_sources), nsources)
        nengines = line_count('Machine.csv') - 1
        self.assertEqual(len(project.site.engines), nengines)
        nbuildings = line_count('Building.csv') - 1
        self.assertEqual(len(project.site.buildings), nbuildings)
        nreceptors = line_count('Recepteur.csv') - 1
        self.assertEqual(len(project.user_receptors), nreceptors)
Example #3
0
def load_tympan_xml(tympan_xml):
    """
    Open xml file and return project
    """
    print('Opening Code_TYMPAN project from %s' % tympan_xml)
    project = Project.from_xml(tympan_xml, verbose=False)
    return project
Example #4
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
Example #5
0
 def test_select_solver(self):
     project = Project.from_xml(
         os.path.join(TEST_DATA_DIR, 'empty_site.xml'))
     self.assertEqual(project.current_computation.solver_id,
                      "{a98b320c-44c4-47a9-b689-1dd352daa8b2}")
     project.set_solver('ANIME3DSolver', solverdir=TEST_SOLVERS_DIR)
     self.assertEqual(project.current_computation.solver_id,
                      "{2f0b51a7-37bd-414e-8908-baea85acef2c}")
Example #6
0
def load_elements(elements_xml):
    """
       Load elements defined in the file elements_xml
    """
    # Load project from XML file and get elements
    project_elements = Project.from_xml(elements_xml)
    elements = project_elements.site

    return elements
def load_tympan_xml(tympan_xml):
    '''
    Return data read from Code_Tympan XML file and built using Code_Tympan
    data model and altimetry
    tympan_xml: filepath to xml tympan project file
    '''
    print('Building Tympan model from %s' % tympan_xml)
    project = Project.from_xml(tympan_xml, verbose=False)

    return project
Example #8
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)
Example #9
0
 def load_project(self, *path):
     from tympan.models.project import Project
     from tympan.altimetry import AltimetryMesh
     # read acoustic project
     project = Project.from_xml(osp.join(TEST_DATA_DIR, *path))
     with self.no_output():
         # compute altimetry (silently)
         altimesh = AltimetryMesh.from_site(project.site)
         # update site altimetry
         project.update_site_altimetry(altimesh)
     return project
Example #10
0
 def build_altimetry(self, fname):
     """Return the AltimetryMesh instance from Tympan XML file name"""
     fpath = os.path.join(TEST_PROBLEM_DIR, fname)
     project = Project.from_xml(fpath, verbose=self.debug)
     altim = AltimetryMesh.from_site(project.site)
     site = altim.equivalent_site
     if self.saveply:
         plyfile = os.path.abspath(fname.split('.')[0] + '.ply')
         altim.to_ply(plyfile)
         print 'PLY file saved at ', plyfile
     return altim
Example #11
0
def main(tympan_xml,
         receptors_csv,
         output_xml,
         output_txt='Niveau_sonore_moyen.txt'):
    """
        Main
    """
    # load project
    project = Project.from_xml(tympan_xml)

    # Case receptors are read in a CSV file
    if receptors_csv != "":
        # Import and add receptor positions
        x, y, z = import_xyz_csv(receptors_csv, project)
        for i in range(len(x)):
            height = z[i]
            position = Point3D()
            position.set_x(x[i])
            position.set_y(y[i])
            position.set_z(height)
            project.add_user_receptor(position, height, "Position_" + str(i))

    # Run the calculations
    run_calculations(project)

    # Choose current computation, get receptors list and sources list
    list_calc = []
    list_calc.append(project.current_computation.name)
    list_src = get_sources_list(project, list_calc)
    list_rec = get_receptors_list(project, list_calc)

    # Get receptor number
    N = len(list_rec)

    # Get spectrums
    valeurs, nom_spectres = get_rec_spec(project, list_src, list_rec)
    del nom_spectres

    # Calculate mean value and set spectrum name
    val_result = np.sum(valeurs, axis=0) / N
    nom_spectre = ['Niveau sonore moyen sur parcours']

    # Write results to a .txt file
    print('\nFile created: ' + output_txt)
    write_results(val_result, nom_spectre, output_txt)

    # Save to output_xml
    if output_xml != "":
        project.to_xml(output_xml)
        print('Result saved to', output_xml)

    return project
Example #12
0
def compare_xml_meshes_results(result_xml, reference_xml, testobj):
    """
    Compares the result in meshes 
    """
    project = Project.from_xml(result_xml)
    expected_project = Project.from_xml(reference_xml)

    testobj.assertEqual(len(project.meshes), len(
        expected_project.meshes), 'The two projects must have only one mesh each')
    testobj.assertEqual(len(project.meshes[0].receptors), len(expected_project.meshes[0].receptors),
                        'The two projects must have meshes with the same number of receptors')

    project_computations = project.computations[1:-1]
    expected_project_computations = expected_project.computations
    for comp1, comp2 in zip(project_computations, expected_project_computations):
        project.select_computation(comp1)
        expected_project.select_computation(comp2)
        testobj.assertEqual(comp1.name, comp2.name)
        results = np.array([r.dBA for r in project.meshes[0].receptors])
        expected_results = np.array(
            [p.dBA for p in expected_project.meshes[0].receptors])

        np.testing.assert_allclose(results, expected_results, atol=0.5)
Example #13
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)
Example #14
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
def main(input_project, result_file):
    """Process altimetry from `input_project` and save to `result_file` (PLY
    format).
    """
    try:
        try:
            project = Project.from_xml(input_project, verbose=True)
        except RuntimeError:
            logging.exception(
                "Couldn't load the acoustic project from %s file",
                input_project)
            raise
        altimesh = AltimetryMesh.from_site(project.site)
        altimesh.to_ply(result_file)
    except Exception as exc:
        sys.stderr.write('Error: %s' % exc)
        logging.exception("Error processing the altimetry:\n%s", exc)
Example #16
0
    def load_xml_file(self):
        """
        Load TYMPAN xml file, set the meshes (récepteurs
        surfaciques)list and the computations list
        """
        # Open dialog window to choose XML file
        self.xml_file = askopenfile(title=u"Ouvrir XML",
                                    filetypes=[('xml files', '.xml'),
                                               ('all files', '.*')])
        # Set project
        self.project = Project.from_xml(self.xml_file.name)

        # Get meshes
        rec_surf = self.project.meshes
        size = len(rec_surf)
        if size == 0:
            d = MyDialog(self, u"Pas de mesh trouvé dans le fichier XML !")
            self.wait_window(d.top)
            del self.xml_file
            del self.project
            del rec_surf
            return

        # Set label variable in principal window
        self.labelVariable.set(self.xml_file.name)

        self.list_rec_surf.delete(0, tk.END)
        for i in range(len(rec_surf)):
            self.list_rec_surf.insert(i,
                                      u"Récepteur surfacique n°" + str(i + 1))

        # Get computations
        comps = self.project.computations
        self.list_comp_01.delete(0, tk.END)
        for i in range(len(comps)):
            self.list_comp_01.insert(i, comps[i].name)
        self.list_comp_02.delete(0, tk.END)
        for i in range(len(comps)):
            self.list_comp_02.insert(i, comps[i].name)

        # Set computations and mesh labels
        self.labelRecSurf.set(u"Choisis un récepteur surfacique...")
        self.labelRefComp01.set(u"Choisis le calcul n°1...")
        self.labelRefComp02.set(u"Choisis le calcul n°2...")
Example #17
0
def main(input_project,
         result_file,
         size_criterion=0.0,
         refine_mesh=True,
         use_vol_landtakes=False):
    """Process altimetry from `input_project` and save to `result_file` (PLY
    format).
    """
    try:
        project = Project.from_xml(input_project,
                                   verbose=True,
                                   size_criterion=size_criterion,
                                   refine_mesh=refine_mesh,
                                   use_vol_landtakes=use_vol_landtakes)
    except RuntimeError:
        logging.exception("Couldn't load the acoustic project from %s file",
                          input_project)
        raise
    project.export_altimetry(result_file, size_criterion=size_criterion)
Example #18
0
 def test_process_vegetation_area(self):
     fpath = osp.join(TEST_PROBLEM_DIR,
                      'Site_avec_2_terrain_1_avec_veget_1_sans.xml')
     project = Project.from_xml(fpath)
     asite = builder.build_sitenode(project.site)
     _, _, feature_by_face = builder.build_altimetry(asite)
     matarea = list(asite.material_areas)
     self.assertEqual(len(matarea), 2)
     try:
         vegarea = asite.features_by_id['{60260543-0297-4cec-aacc-cb63492d1171}']
     except KeyError:
         self.fail('vegetation area not found in altimetry site')
     self.assertEqual(vegarea.height, 10)
     self.assertTrue(vegarea.foliage)
     self.assertEqual(vegarea.variety, 'aspen')
     vegfaces = [fh for fh, feature in feature_by_face.items()
                 if isinstance(feature, VegetationArea)]
     # Just check there are faces in the vegetation area.
     self.assertTrue(vegfaces)
    def load_compared_xml_file(self, xml_file=""):
        """
        Load TYMPAN xml file and set compared project
        """
        if xml_file == "":
            # Open dialog window to choose XML file
            xml_file = askopenfile(title=u"Ouvrir le fichier XML",
                                   filetypes=[('fichiers xml', '.xml'),
                                              ('tous les fichiers', '.*')
                                              ]).name
            # Set label variable in principal window
            self.label2Variable.set(xml_file)

        # Set project
        try:
            self.project_compared = Project.from_xml(xml_file)
        except:
            self.label2Variable.set("")
            d = MyDialog(self, u"Erreur, ce n'est pas un projet Code_TYMPAN.")
            self.wait_window(d.top)
            return
Example #20
0
 def test_parameters_serialization(self):
     config = ('''
         [tutu]
             titi=15549.15
             toto=hi there!
             tata=0
         ''')
     # Open a basic project that doesn't have solver parameters
     project = self.load_project('', 'empty_site.xml')
     # Set a custom solver configuration to it
     project.current_computation.solver_parameters = config
     # Export to XML and reimport it
     with tempfile.NamedTemporaryFile(suffix='.xml', delete=False) as f:
         project.to_xml(f.name)
         configured_project = Project.from_xml(f.name)
         # Check configuration didn't disappear
         self.assertEqual(
             configured_project.current_computation.solver_parameters.
             decode(), config)
     f.close()
     os.unlink(f.name)
 def test_import_xyz_csv(self):
     """ Test CSV import """
     positions = np.asarray([[2.0, 0.0, 2.0], [0.0, 2.0, 2.1], [-2.0, 0.0, 2.2], [0.0, -2.0, 2.3]])
     # Write
     np.savetxt("comma.csv", positions, delimiter=',')
     # Read
     project = Project.from_xml("Recepteur_mobile.xml")
     x1, y1, z1 = import_xyz_csv("comma.csv", project)
     # Compare
     np.testing.assert_array_equal(x1, positions[:, 0])
     np.testing.assert_array_equal(y1, positions[:, 1])
     np.testing.assert_array_equal(z1, positions[:, 2])
     # Check if error if the point is well detected outside the domain:
     positions = np.asarray([[2.0, 10000.0, 2.0]])
     np.savetxt("comma.csv", positions, delimiter=',')
     try:
         import_xyz_csv("comma.csv", project)
     except:
         print("OK, it detects expected error.")
     else:
         sys.exit(-1)
Example #22
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)
Example #23
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
Example #24
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
Example #25
0
def main(object_file_list, object_positions_file_list, object_type_list,
         object_name_list, input_xml, output_xml):
    """
    Import csv file with TYMPAN coordinates and create new project with objects
    Or add objects to an existing project
    """
    # Create new project if no project entered by user
    project = Project.create() if input_xml == '' else Project.from_xml(
        input_xml)

    # Loop on objects
    for object_file, object_positions_file, object_type, object_name in zip(
            object_file_list, object_positions_file_list, object_type_list,
            object_name_list):
        # Import the object read in the xml file:
        if object_file != "":
            # Import the elements from XML file:
            elements = import_infra(object_file, object_type)

        # Create numpy array with csv file containing TYMPAN coordinates of the objects
        my_data = np.genfromtxt(object_positions_file,
                                dtype='float',
                                delimiter=';',
                                skip_header=1)
        if my_data.shape[1] < 3:
            print("Error! Should read x,y,z or x,y,z,angle in " +
                  object_positions_file)
            sys.exit(-1)
        # Add object to project site for each position
        site = project.site
        rotation = Point3D(0, 0, 0)
        for i in range(len(my_data[:, 0])):
            position = Point3D()
            height = my_data[i, 2]
            position.set_x(my_data[i, 0])
            position.set_y(my_data[i, 1])
            position.set_z(height)
            # Add rotation if found
            if my_data.shape[1] == 4:
                rotation.set_z(my_data[i, 3])
            name = object_name + str(i)
            # Add object:
            if object_type == "source":
                # Source
                src = User_source(height, name, position)
                site.add_user_source(src, position, height)
            elif object_type == "receptor":
                # Receptor
                project.add_user_receptor(position, height, name)
            elif object_type == "engine":
                # Engine
                site.add_engine(elements.engines[0], position, rotation,
                                height)
            elif object_type == "building":
                # Building
                site.add_building(elements.buildings[0], position, rotation,
                                  height)
            else:
                print("Error: Unknown object type: ", object_type)
                sys.exit(-1)

        # Add project user_receptors to the last computation
        if object_type == "receptor":
            calcul = project.computations[-1]
            for rec in project.user_receptors:
                calcul.addReceptor(rec)

    # Write the project
    project.to_xml(output_xml)
    print('Project saved to ', output_xml)
 def test_compare_results(self):
     """ Test compare_results utility """
     project = Project.from_xml("Recepteur_mobile.xml")
     expected_project = Project.from_xml("Recepteur_mobile.xml")
     compare_project_results(project, expected_project, self)
Example #27
0
 def altimetry_site(self, xmlfile):
     """Build altimetry site from TYProject and Site as read from XML file"""
     fpath = osp.join(TEST_PROBLEM_DIR, xmlfile)
     project = Project.from_xml(fpath)
     return builder.build_sitenode(project.site)
Example #28
0
 def load_project(self, *path):
     from tympan.models.project import Project
     # read acoustic project
     project = Project.from_xml(osp.join(TEST_DATA_DIR, *path))
     return project