def import_sanidad_2015(survey,infile):
    """ Function to import_modules sanidad records from plots in the 2015 file format

    :param survey:  An instance of the survey class
    :param infile:  The file path to the import_modules file
    """
    #TODO This function is only a template and will not work in the current version as it is unclear how the sanidad files should be imported
    with open(infile, 'rb') as data:
        datareader = csv.DictReader(data, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre']
            if ID in survey.plots.keys():
                try:
                    numbarb = row['numarb_sanp']
                    sanidadA= class_lib.Sanidad(numbarb)
                except ValueError:
                    warnin_msg = 'Could not use the variable \"numarb_sanp\" with with value: \"{value}\" as id for sanidad of plot {plotid}'\
                        .format(value=row['numarb_sanp'], plotid=ID)
                    logging.warn(warnin_msg)

                if sanidadA:
                    sanidadA.san_dap = tools_lib.import_variable(row, 'dap_sanp', 'float')
                    sanidadA.san_categoria = tools_lib.import_variable(row, 'categoria_sanp', 'int')
                    sanidadA.san_tipo_fuste = tools_lib.import_variable(row, 'tipofuste_sanp', 'int')
                    sanidadA.san_porcopa = tools_lib.import_variable(row, 'porccopa_sanp', 'int')
                    sanidadA.san_porcopa = tools_lib.import_variable(row, 'porccopa_sanp', 'int')

    info_msg = "Updated the equipo table for {nplots} plots from the file: {file}"\
                    .format(nplots=counter.__len__(),file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 2
0
def import_flora_soto_2015(survey, infile):
    """
    Function to import_modules the flora soto records into the survey

    :param survey: An instance of base class Survey
    :param infile: The file path to the input file
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        counter = []
        for row in datareader:
            # Here we should replace all empty string with None in the dictonary row
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'Flora':
                    flora_soto_tipo = tools_lib.import_variable(
                        row, 'tipoSotobosque', 'code', ID,
                        code_lists.flora_suelo_tipo)
                    if flora_soto_tipo:
                        floraSotoA = class_lib.FloraSoto(ID, flora_soto_tipo)
                        floraSotoA.flora_soto_altura = tools_lib.import_variable(
                            row, 'alturaSotobosque', 'float', ID)
                        floraSotoA.flora_soto_altura_unit_name = "metros"
                        survey.plots[ID].flora_soto[
                            id_generator()] = floraSotoA
                        survey.plots[ID].flora_soto_flora_soto_presencia = 1
                        if ID not in counter:
                            counter.append(ID)
    info_msg = "Updated the flora soto table for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
def import_flora_suelo_2015(survey,species_list, infile):
    """
    Function to import_modules the flora suelo records into the survey

    :param survey: An instance of base class Survey
    :param species_list: A dictonary with all species
    :param infile: The file path to the input file
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        plot_counter=[]
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'FloraDelSuelo':
                    species = ''
                    if row.has_key('nombreCientifico_FloraDelSuelo') and row['nombreCientifico_FloraDelSuelo'] not in ['',' ']:
                        species = row['nombreCientifico_FloraDelSuelo'].strip()
                    if row.has_key('nombreCientifico_floraDelSuelo') and row['nombreCientifico_floraDelSuelo'] not in ['', ' ']:
                        species = row['nombreCientifico_floraDelSuelo'].strip()
                    index = tools_lib.find_species_scientific(species_list, species)
                    if index.__len__() > 0:
                        floraSueloA = class_lib.FloraSuelo(ID, species_list[index[0]].species_code)
                        floraSueloA.flora_suelo_especie_scientific_name = species_list[index[0]].scientific_name
                        floraSueloA.flora_suelo_especie_vernacular_name = species_list[index[0]].common_name
                        if row.has_key('Frecuencia_FloraDelSuelo'):
                            floraSueloA.flora_suelo_freq = tools_lib.import_variable(row, 'Frecuencia_FloraDelSuelo',
                                                                                          'code', ID,
                                                                                     code_lists.flora_suelo_freq)
                        if row.has_key('frecuencia_floraDelSuelo'):
                            floraSueloA.flora_suelo_freq = tools_lib.import_variable(row,
                                                                                          'frecuencia_floraDelSuelo',
                                                                                          'code', ID,
                                                                                     code_lists.flora_suelo_freq)
                        survey.plots[ID].flora_suelo[floraSueloA.flora_suelo_especies_code] = floraSueloA
                        survey.plots[ID].flora_soto_flora_soto_presencia = 1
                        if ID not in plot_counter:
                            plot_counter.append(ID)
                    else:
                        warn_msg = 'Flora suelo species "{species}" on plot {plotid} is not in the flora suelo species list in plot {plotid}'\
                                    .format(species=species,plotid=ID)
                        logging.warn(warn_msg)
    info_msg = "Updated the flora suelo table for {nplots} plots from the file: {file}" \
        .format(nplots=plot_counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 4
0
def import_invasoras_2015(survey, species_list, infile):
    """ Function to import_modules invasores records from plots in the 2015 file format

    :param survey:  An instance of the survey class
    :param species_list: Dictonary with the invasora species
    :param infile:  The file path to the import_modules file
    """
    with open(infile, 'rb') as data:
        datareader = csv.DictReader(data, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'EspeciesInvasoras':
                    if row.has_key(
                            'nombreCientifico_EspeciesInvasoras'
                    ) and row['nombreCientifico_EspeciesInvasoras'] not in [
                            '', ' '
                    ]:
                        species = row[
                            'nombreCientifico_EspeciesInvasoras'].strip()
                        index = tools_lib.find_species_scientific(
                            species_list, species)
                        if index.__len__() > 0:
                            invasoraA = class_lib.Invasora(
                                ID, species_list[index[0]].species_code)
                            invasoraA.invasora_especie_scientific_name = species_list[
                                index[0]].scientific_name
                            invasoraA.invasora_especie_vernacular_name = species_list[
                                index[0]].common_name
                            invasoraA.invasora_categoria = \
                                tools_lib.import_variable(row, 'Categoría_EspeciesInvasoras', 'code',
                                                          ID, code_lists.invasora_categoria)
                            invasoraA.invasora_severidad = \
                                tools_lib.import_variable(row, 'severidad_invasora', 'code', ID,
                                                          code_lists.invasora_severidad)
                            survey.plots[ID].invasoras[
                                invasoraA.invasora_especie_code] = invasoraA
                            if ID not in counter:
                                counter.append(ID)

    info_msg = "Updated the invasores table for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 5
0
def import_equipo_2015(survey, infile):
    """ Function to import_modules equipment records from plots in the 2015 file format

    :param survey:  An instance of the survey class
    :param infile:  The file path to the import_modules file
    """
    with open(infile, 'rb') as data:
        datareader = csv.DictReader(data, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'EquipoTrabajo':
                    if row.has_key('Nomb._equ. Trab.'
                                   ) and row['Nomb._equ. Trab.'] not in [
                                       '', ' '
                                   ]:
                        nom = tools_lib.import_variable(
                            row, 'Nomb._equ. Trab.', 'string', ID)
                    elif row.has_key('nom._eq.tra'
                                     ) and row['nom._eq.tra'] not in ['', ' ']:
                        nom = tools_lib.import_variable(
                            row, 'nom._eq.tra', 'string', ID)

                    if nom not in ['']:
                        equipoA = class_lib.Equipo(nom)
                        equipoA.equipo_cargo = \
                            tools_lib.import_variable(row, 'cargo', 'code', ID, code_lists.equipo_cargo)
                        equipoA.equipo_emp = \
                            tools_lib.import_variable(row, 'empresa', 'string', ID)
                        equipoA.equipo_app = '-'
                        survey.plots[ID].equipo[equipoA.equipo_nom] = equipoA
                        if ID not in counter:
                            counter.append(ID)

    info_msg = "Updated the equipo table for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
def import_flora_soto_2010(survey,infile):
    """
    Function to import_modules the flora soto records into the survey

    :param survey:  A survey object into which the plot information will be added
    :param infile:  File path to the 2010 plot data
    :type survey: An instance of :class:`~model.class_lib.Survey`
    :type infile: A file path
    :return: If executed as script a file with the flora soto bosque information that can be imported in to OF Collect.
     Otherwise an updated survey object
    :rtype: :class:`~model.class_lib.Survey` / CSV File

    - **Example**  how to use as script::

        :Example usage:
        python import_flora_soto_2010.py Datos_generales_2010.csv flora_soto_caracter.csv
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        plot_counter=[]
        for row in datareader:
            # Here we should replace all empty string with None in the dictonary row
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                # As many species are in one cell we need to iterate of the cells
                flora_soto_tipo = row['tipoSotobosque']
                if flora_soto_tipo == '':
                    flora_soto_tipo = None
                else:
                    flora_soto_tipo= tools_lib.find_key(code_lists.flora_suelo_tipo, flora_soto_tipo)
                if flora_soto_tipo:
                    if ID not in plot_counter:
                        plot_counter.append(ID)
                    floraSotoA = class_lib.FloraSoto(ID, flora_soto_tipo)
                    floraSotoA.flora_soto_altura = tools_lib.import_variable(row, 'alturaSotobosque (m)', 'float', ID)
                    floraSotoA.flora_soto_altura_unit_name = "metros"
                    survey.plots[ID].flora_soto[id_generator()]= floraSotoA
                    survey.plots[ID].flora_soto_flora_soto_presencia = 1
    info_msg = "Updated the flora soto table for {nplots} plots from the file: {file}" \
        .format(nplots=plot_counter.__len__(), file=os.path.basename(infile))
    logging.info(info_msg)
    print(info_msg)
def import_regeneracion_2015(survey,species_list,infile):
    """ Function to import_modules invasores records from plots in the 2015 file format

    :param survey:  An instance of the survey class
    :param species_list: Dictonary with the invasora species
    :param infile:  The file path to the import_modules file
    """
    with open(infile, 'rb') as data:
        datareader = csv.DictReader(data, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'Regeneracion Natural':
                    if row.has_key('nombrecient_regnat') and row['nombrecient_regnat'] not in ['',' ']:
                        species = row['nombrecient_regnat'].strip()
                        index = tools_lib.find_species_scientific(species_list, species)
                        if index.__len__() > 0:
                            regeneracionA = class_lib.Regeneracion(ID, species_list[index[0]].species_code)
                            regeneracionA.regen_especie_scientific_name = species_list[index[0]].scientific_name
                            regeneracionA.regen_especie_vernacular_name = species_list[index[0]].common_name
                            if ID not in counter:
                                counter.append(ID)
                            regeneracionA.regen_subparcela_id = tools_lib.import_variable(row, 'subparcela_regnat',
                                                                                               'int', ID)
                            if row.has_key('Rumbo_regnat'):
                                regeneracionA.regen_rumbo = tools_lib.import_variable(row, 'Rumbo_regnat',
                                                                                               'int', ID)
                            if row.has_key('Rumbo'):
                                regeneracionA.regen_rumbo = tools_lib.import_variable(row, 'Rumbo',
                                                                                               'int', ID)
                            if row.has_key('Distancia_regnat'):
                                regeneracionA.regen_distancia = tools_lib.import_variable(row, 'Distancia_regnat',
                                                                                               'float', ID)
                            if row.has_key('Distancia'):
                                regeneracionA.regen_distancia = tools_lib.import_variable(row, 'Distancia',
                                                                                               'float', ID)
                            regeneracionA.regen_frec = tools_lib.import_variable(row, 'cant_regnat',
                                                                                               'int', ID)

                            regeneracionA.regen_distancia_unit_name = 'metros'
                            regeneracionA.regen_rumbo_unit_name = 'grados'
                            survey.plots[ID].regeneracion[regeneracionA.regen_especie_code] = regeneracionA
    info_msg = "Updated the regeneration table for {nplots} plots from the file: {file}"\
                    .format(nplots=counter.__len__(),file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 8
0
def import_fotos_2015(survey, infile):
    """ Function to import_modules foto data from plots in the 2015 file format

    :param survey:  An instance of the survey class
    :param infile:  The file path to the import_modules file
    """

    with open(infile, 'rb') as data:
        datareader = csv.DictReader(data, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'Fotos':
                    foto_id = row['foto']
                    # We add only a foto if it is not in the foto list of this plot
                    if foto_id not in survey.plots[ID].fotos.keys():
                        survey.plots[ID].add_foto(foto_id)
                        if ID not in counter:
                            counter.append(ID)
                    survey.plots[ID].fotos[foto_id].foto_position = 1
                    survey.plots[ID].fotos[foto_id].foto_tipo = \
                        tools_lib.import_variable(row, 'tipoFoto', 'code', ID, code_lists.foto_tipo)
                    survey.plots[ID].fotos[
                        foto_id].foto_desc = tools_lib.import_variable(
                            row, 'descr', 'string', ID)
                    survey.plots[ID].fotos[foto_id].foto_archivo = foto_id
                    if row.has_key('lat_foto'):
                        survey.plots[ID].fotos[foto_id].foto_lat = \
                            tools_lib.import_variable(row, 'lat_foto', 'float', ID)
                    elif row.has_key('Lat_foto'):
                        survey.plots[ID].fotos[foto_id].foto_lat = \
                            tools_lib.import_variable(row, 'Lat_foto', 'float', ID)
                    if row.has_key('lon_foto'):
                        survey.plots[ID].fotos[foto_id].foto_lon = \
                            tools_lib.import_variable(row, 'lon_foto', 'float', ID)
                    elif row.has_key('Lon_foto'):
                        survey.plots[ID].fotos[foto_id].foto_lon = \
                            tools_lib.import_variable(row, 'Lon_foto', 'float', ID)
                    survey.plots[ID].fotos[
                        foto_id].foto_systema_referencia = 'EPSG:4326'
    info_msg = "Updated the foto table for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
def import_fni_plots_test(survey, species_list, infile):
    """Function to import_modules plot data in the 2015 file format

       :param survey: An instance of class survey
       :param infile: The file path to the tetst plot data
       """

    # Check if survey is of class survey
    try:
        isinstance(survey, class_lib.Survey)
        print "Using survey {}".format(survey.survey_id)
    except:
        print "Survey is not of class Survey"
        sys.exit(0)

    # Check if files exits and readable
    try:
        f = open(infile, 'r')
    except IOError:
        print "Input file {} is missing or is not readable".format(infile)
        sys.exit(0)

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if ID not in counter:
                    counter.append(ID)

                #if row['name'] == 'DatosGenerales':
                survey.plots[ID].general_datos_parcela_bosque_tipo =\
                    tools_lib.import_variable(row, 'tipoDeBosq', 'code', ID, code_lists.bosque_tipo)

                survey.plots[ID].general_datos_parcela_bosque_sub_tipo =\
                    tools_lib.import_variable(row, 'subbosque', 'code', ID, code_lists.subbosque_tipo)
                print(row['subbosque'])
                print(
                    tools_lib.import_variable(row, 'subbosque', 'code', ID,
                                              code_lists.subbosque_tipo))

                survey.plots[ID].pm_departamento = \
                    tools_lib.import_variable(row, 'departament', 'code', ID, code_lists.departamento)

                date = str.split(row['fecha'], '/')
                try:
                    date.__len__() == 3
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_year = date[
                            2]
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_month = date[
                            1]
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_day = date[
                            0]
                except ValueError:
                    warn_msg = 'Cannot convert the variable fecha wit value :\"{date}\" into a date \
                                for plot {plotid}'.format(date=row['fecha'],
                                                          plotid=ID)
                    logging.warn(warn_msg)

                #if row['name'] == 'CoordenadasParcela':
                survey.plots[
                    ID].parcela_coordenadas_gps_coord_x = tools_lib.import_variable(
                        row, 'oeste', 'float', ID)
                survey.plots[
                    ID].parcela_coordenadas_gps_coord_y = tools_lib.import_variable(
                        row, 'sur', 'float', ID)
                survey.plots[
                    ID].parcela_coordenadas_gps_coord_srs = 'EPSG:4326'

                survey.plots[ID].pm_subcuenca = row['SubCuenca']

    info_msg = "Updated the plot information for {nplots} plots from the file: {file}"\
                    .format(nplots=counter.__len__(),file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 10
0
def import_distancia_2010(survey, infile):
    """
    Function to import_modules the distance records in the 2010 data format into the survey

    :param survey:  A survey object into which the plot information will be added
    :param infile:  he file path to the 2010 single tree data
    :type survey: An instance of :class:`~model.class_lib.Survey`
    :type infile: A file path
    :return: If executed as script a file with the distance information that can be imported in to OF Collect.
     Otherwise an updated survey object
    :rtype: :class:`~model.class_lib.Survey` / CSV File
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        plot_counter=[]
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if ID not in plot_counter:
                    plot_counter.append(ID)
                position = 1
                censo = 1

                # Adding the distance infomation carretera vecinal
                if row.has_key('carreteraCaminoVecinal') and row['carreteraCaminoVecinal'] not in ['', ' ']:
                    carreteraVecinal = class_lib.Distance(ID)
                    carreteraVecinal.parcela_pm_censo = censo
                    carreteraVecinal.distancia_position = position
                    carreteraVecinal.distancia_kilometros_unit_name = 'kilometros'
                    carreteraVecinal.distancia_categoria = 1
                    carreteraVecinal.distancia_camino_estado = '-'
                    carreteraVecinal.distancia_kilometros = \
                        tools_lib.import_variable(row, 'carreteraCaminoVecinal', 'int', ID)

                # Adding the distance infomation camino vecinal
                if row.has_key('caminoVecinalCaminoAcceso') and row['caminoVecinalCaminoAcceso'] not in ['', ' ']:
                    caminoVecinal = class_lib.Distance(ID)
                    caminoVecinal.parcela_pm_censo = censo
                    caminoVecinal.distancia_position = position
                    caminoVecinal.distancia_kilometros_unit_name = 'kilometros'
                    caminoVecinal.distancia_categoria = 2
                    caminoVecinal.distancia_camino_estado = '-'
                    caminoVecinal.distancia_kilometros =\
                        tools_lib.import_variable(row, 'caminoVecinalCaminoAcceso', 'int', ID)

                # Adding the distance infomation camino accesso
                if row.has_key('caminoAccesoPuntoGPS') and row['caminoAccesoPuntoGPS'] not in ['', ' ']:
                    caminoAccesso = class_lib.Distance(ID)
                    caminoAccesso.parcela_pm_censo = censo
                    caminoAccesso.distancia_position = position
                    caminoAccesso.distancia_kilometros_unit_name = 'kilometros'
                    caminoAccesso.distancia_categoria = 3
                    caminoAccesso.distancia_camino_estado = '-'
                    caminoAccesso.distancia_kilometros = \
                        tools_lib.import_variable(row, 'caminoAccesoPuntoGPS', 'int', ID)

                # Adding the distance infomation PuntoGPSCentroParcella
                if row.has_key('rumboCaminoCentroParcela') and row['rumboCaminoCentroParcela'] not in ['', ' ']:
                    puntoGPSCentroParcella = class_lib.Distance(ID)
                    puntoGPSCentroParcella.parcela_pm_censo = censo
                    puntoGPSCentroParcella.distancia_position = position
                    puntoGPSCentroParcella.distancia_categoria = 4
                    puntoGPSCentroParcella.distancia_kilometros_unit_name = 'kilometros'
                    puntoGPSCentroParcella.distancia_camino_estado = '-'
                    puntoGPSCentroParcella.rumbo_punto_gps_centro =\
                        tools_lib.import_variable(row, 'rumboCaminoCentroParcela', 'int', ID)

                    if row.has_key('puntoGPSCentroParcela') and row['puntoGPSCentroParcela'] not in ['', ' ']:
                            puntoGPSCentroParcella.distancia_kilometros = \
                                tools_lib.import_variable(row, 'puntoGPSCentroParcela', 'int', ID)

                #Adding the distance instances to the survey
                try:
                    survey.plots[ID].distances['1'] = carreteraVecinal
                except:
                    warn_msg = 'Could not find information on distance "carreteraVecinal" on plot: {plotid}.' \
                        .format( plotid=ID)
                    logging.warning(warn_msg)
                try:
                    survey.plots[ID].distances['2'] = caminoVecinal
                except:
                    warn_msg = 'Could not find information on distance "caminoVecinal" on plot: {plotid}.' \
                        .format( plotid=ID)
                    logging.warning(warn_msg)
                try:
                    survey.plots[ID].distances['3'] = caminoAccesso
                except:
                    warn_msg = 'Could not find information on distance "caminoAcceso" on plot: {plotid}.' \
                        .format(plotid=ID)
                    logging.warning(warn_msg)
                try:
                   survey.plots[ID].distances['4'] = puntoGPSCentroParcella
                except:
                    warn_msg = 'Could not find information on distance "puntoGPSCentroParcella" on plot: {plotid}.' \
                        .format( plotid=ID)
                    logging.warning(warn_msg)

        info_msg = "Updated the distance table for {nplots} plots from the file: {file}" \
            .format(nplots=plot_counter.__len__(), file=os.path.basename(infile))
        logging.info(info_msg)
        print(info_msg)
def import_fauna_2015(survey, species_list, infile):
    """
    Function to import_modules the fauna records into the survey

    :param survey: An instance of base class Survey
    :param species_list: A dictonary with all fauna species
    :param infile: The file path to the input file
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if row['name'] == 'Fauna':
                    species = ''
                    if row.has_key('especie_fauna_cientif'
                                   ) and row['especie_fauna_cientif'] not in [
                                       '', ' '
                                   ]:
                        species = row['especie_fauna_cientif'].strip()
                    if row.has_key('especie_fauna'
                                   ) and row['especie_fauna'] not in ['', ' ']:
                        species = row['especie_fauna'].strip()
                    if row.has_key('especie_fauna_nombrecientif') and row[
                            'especie_fauna_nombrecientif'] not in ['', ' ']:
                        species = row['especie_fauna_nombrecientif'].strip()
                    index = tools_lib.find_species_scientific(
                        species_list, species)
                    if index.__len__() > 0:
                        faunaA = class_lib.Fauna(
                            ID, species_list[index[0]].species_code)
                        faunaA.fauna_especie_scientific_name = species_list[
                            index[0]].scientific_name
                        faunaA.fauna_especie_vernacular_name = species_list[
                            index[0]].common_name
                        faunaA.fauna_cant = tools_lib.import_variable(
                            row, 'frec', 'float', ID)
                        faunaA.fauna_tipo_observacion = '-'

                        if 'AV' in faunaA.fauna_especies_code:
                            survey.plots[ID].fauna_aves[
                                faunaA.fauna_especies_code] = faunaA
                            if ID not in counter:
                                counter.append(ID)
                        if 'MA' in faunaA.fauna_especies_code:
                            survey.plots[ID].fauna_mamiferos[
                                faunaA.fauna_especies_code] = faunaA
                            if ID not in counter:
                                counter.append(ID)
                        if 'RE' in faunaA.fauna_especies_code:
                            survey.plots[ID].fauna_reptiles[
                                faunaA.fauna_especies_code] = faunaA
                            if ID not in counter:
                                counter.append(ID)
                        if 'AN' in faunaA.fauna_especies_code:
                            survey.plots[ID].fauna_anfibios[
                                faunaA.fauna_especies_code] = faunaA
                            if ID not in counter:
                                counter.append(ID)
                    else:
                        warnin_msg = 'Variable \"especie_fauna_cientif\" with value: \"{value}\" could not be found in the fauna species lists on plot {plotid}'\
                        .format(value=species,plotid=ID)
                        logging.warn(warnin_msg)

    info_msg = "Updated the fauna tables for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
def import_fni_trees_2010(survey, species_list, infile):
    """ Function to import_modules tree data from natural forest and plantations the 2010 file format

    :param survey:  A survey object into which the plot information will be added
    :param species_list:  A list with tree species names as exported from the Collect species list
    :param infile:  he file path to the 2010 single tree data
    :type survey: An instance of :class:`~model.class_lib.Survey`
    :type species_list: A dictionary with instances of :class:`~model.class_lib.Species`
    :type infile: A file path
    :return: If executed as script a file with the single tree information that can be imported in to OF Collect.
     Otherwise an updated survey object
    :rtype: :class:`~model.class_lib.Survey` / CSV File

    - **Example**  how to use as script::

        :Example usage:
        python import_arbol_2010.py Nativo_2010.csv arbol_especie.csv arboles_nativo_2010.csv
    """

    with open(infile, 'rb') as planilla_bn:
        datareader = csv.DictReader(planilla_bn, delimiter=',')
        plot_counter = []
        for row in datareader:
            id = row['p_muestreo_pl']
            if id in survey.plots.keys():
                print 'Processing PlotID:{:}'.format(id)
                if id not in plot_counter:
                    plot_counter.append(id)
                #TODO Check client favor solution for missing tree ids is
                no_tree_id=False
                if row['arbol'] in['' , ' ']:
                    # Set a artifical id
                    arbol_id = survey.plots[id].trees.__len__() + 1
                    no_tree_id = True
                    warn_msg = "No Tree id found for plot: {plotid} creating a new Tree id: {arbol_id}"\
                        .format(plotid=id,arbol_id=arbol_id)
                    logging.warn(warn_msg)

                else:
                    arbol_id = tools_lib.import_variable(row, 'arbol', 'int', id)
                    stem_id = tools_lib.import_variable(row, 'No vara', 'int', id)

                dap1 = tools_lib.import_variable(row, 'd1', 'int', id)
                dap2 = tools_lib.import_variable(row, 'd2', 'int', id)
                ht = tools_lib.import_variable(row, 'ht', 'int', id)

                if row.has_key('diametro'):
                    parcela = tools_lib.convert_arbol_diametro(row['diametro'])
                else:
                    parcela = 5
                arbol_unico_id = str(parcela) + '_' + str(arbol_id) + '_' + str(stem_id)

                # We add only a tree if it is not in the tree list
                if arbol_unico_id not in survey.plots[id].trees.keys():
                    survey.plots[id].add_tree(arbol_unico_id)

                survey.plots[id].trees[arbol_unico_id].arbol_id = arbol_id
                survey.plots[id].trees[arbol_unico_id].arbol_parcela = parcela
                # For bosque nativo the species is observed on the single tree level and recorded in the tree table
                if row.has_key('genero') and row.has_key('Especie'):
                    species_name = row['genero'] + ' ' + row['Especie']
                    index = tools_lib.find_species_scientific(species_list, species_name)
                    if index.__len__() > 0:
                        survey.plots[id].trees[arbol_unico_id].arbol_especie_code = \
                            species_list[index[0]].species_code
                        survey.plots[id].trees[arbol_unico_id].arbol_especie_scientific_name = \
                            species_list[index[0]].scientific_name
                        survey.plots[id].trees[arbol_unico_id].arbol_especie_vernacular_name = \
                            species_list[index[0]].common_name
                    else:
                        error_msg = "Cannot find the tree species \"{species}\" in the species list for tree {treeid} "\
                                   "on plot {plotid}". \
                            format(species=species_name, treeid=arbol_id, plotid=id)
                        logging.error(error_msg)

                # For plantations the species is a plot variable and similar for all trees
                else:
                    species_code = survey.plots[id].plantacion_plant_especie_code
                    if species_code is not None:
                        index = tools_lib.find_species_code(species_list, species_code)
                        if index.__len__() > 0:
                            survey.plots[id].trees[arbol_unico_id].arbol_especie_code = \
                                species_list[index].species_code
                            survey.plots[id].trees[arbol_unico_id].arbol_especie_scientific_name = \
                                species_list[index].scientific_name
                            survey.plots[id].trees[arbol_unico_id].arbol_especie_vernacular_name = \
                                species_list[index].common_name
                    else:
                        warn_msg = "Species code not set for tree {treeid} on plot {plotid}"\
                                .format(treeid=arbol_id, plotid=id)
                        logging.warn(warn_msg)

                #Adding the stem to the tree
                survey.plots[id].trees[arbol_unico_id].add_stem(stem_id=stem_id,dap1=dap1, dap2=dap2, ht=ht)

                #Adding the comments field
                if row.has_key('d_obser'):
                    ostr = 'd_obser'
                if row.has_key('d_observ'):
                    ostr = 'd_observ'
                if row[ostr] in ['', ' ']:
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].observacion = '-'
                else:
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].observacion = \
                        tools_lib.import_variable(row, ostr, 'string', id)
                if no_tree_id is True:
                    #Adding a comment if the tree id was generated by the script
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].observacion = \
                        survey.plots[id].trees[arbol_unico_id].stems[stem_id].observacion + 'No tree id found in the data'

                survey.plots[id].trees[arbol_unico_id].stems[stem_id].dap1_unit_name = 'centimetros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].dap2_unit_name = 'centimetros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].dap_unit_name = 'centimetros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].ht_unit_name = 'metros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].hp_unit_name = 'metros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].corteza_espesor_unit_name = ''
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].rumbo_unit_name = None
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].distancia_unit_name = 'metros'
                survey.plots[id].trees[arbol_unico_id].stems[stem_id].hc_unit_name = 'metros'

                # Single tree attribute only relevant for nature forest
                if row.has_key('diametro'):
                    bosque_nativo = False
                else:
                    bosque_nativo = True

                if bosque_nativo:
                    # TODO Estrato needs to be updated once the information how the mapping should be done is available
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].estrado = tools_lib.\
                                import_variable(row,'estrato_v','code', id, codelist=code_lists.arbol_estrato)
                    # TODO Needs to be updated once the information is available
                    #survey.plots[id].trees[arbol_unico_id].stems[stem_id].rango_edad = \
                    #    tools_lib.import_variable(row,'rango_edad','int',id)
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].rango_edad = '-'
                else:
                    #for plantations only
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].distancia = \
                        tools_lib.import_variable(row, 'dist', 'float', id)
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].rumbo = \
                        tools_lib.import_variable(row, 'rumbo', 'int', id)
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].hc = \
                        tools_lib.import_variable(row, 'hc', 'float', id)
                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].hp = \
                        tools_lib.import_variable(row, 'h_poda', 'float', id)

                    if row.has_key('forma') and  row['forma'] not in ['',' ']:
                        forma_str =str.replace(row['forma'],',','.')
                        #TODO Only one form variable can be stored in OF. We are using the first only!
                        forma = str.split(forma_str,'.')[0]
                        if forma in ['1','2','3','4','5','6']:
                                survey.plots[id].trees[arbol_unico_id].stems[stem_id].forma= forma
                        else:
                            warn_msg = 'Cannot convert the forma variable "{forma}" to a class between 1:5 for tree"' \
                                       '{treeid} on plot {plotid}'.format(forma=row['forma'],treeid=arbol_id,plotid=id)
                            logging.warning(warn_msg)

                    survey.plots[id].trees[arbol_unico_id].stems[stem_id].corteza_espesor = tools_lib.import_variable(row, 'espesor', 'float', id)

    info_msg = "Updated the tree table for {nplots} plots from the file: {file}"\
                    .format(nplots=plot_counter.__len__(),file=os.path.basename(infile))
    logging.info(info_msg)
    print(info_msg)
def import_fni_plots_2010(survey, species_list, infile):
    """This function imports the plot data in the 2010 file format and adds the information to the survey instance.

    :param survey: A survey object into which the plot information will be added
    :param species_list: A list with tree species names as exported from the Collect species list
    :param infile: The file path to the 2010 plot data
    :type survey: An instance of :class:`~model.class_lib.Survey`
    :type species_list: A dictionary with instances of :class:`~model.class_lib.Species`
    :type infile: A file path
    :return: If executed as script a file with the plot information that can be imported in to OF Collect. Otherwise an
     updated survey object
    :rtype: :class:`~model.class_lib.Survey` / CSV File

    .. warning:: The mapping for the variable 'Uso de Tierra" is unclear as the classes in OF Collect are either
        'Agricola' or 'Ganadero'. However, in the 2010 DGF dataset we often find classes like "Ganadero Agricola".
        Therefore the dict "suelo_suelo_uso_tierra" in :mod:`~src.model.code_lists` should be adapted accordingly.

    """

    # Check if survey is of class survey
    try:
        isinstance(survey, class_lib.Survey)
    except:
        print "Survey is not of class Survey"
        sys.exit(0)

    # Check if files exits and readable
    try:
        open(infile, 'r')
    except IOError:
        print "Input file is missing or is not readable"
        sys.exit(0)

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        plot_counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                # print "Processing PlotID:{}".format(ID)
                if ID not in plot_counter:
                    plot_counter.append(ID)
                survey.plots[ID].pm_censo = 1
                survey.plots[ID].pm_coord_crs = ''
                survey.plots[ID].pm_coord_x = ''
                survey.plots[ID].pm_coord_y = ''
                survey.plots[ID].pm_altitude = ''
                survey.plots[ID].pm_altitude_unit_name = 'metros'
                survey.plots[ID].pm_departamento = \
                    tools_lib.import_variable(row, 'departamento', 'code', ID, codelist=code_lists.departamento)
                survey.plots[ID].pm_cuenca = None
                survey.plots[ID].pm_subcuenca = None
                survey.plots[ID].pm_censal = None
                survey.plots[ID].general_datos_parcela_estado_1 = 1
                survey.plots[ID].general_datos_parcela_bosque_tipo = \
                    tools_lib.import_variable(row, 'tipoDeBosque', 'code', ID, codelist=code_lists.bosque_tipo)
                if survey.plots[ID].general_datos_parcela_bosque_tipo == 2:
                    # Set the nivel 3 category for all plantations to DAB > 3cm by default
                    survey.plots[ID].general_datos_parcela_estado_3 = 2

                survey.plots[ID].general_datos_parcela_bosque_sub_tipo = \
                    tools_lib.import_variable(row, 'subbosque', 'code', ID, codelist=code_lists.subbosque_tipo)

                if row['Observaciones'] in ['', ' ']:
                    survey.plots[ID].general_datos_parcela_commentario = '-'
                else:
                    survey.plots[ID].general_datos_parcela_commentario = \
                        tools_lib.import_variable(row, 'Observaciones', 'string', ID)
                date = str.split(row['fecha'], '/')
                if date.__len__() == 3:
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_year = date[
                            2]
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_month = date[
                            0]
                    survey.plots[
                        ID].general_datos_parcela_fecha_observation_day = date[
                            1]
                else:
                    error_msg = 'Cannot convert the variable \"fecha"\" with value "{date}" into a date for plot ' \
                                '{plotid}'.format(date=row['fecha'], plotid=ID)
                    logging.error(error_msg)

                survey.plots[ID].general_datos_parcela_accesibilidad = \
                    tools_lib.import_variable(row, 'facilidadProgresion', 'code', ID,
                                              codelist=code_lists.accesibilidad)
                survey.plots[ID].general_datos_parcela_propietario = \
                    tools_lib.import_variable(row, 'propietario', 'string', ID)
                survey.plots[ID].general_datos_parcela_predio = \
                    tools_lib.import_variable(row, 'predio', 'string', ID)
                survey.plots[ID].rumbo = \
                    tools_lib.import_variable(row, 'rumboCaminoCentroParcela', 'float', ID)
                survey.plots[ID].track_archivo = \
                    tools_lib.import_variable(row, 'track', 'string', ID)
                survey.plots[ID].parcela_coordenadas_gps_coord_x = \
                    tools_lib.import_variable(row, 'oeste', 'float', ID)
                survey.plots[ID].parcela_coordenadas_gps_coord_y = \
                    tools_lib.import_variable(row, 'sur', 'float', ID)
                survey.plots[
                    ID].parcela_coordenadas_gps_coord_srs = 'EPSG:4326'
                survey.plots[ID].parcela_coordenadas_gps_altidud = \
                    tools_lib.import_variable(row, 'altitud', 'int', ID)
                survey.plots[
                    ID].parcela_coordenadas_gps_altiudud_unit = 'metros'
                survey.plots[ID].relieve_relieve_ubicacion = \
                    tools_lib.import_variable(row, 'ubicación_relieve', 'code', ID,
                                              codelist=code_lists.relieve_ubicaion)
                survey.plots[ID].relieve_relieve_exposicion = \
                    tools_lib.import_variable(row, 'exposicion_relieve', 'code', ID,
                                              codelist=code_lists.relieve_exposicion)
                survey.plots[ID].relieve_relieve_pendiente = \
                    tools_lib.convert_text_to_numbers(row['pendiente'], 'mean', 'real')
                survey.plots[ID].relieve_relieve_pendiente_forma = \
                    tools_lib.import_variable(row, 'formaPendiente', 'code', ID,
                                              codelist=code_lists.relieve_pediente_forma)
                survey.plots[ID].suelo_suelo_coneat = \
                    tools_lib.import_variable(row, 'grupoConeat', 'code', ID,
                                              codelist=code_lists.suelo_suelo_coneat)
                if survey.plots[ID].suelo_suelo_coneat is None:
                    survey.plots[ID].suelo_suelo_coneat = '-'
                survey.plots[ID].suelo_suelo_uso_tierra = \
                    tools_lib.import_variable(row, 'usoTierra', 'code', ID,
                                              codelist=code_lists.suelo_suelo_uso_tierra)
                survey.plots[ID].suelo_suelo_uso_previo = \
                    tools_lib.import_variable(row, 'usoPrevio', 'code', ID,
                                              codelist=code_lists.suelo_suelo_uso_previo)
                survey.plots[ID].suelo_suelo_labranza = \
                    tools_lib.import_variable(row, 'tipoLabranza', 'code', ID,
                                              codelist=code_lists.suelo_suelo_labranza)
                survey.plots[ID].suelo_suelo_erosion_grado = \
                    tools_lib.import_variable(row, 'gradoErosion', 'code', ID,
                                              codelist=code_lists.suelo_suelo_erosion_grado)
                survey.plots[ID].suelo_suelo_erosion_tipo = \
                    tools_lib.import_variable(row, 'tipoErosion', 'code', ID,
                                              codelist=code_lists.suelo_suelo_erosion_tipo)
                survey.plots[ID].suelo_suelo_profundidad_horizonte = \
                    tools_lib.import_variable(row, 'profundidadPrimerHorizonte', 'code', ID,
                                              codelist=code_lists.suelo_suelo_profundidad_horizonte)
                survey.plots[ID].suelo_suelo_profundidad_mantillo = \
                    tools_lib.import_variable(row, 'profundidadMantillo', 'code', ID,
                                              codelist=code_lists.suelo_suelo_profundidad_humus_y_mantillo)
                survey.plots[ID].suelo_suelo_profundidad_humus = \
                    tools_lib.import_variable(row, 'profundidadHumus', 'code', ID,
                                              codelist=code_lists.suelo_suelo_profundidad_humus_y_mantillo)
                survey.plots[ID].suelo_suelo_color = \
                    tools_lib.import_variable(row, 'color', 'code', ID,
                                              codelist=code_lists.suelo_suelo_color)
                survey.plots[ID].suelo_suelo_textura = \
                    tools_lib.import_variable(row, 'textura', 'code', ID
                                              , codelist=code_lists.suelo_suelo_textura)
                survey.plots[ID].suelo_suelo_estructura = \
                    tools_lib.import_variable(row, 'estructura_suelo', 'code', ID
                                              , codelist=code_lists.suelo_suelo_estructura)
                survey.plots[ID].suelo_suelo_drenaje = \
                    tools_lib.import_variable(row, 'drenaje', 'code', ID,
                                              codelist=code_lists.suelo_suelo_drenaje)
                survey.plots[ID].suelo_suelo_infiltracion = \
                    tools_lib.import_variable(row, 'infiltracion', 'code', ID,
                                              codelist=code_lists.suelo_suelo_infiltracion)
                survey.plots[ID].suelo_suelo_impedimento = \
                    tools_lib.import_variable(row, 'impedimento', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].suelo_suelo_olor = \
                    tools_lib.import_variable(row, 'olor', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].suelo_suelo_humedad = \
                    tools_lib.import_variable(row, 'humedad', 'code', ID,
                                              codelist=code_lists.suelo_suelo_humedad)
                survey.plots[ID].suelo_suelo_pedregosidad = \
                    tools_lib.convert_text_to_numbers(row['pedregosidad'], 'mean', 'integer')
                survey.plots[
                    ID].suelo_suelo_pedregosidad_unit_name = 'porciento'
                survey.plots[ID].suelo_suelo_rocosidad = \
                    tools_lib.convert_text_to_numbers(row['rocosidad'], 'mean', 'integer')
                survey.plots[ID].suelo_suelo_rocosidad_unit_name = 'porciento'
                survey.plots[ID].suelo_suelo_micorrizas = \
                    tools_lib.import_variable(row, 'micorrizas', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].suelo_suelo_fauna = \
                    tools_lib.import_variable(row, 'faunaSuelo', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].suelo_suelo_raices = \
                    tools_lib.import_variable(row, 'raices', 'code', ID,
                                              codelist=code_lists.suelo_suelo_raices)
                survey.plots[ID].cobertura_vegetal_cobertura_copas = \
                    tools_lib.convert_cobertura_copas(
                        tools_lib.convert_text_to_numbers(row['gradoCoberturaCopas'], 'mean', 'real'))

                survey.plots[ID].cobertura_vegetal_cobertura_sotobosque = \
                    tools_lib.convert_cobertura_copas(
                        tools_lib.convert_text_to_numbers(row['gradoSotobosque'], 'mean', 'real'))

                survey.plots[ID].cobertura_vegetal_cobertura_herbacea = \
                    tools_lib.convert_cobertura_copas(
                        tools_lib.convert_text_to_numbers(row['coberturaHerbacea'], 'mean', 'real'))

                survey.plots[ID].cobertura_vegetal_cobertura_residuos_plantas = \
                    tools_lib.convert_cobertura_residuos(
                        tools_lib.convert_text_to_numbers(row['coberturaResiduosPlantas'], 'mean', 'real'))

                survey.plots[ID].cobertura_vegetal_cobertura_residuos_cultivos = \
                    tools_lib.convert_cobertura_residuos(
                        tools_lib.convert_text_to_numbers(row['coberturaResiduosCultivos'], 'mean', 'real'))
                if row['tipoSotobosque'] == '':
                    survey.plots[ID].flora_soto_flora_soto_presencia = 2
                else:
                    survey.plots[ID].flora_soto_flora_soto_presencia = 1

                survey.plots[ID].agua_agua_caudal = \
                    tools_lib.import_variable(row, 'tipoCaudal', 'code', ID,
                                              codelist=code_lists.agua_agua_caudal)
                survey.plots[ID].agua_agua_distancia = \
                    tools_lib.convert_text_to_numbers(row['distancia_agua'], 'mean', 'integer')
                survey.plots[ID].agua_agua_distancia_unit_name = 'metros'

                survey.plots[ID].agua_agua_nombre = \
                    tools_lib.import_variable(row,'Nomb_afluente','string',ID)
                survey.plots[ID].agua_agua_manejo = \
                    tools_lib.import_variable(row, 'manejo', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].agua_agua_frec = \
                    tools_lib.import_variable(row, 'frecuencia_caudal', 'code', ID,
                                              codelist=code_lists.agua_agua_frec)
                if survey.plots[ID].agua_agua_frec is not None:
                    survey.plots[ID].agua_agua_presencia = 1
                else:
                    survey.plots[ID].agua_agua_presencia = 2

                survey.plots[ID].agua_agua_acuicultura = \
                    tools_lib.import_variable(row, 'acuacultura', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].agua_agua_contaminacion = \
                    tools_lib.import_variable(row, 'gradoContaminacion', 'code', ID,
                                              codelist=code_lists.agua_agua_contaminacion)
                survey.plots[ID].ambiental_ambiental_potabilidad = \
                    tools_lib.import_variable(row, 'pobreCalidadAgua', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ambiental_ambiental_polucion = \
                    tools_lib.import_variable(row, 'polucionAire', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ambiental_ambiental_fertalidad = \
                    tools_lib.import_variable(row, 'perdidaFertilidad', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ambiental_ambiental_invasion = \
                    tools_lib.import_variable(row, 'invasionEspecies', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ambiental_ambiental_pesticida = \
                    tools_lib.import_variable(row, 'presenciaPesticidas', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].fuego_fuego_evidencia = \
                    tools_lib.import_variable(row, 'evidenciaFuego', 'code', ID,
                                              codelist=code_lists.fuego_fuego_evidencias)
                survey.plots[ID].fuego_fuego_tipo = \
                    tools_lib.import_variable(row, 'tipoFuego', 'code', ID,
                                              codelist=code_lists.fuego_fuego_tipo)
                survey.plots[ID].fuego_fuego_proposito = \
                    tools_lib.import_variable(row, 'propositoFuego', 'code', ID,
                                              codelist=code_lists.fuego_fuego_proposito)

                # For plantaciones set the species code
                if survey.plots[ID].general_datos_parcela_bosque_tipo == 2:
                    survey.plots[ID].genero = row['genero'].strip()
                    especies = row['especie_plantacion'].strip()
                    plant_especies = survey.plots[ID].genero + ' ' + especies
                    index = tools_lib.find_species_scientific(
                        species_list, plant_especies)
                    try:
                        if index.__len__() > 0:
                            survey.plots[ID].plantacion_plant_especie_code = \
                                species_list[index[0]].species_code
                            survey.plots[ID].plantacion_plant_especie_scientific_name = \
                                species_list[index[0]].scientific_name
                            survey.plots[ID].plantacion_plant_especie_vernacular_name = \
                                species_list[index[0]].common_name
                        else:
                            error_msg = "Could not find the species \"{species}\" in the tree species code list" \
                                        "for plot {plotid}".format(species=plant_especies, plotid=ID)
                            logging.error(error_msg)
                    except ValueError:
                        error_msg = "Could not find the species \"{species}\" in the tree species code list" \
                                    "for plot{plotid}".format(species=plant_especies, plotid=ID)
                        logging.error(error_msg)

                survey.plots[ID].plantacion_plant_edad = \
                    tools_lib.import_variable(row,'edad','code',ID,codelist=code_lists.plantacion_edad)
                survey.plots[ID].plantacion_plant_raleo = \
                    tools_lib.import_variable(row, 'raleo', 'code', ID,
                                              codelist=code_lists.plantacion_raleo)
                survey.plots[ID].plantacion_plant_poda = \
                    tools_lib.import_variable(row, 'tienePoda', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].plantacion_plant_poda_altura = \
                    tools_lib.import_variable(row, 'alturaPoda', 'float', ID)
                survey.plots[
                    ID].plantacion_plant_poda_altura_unit_name = 'metros'
                survey.plots[ID].plantacion_plant_regular = \
                    tools_lib.import_variable(row,'parcelaRegular','code',ID,code_lists.si_no)
                survey.plots[ID].plantacion_plant_dist_fila = \
                    tools_lib.convert_text_to_numbers(row['distanciaFila'], 'mean', 'real')
                survey.plots[
                    ID].plantacion_plant_dist_fila_unit_name = 'metros'
                survey.plots[ID].plantacion_plant_dist_entrefila = \
                    tools_lib.convert_text_to_numbers(row['distanciaEntreFila'], 'mean', 'real')
                survey.plots[
                    ID].plantacion_plant_dist_entrefila_unit_name = 'metros'
                survey.plots[
                    ID].plantacion_plant_dist_silvopast_unit_name = 'metros'
                survey.plots[ID].plantacion_plant_adaptacion = \
                    tools_lib.import_variable(row, 'adaptacionEspecie', 'code', ID,
                                              codelist=code_lists.plantacion_adaptation)
                survey.plots[ID].plantacion_plant_regimen = \
                    tools_lib.import_variable(row, 'regimen', 'code', ID,
                                              codelist=code_lists.plantacion_regimen)
                survey.plots[ID].plantacion_plant_estado = \
                    tools_lib.import_variable(row, 'estadoGeneral', 'code', ID,
                                              codelist=code_lists.plantacion_estado)
                survey.plots[ID].forestacion_forest_origen = \
                    tools_lib.import_variable(row, 'origenPlantacion', 'code', ID,
                                              codelist=code_lists.forestacion_forest_origen)
                survey.plots[ID].forestacion_forest_estructura = \
                    tools_lib.import_variable(row, 'estructura_forestacion', 'code', ID
                                              , codelist=code_lists.forestacion_forest_estructura)
                survey.plots[ID].forestacion_forest_propiedad = \
                    tools_lib.import_variable(row, 'propiedadTierra', 'code', ID,
                                              codelist=code_lists.forestacion_forest_propiedad)
                survey.plots[ID].forestacion_forest_plan_manejo = \
                    tools_lib.import_variable(row, 'planManejo', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].forestacion_forest_intervencion = \
                    tools_lib.import_variable(row, 'gradoIntervencion', 'code', ID,
                                              codelist=code_lists.human_intervention_degree)
                survey.plots[ID].forestacion_forest_madera_destino_1 = \
                    tools_lib.import_variable(row, 'destinoMadera', 'code', ID,
                                              codelist=code_lists.forestacion_forest_madera_destino)
                survey.plots[ID].forestacion_forest_silvicultura = \
                    tools_lib.import_variable(row, 'maFalTrueeejoTrueilvicultural', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].forestacion_forest_tecnologia = \
                    tools_lib.import_variable(row, 'tecnologiaExplotacion', 'code', ID,
                                              codelist=code_lists.forestacion_forest_tecnologia)

                tmp = tools_lib.convert_ntfp_gando_tipo(row['tipoGanado'])
                if tmp.__len__() == 1:
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[0])
                if tmp.__len__() == 2:
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[0])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_2 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[1])
                if tmp.__len__() == 3:
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[0])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_2 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[1])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_3 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[2])
                if tmp.__len__() == 4:
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[0])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_2 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[1])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_3 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[2])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_4 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[3])
                if tmp.__len__() == 5:
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[0])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_2 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[1])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_3 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[2])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_4 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[3])
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_5 = \
                        tools_lib.find_key(code_lists.ntfp_ntfp_ganado_tipo, tmp[4])

                survey.plots[ID].ntfp_ntfp_pastoreo_intens = \
                    tools_lib.import_variable(row, 'intensidadPastoreo', 'code', ID,
                                              codelist=code_lists.ntfp_ntfp_pastoreo_intens)
                survey.plots[ID].ntfp_ntfp_prod_cultivo = \
                    tools_lib.import_variable(row, 'sistemasProduccion', 'code', ID,
                                              codelist=code_lists.ntfp_ntfp_prod_cultivo)
                survey.plots[ID].ntfp_ntfp_prod_apicola = \
                    tools_lib.import_variable(row, 'produccionApicola', 'code', ID, codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_sombra = \
                    tools_lib.import_variable(row, 'sombra', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_caza_pesca = \
                    tools_lib.import_variable(row, 'actividadesCasaPesca', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_rompe_vientos = \
                    tools_lib.import_variable(row, 'rompeVientos', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_recreacion = \
                    tools_lib.import_variable(row, 'actividadesRecreacion', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_hongos = \
                    tools_lib.import_variable(row, 'recoleccionHongos', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_semillas = \
                    tools_lib.import_variable(row, 'obtencionSemillas', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_cientificos = \
                    tools_lib.import_variable(row, 'estudiosCientificos', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_aceites = \
                    tools_lib.import_variable(row, 'aceitesEsenciales', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].ntfp_ntfp_carbono = \
                    tools_lib.import_variable(row, 'fijacionCarbono', 'code', ID,
                                              codelist=code_lists.si_no)
                survey.plots[ID].san_rumbo_unit_name = 'grados'

    info_msg = "Updated the plot information for {nplots} plots from the file: {file}" \
        .format(nplots=plot_counter.__len__(), file=os.path.basename(infile))
    logging.info(info_msg)
    print(info_msg)
Esempio n. 14
0
def import_distanca_2015(survey, infile):
    """
    Function to import_modules the distance records into the survey

    :param survey: An instance of base class Survey
    :param infile: The file path to the input file
    """

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                position = 1
                censo = 1
                if row['name'] == 'Distancias':
                    # Adding the distance infomation carretera vecinal
                    if row.has_key('carreteraCaminoVecinal'
                                   ) and row['carreteraCaminoVecinal'] not in [
                                       '', ' '
                                   ]:
                        carreteraVecinal = class_lib.Distance(ID)
                        carreteraVecinal.parcela_pm_censo = censo
                        carreteraVecinal.distancia_position = position
                        carreteraVecinal.distancia_kilometros_unit_name = 'kilometros'
                        carreteraVecinal.distancia_categoria = 1
                        carreteraVecinal.distancia_camino_estado = '-'
                        if ID not in counter:
                            counter.append(ID)
                        carreteraVecinal.distancia_kilometros = \
                            tools_lib.import_variable(row, 'carreteraCaminoVecinal', 'float', ID)

                    # Adding the distance infomation camino vecinal
                    if row.has_key('caminoVecinalCaminoAcceso') and row[
                            'caminoVecinalCaminoAcceso'] not in ['', ' ']:
                        caminoVecinal = class_lib.Distance(ID)
                        caminoVecinal.parcela_pm_censo = censo
                        caminoVecinal.distancia_position = position
                        caminoVecinal.distancia_kilometros_unit_name = 'kilometros'
                        caminoVecinal.distancia_categoria = 2
                        caminoVecinal.distancia_camino_estado = '-'
                        if ID not in counter:
                            counter.append(ID)
                        caminoVecinal.distancia_kilometros =\
                            tools_lib.import_variable(row, 'caminoVecinalCaminoAcceso', 'float', ID)

                # Adding the distance infomation camino accesso
                    if row.has_key('caminoAccesoPuntoGPS'
                                   ) and row['caminoAccesoPuntoGPS'] not in [
                                       '', ' '
                                   ]:
                        caminoAccesso = class_lib.Distance(ID)
                        caminoAccesso.parcela_pm_censo = censo
                        caminoAccesso.distancia_position = position
                        caminoAccesso.distancia_kilometros_unit_name = 'kilometros'
                        caminoAccesso.distancia_categoria = 3
                        caminoAccesso.distancia_camino_estado = '-'
                        if ID not in counter:
                            counter.append(ID)
                        caminoAccesso.distancia_kilometros = \
                            tools_lib.import_variable(row, 'caminoAccesoPuntoGPS', 'float', ID)

                    # Adding the distance infomation rumboCaminoCentroParcela
                    if row.has_key('rumboCaminoCentroParcela') and row[
                            'rumboCaminoCentroParcela'] not in ['', ' ']:
                        puntoGPSCentroParcella = class_lib.Distance(ID)
                        puntoGPSCentroParcella.parcela_pm_censo = censo
                        puntoGPSCentroParcella.distancia_position = position
                        puntoGPSCentroParcella.distancia_categoria = 4
                        puntoGPSCentroParcella.distancia_kilometros_unit_name = 'kilometros'
                        puntoGPSCentroParcella.distancia_camino_estado = '-'
                        if ID not in counter:
                            counter.append(ID)
                        puntoGPSCentroParcella.rumbo_punto_gps_centro = \
                            tools_lib.import_variable(row, 'rumboCaminoCentroParcela', 'int', ID)

                    # Adding the distance infomation PuntoGPSCentroParcella
                    if row.has_key('puntoGPSCentroParcela'
                                   ) and row['puntoGPSCentroParcela'] not in [
                                       '', ' '
                                   ]:
                        puntoGPSCentroParcella.distancia_kilometros =\
                            tools_lib.import_variable(row, 'puntoGPSCentroParcela', 'float', ID)

                    # Adding the distance instances to the survey
                    try:
                        survey.plots[ID].distances['1'] = carreteraVecinal
                    except:
                        warn_msg = 'Could not find information on distance "carreteraVecinal" on plot: {plotid}.' \
                                    .format(plotid=ID)
                        logging.warning(warn_msg)
                    try:
                        survey.plots[ID].distances['2'] = caminoVecinal
                    except:
                        warn_msg = 'Could not find information on distance "caminoVecinal" on plot: {plotid}.' \
                                    .format(plotid=ID)
                        logging.warning(warn_msg)
                    try:
                        survey.plots[ID].distances['3'] = caminoAccesso
                    except:
                        warn_msg = 'Could not find information on distance "caminoAcceso" on plot: {plotid}.' \
                                  .format(plotid=ID)
                        logging.warning(warn_msg)
                    try:
                        survey.plots[ID].distances[
                            '4'] = puntoGPSCentroParcella
                    except:
                        warn_msg = 'Could not find information on distance "puntoGPSCentroParcella" on plot: {plotid}.' \
                                 .format(plotid=ID)
                        logging.warning(warn_msg)

    info_msg = "Updated the distance table for {nplots} plots from the file: {file}" \
                  .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
Esempio n. 15
0
def import_fni_trees_test(survey, species_list, infile):
    """ Function to import_modules single tree data in the 2015 file format

    :param survey:  An instance of the survey class
    :param species_list:  An instance of class species
    :param infile:  The file path to the import_modules file
    """

    with open(infile, 'rb') as planilla_bn:
        datareader = csv.DictReader(planilla_bn, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                #print 'Processing PlotID:{:}'.format(ID)
                if ID not in counter:
                    counter.append(ID)
                #TODO Check client favor solution for missin tree ids is

                #if row['tipoDeBosq'] in ['Bosque Nativo']:
                try:
                    arbol_id = "%d" % float(row['numArbol'])
                    print(arbol_id)
                except ValueError:
                    error_msg = " Cannot create a tree id from \"{numArbol}\" for plot {plotid}"\
                            .format(numArbol=row['numArbol'],plotid=ID)
                    logging.error(error_msg)

                # We add only a tree if it is not in the tree list otherwise we assume that this is a stem of the same tree
                if arbol_id not in survey.plots[ID].trees.keys():
                    print("not in")
                    survey.plots[ID].add_tree(arbol_id)

                # We get stem id from row
                stem_id = row['No vara']

                # Add stems to the tree
                dap1 = tools_lib.import_variable(row, 'dap1', 'float', ID)

                dap2 = tools_lib.import_variable(row, 'dap2', 'float', ID)

                ht = tools_lib.import_variable(row,
                                               'ht',
                                               'float',
                                               ID,
                                               treeid=arbol_id)
                survey.plots[ID].trees[arbol_id].add_stem(stem_id=stem_id,
                                                          dap1=dap1,
                                                          dap2=dap2,
                                                          ht=ht)

                print 'Stem count:{:}'.format(
                    survey.plots[ID].trees[arbol_id].stem_count())

                survey.plots[ID].trees[arbol_id].arbol_id = arbol_id

                #Import the attributes for natural forest
                #if row['tipoDeBosq']== "Bosque Nativo":
                # Check Species Name for natural forests
                if row.has_key('nombreCientifico_FloraNativa'):
                    index = tools_lib.find_species_scientific(
                        species_list, row['nombreCientifico_FloraNativa'])
                    warn_msg = "Cannot find the tree species \"{species}\" in the species list for tree {treeid} on plot {plotid}". \
                        format(species=row['nombreCientifico_FloraNativa'], treeid=arbol_id, plotid=ID)
                    try:
                        if index.__len__() > 0:
                            survey.plots[ID].trees[arbol_id].arbol_especie_code = \
                                species_list[index[0]].species_code
                            survey.plots[ID].trees[arbol_id].arbol_especie_scientific_name = \
                                species_list[index[0]].scientific_name
                            survey.plots[ID].trees[arbol_id].arbol_especie_vernacular_name = \
                                species_list[index[0]].common_name
                        else:
                            survey.plots[ID].trees[
                                arbol_id].arbol_especie_code = '-'
                            logging.warn(warn_msg)
                    except ValueError:
                        logging.warn(warn_msg)

                survey.plots[ID].trees[arbol_id].stems[stem_id].estrado = \
                        tools_lib.import_variable(row, 'estrato', 'code', ID,
                                                  codelist=code_lists.arbol_estrato,
                                                  treeid=arbol_id)

                #Import the attribute for plantaciones

                survey.plots[ID].trees[arbol_id].stems[
                    stem_id].dap1_unit_name = 'centimetros'
                survey.plots[ID].trees[arbol_id].stems[
                    stem_id].dap2_unit_name = 'centimetros'
                survey.plots[ID].trees[arbol_id].stems[
                    stem_id].dap_unit_name = 'centimetros'
                survey.plots[ID].trees[arbol_id].stems[
                    stem_id].ht_unit_name = 'metros'
                survey.plots[ID].trees[arbol_id].arbol_parcela = 5

    info_msg = "Updated the tree table for {nplots} plots from the file: {file}" \
        .format(nplots=counter.__len__(), file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)
def import_fni_plots_2015(survey, species_list, infile):
    """Function to import_modules plot data in the 2015 file format

       :param survey: An instance of class survey
       :param infile: The file path to the 2015 plot data
       """

    # Check if survey is of class survey
    try:
        isinstance(survey, class_lib.Survey)
        print "Using survey {}".format(survey.survey_id)
    except:
        print "Survey is not of class Survey"
        sys.exit(0)

    # Check if files exits and readable
    try:
        f = open(infile, 'r')
    except IOError:
        print "Input file {} is missing or is not readable".format(infile)
        sys.exit(0)

    with open(infile, 'rb') as csvfile:
        datareader = csv.DictReader(csvfile, delimiter=',')
        counter = []
        for row in datareader:
            ID = row['nombre_pm']
            if ID in survey.plots.keys():
                if ID not in counter:
                    counter.append(ID)
                survey.plots[ID].pm_altitude = ''
                survey.plots[ID].pm_altitude_unit_name = 'metros'
                survey.plots[ID].general_datos_parcela_estado_1 = 1

                if row['name'] == 'Punto':
                    survey.plots[ID].pm_coord_crs = ''
                    survey.plots[ID].pm_coord_y = tools_lib.import_variable(
                        row, 'lat_pm', 'float', ID)
                    survey.plots[ID].pm_coord_x = tools_lib.import_variable(
                        row, 'lon_pm', 'float', ID)

                if row['name'] == 'DatosGenerales':
                    survey.plots[ID].general_datos_parcela_bosque_tipo =\
                        tools_lib.import_variable(row, 'tipoDeBosque', 'code', ID, code_lists.bosque_tipo)
                    if survey.plots[ID].general_datos_parcela_bosque_tipo == 2:
                        #Set the nivel 3 catagory for all plantations to DAB > 3cm by default
                        survey.plots[ID].general_datos_parcela_estado_3 = 2
                    survey.plots[ID].general_datos_parcela_bosque_sub_tipo =\
                        tools_lib.import_variable(row, 'subbosque', 'code', ID, code_lists.subbosque_tipo)

                    survey.plots[ID].general_datos_parcela_accesibilidad = \
                        tools_lib.import_variable(row, 'facilidadProgresion', 'code', ID, code_lists.accesibilidad)

                    survey.plots[ID].pm_departamento = \
                        tools_lib.import_variable(row, 'departamento', 'code', ID, code_lists.departamento)

                    survey.plots[ID].general_datos_parcela_propietario = \
                        tools_lib.import_variable(row, 'propietario', 'string', ID)

                    survey.plots[ID].general_datos_parcela_predio = \
                        tools_lib.import_variable(row, 'predio', 'string', ID)

                    date = str.split(row['fecha'], '/')
                    try:
                        date.__len__() == 3
                        survey.plots[
                            ID].general_datos_parcela_fecha_observation_year = date[
                                2]
                        survey.plots[
                            ID].general_datos_parcela_fecha_observation_month = date[
                                0]
                        survey.plots[
                            ID].general_datos_parcela_fecha_observation_day = date[
                                1]
                    except ValueError:
                        warn_msg = 'Cannot convert the variable fecha wit value :\"{date}\" into a date \
                                    for plot {plotid}'.format(
                            date=row['fecha'], plotid=ID)
                        logging.warn(warn_msg)
                #Nativo
                if row['name'] == 'Observaciones' and row.has_key(
                        'Observaciones'):
                    if row['Observaciones'] in ['', ' ']:
                        survey.plots[
                            ID].general_datos_parcela_commentario = '-'
                    else:
                        survey.plots[ID].general_datos_parcela_commentario = \
                            tools_lib.import_variable(row, 'Observaciones', 'string', ID)
                #Plantado
                if row['name'] == 'Observaciones' and row.has_key(
                        'observacion'):
                    if row['observacion'] in ['', ' ']:
                        survey.plots[
                            ID].general_datos_parcela_commentario = '-'
                    else:
                        survey.plots[ID].general_datos_parcela_commentario = \
                            tools_lib.import_variable(row, 'observacion', 'string', ID)

                # If there is no observation record found in the database set '-'
                if survey.plots[ID].general_datos_parcela_commentario is None:
                    survey.plots[ID].general_datos_parcela_commentario = '-'

                if row['name'] == 'Distancias':
                    survey.plots[ID].track_archivo = row['track']

                if row['name'] == 'CoordenadasParcela':
                    survey.plots[
                        ID].parcela_coordenadas_gps_coord_x = tools_lib.import_variable(
                            row, 'oeste', 'float', ID)
                    survey.plots[
                        ID].parcela_coordenadas_gps_coord_y = tools_lib.import_variable(
                            row, 'sur', 'float', ID)
                    survey.plots[
                        ID].parcela_coordenadas_gps_altidud = tools_lib.import_variable(
                            row, 'altitud', 'int', ID)
                    survey.plots[
                        ID].parcela_coordenadas_gps_altiudud_unit = 'metros'
                    survey.plots[
                        ID].parcela_coordenadas_gps_coord_srs = 'EPSG:4326'

                if row['name'] == 'Agua':
                    survey.plots[ID].agua_agua_caudal = \
                        tools_lib.import_variable(row, 'tipoCaudal', 'code', ID, code_lists.agua_agua_caudal)
                    #If there is a tipocaudal code then there is water
                    if survey.plots[ID].agua_agua_caudal:
                        survey.plots[ID].agua_agua_presencia = 1
                    if row.has_key('manejo'):
                        survey.plots[ID].agua_agua_manejo = \
                            tools_lib.import_variable(row, 'manejo', 'code', ID, code_lists.si_no)
                    else:
                        survey.plots[ID].agua_agua_manejo = \
                            tools_lib.import_variable(row, 'Manejo', 'code', ID, code_lists.si_no)

                    if row.has_key('frecuencia_caudal'):
                        survey.plots[ID].agua_agua_frec = \
                            tools_lib.import_variable(row, 'frecuencia_caudal', 'code', ID, code_lists.agua_agua_frec)
                    else:
                        survey.plots[ID].agua_agua_frec = \
                            tools_lib.import_variable(row, 'frecuencia', 'code', ID, code_lists.agua_agua_frec)

                    if row.has_key('acuacultura'):
                        survey.plots[ID].agua_agua_acuicultura =\
                            tools_lib.import_variable(row, 'acuacultura', 'code', ID, code_lists.si_no)
                    else:
                        survey.plots[ID].agua_agua_acuicultura =\
                            tools_lib.import_variable(row, 'Acuacultura', 'code', ID, code_lists.si_no)

                    survey.plots[ID].agua_agua_contaminacion = \
                        tools_lib.import_variable(row, 'gradoContaminacion', 'code', ID, code_lists.agua_agua_contaminacion)

                if row['name'] == 'NombreAfluentes':
                    if row.has_key('nom_afluente'):
                        survey.plots[ID].agua_agua_nombre =\
                            tools_lib.import_variable(row, 'nom_afluente', 'string', ID)
                    else:
                        survey.plots[ID].agua_agua_nombre = \
                            tools_lib.import_variable(row, 'Nomb_afluente', 'string', ID)

                    survey.plots[ID].agua_agua_distancia_unit_name = 'metros'

                    survey.plots[ID].agua_agua_distancia =\
                        tools_lib.import_variable(row, 'distancia_agua', 'int', ID)

                if row['name'] == 'Relieve':
                    survey.plots[ID].relieve_relieve_ubicacion = \
                        tools_lib.import_variable(row, 'ubicación_relieve', 'code', ID, code_lists.relieve_ubicaion)
                    survey.plots[ID].relieve_relieve_exposicion = \
                        tools_lib.import_variable(row, 'exposicion_relieve', 'code', ID, code_lists.relieve_exposicion)
                    survey.plots[ID].relieve_relieve_pendiente = \
                        tools_lib.import_variable(row, 'pendiente', 'float', ID)
                    survey.plots[ID].relieve_relieve_pendiente_forma = \
                        tools_lib.import_variable(row, 'formaPendiente', 'code', ID, code_lists.relieve_pediente_forma)

                if row['name'] == 'Suelo':
                    survey.plots[ID].suelo_suelo_coneat = \
                        tools_lib.import_variable(row, 'grupoConeat', 'code', ID, code_lists.suelo_suelo_coneat)
                    survey.plots[ID].suelo_suelo_uso_tierra = \
                        tools_lib.import_variable(row, 'usoTierra', 'code', ID, code_lists.suelo_suelo_uso_tierra)
                    survey.plots[ID].suelo_suelo_uso_previo = \
                        tools_lib.import_variable(row, 'usoPrevio', 'code', ID, code_lists.suelo_suelo_uso_previo)
                    survey.plots[ID].suelo_suelo_labranza =\
                        tools_lib.import_variable(row, 'tipoLabranza', 'code', ID, code_lists.suelo_suelo_labranza)
                    survey.plots[ID].suelo_suelo_erosion_grado = \
                        tools_lib.import_variable(row, 'gradoErosion', 'code', ID, code_lists.suelo_suelo_erosion_grado)
                    survey.plots[ID].suelo_suelo_erosion_tipo = \
                        tools_lib.import_variable(row, 'tipoErosion', 'code', ID, code_lists.suelo_suelo_erosion_tipo)
                    survey.plots[ID].suelo_suelo_profundidad_horizonte = \
                        tools_lib.import_variable(row, 'profundidadPrimerHorizonte', 'code', ID, code_lists.suelo_suelo_profundidad_horizonte)
                    survey.plots[ID].suelo_suelo_profundidad_mantillo =  \
                        tools_lib.import_variable(row, 'profundidadMantillo', 'code', ID, code_lists.suelo_suelo_profundidad_humus_y_mantillo)
                    survey.plots[ID].suelo_suelo_profundidad_humus = \
                        tools_lib.import_variable(row, 'profundidadHumus', 'code', ID, code_lists.suelo_suelo_profundidad_humus_y_mantillo)
                    survey.plots[ID].suelo_suelo_color = \
                        tools_lib.import_variable(row, 'color', 'code', ID, code_lists.suelo_suelo_color)
                    survey.plots[ID].suelo_suelo_textura = \
                        tools_lib.import_variable(row, 'textura', 'code', ID, code_lists.suelo_suelo_textura)
                    survey.plots[ID].suelo_suelo_estructura = \
                        tools_lib.import_variable(row, 'estructura_suelo', 'code', ID, code_lists.suelo_suelo_estructura)
                    survey.plots[ID].suelo_suelo_drenaje = \
                        tools_lib.import_variable(row, 'drenaje', 'code', ID, code_lists.suelo_suelo_drenaje)
                    survey.plots[ID].suelo_suelo_infiltracion = \
                        tools_lib.import_variable(row, 'infiltracion', 'code', ID, code_lists.suelo_suelo_infiltracion)
                    survey.plots[ID].suelo_suelo_impedimento = \
                        tools_lib.import_variable(row, 'impedimento', 'code', ID, code_lists.si_no)
                    survey.plots[ID].suelo_suelo_olor = \
                        tools_lib.import_variable(row, 'olor', 'code', ID, code_lists.si_no)
                    survey.plots[ID].suelo_suelo_humedad = \
                        tools_lib.import_variable(row, 'humedad', 'code', ID, code_lists.suelo_suelo_humedad)
                    survey.plots[ID].suelo_suelo_pedregosidad = \
                        tools_lib.import_variable(row, 'pedregosidad', 'int', ID)
                    survey.plots[ID].suelo_suelo_rocosidad = \
                        tools_lib.import_variable(row, 'rocosidad', 'int', ID)
                    survey.plots[
                        ID].suelo_suelo_pedregosidad_unit_name = 'porciento'
                    survey.plots[
                        ID].suelo_suelo_rocosidad_unit_name = 'porciento'
                    survey.plots[ID].suelo_suelo_micorrizas = \
                        tools_lib.import_variable(row, 'micorrizas', 'code', ID, code_lists.si_no)
                    survey.plots[ID].suelo_suelo_fauna = \
                        tools_lib.import_variable(row, 'faunaSuelo', 'code', ID, code_lists.si_no)
                    survey.plots[ID].suelo_suelo_raices = \
                        tools_lib.import_variable(row, 'raices', 'code', ID, code_lists.suelo_suelo_raices)

                if row['name'] == 'CoberturaVegetal':
                    survey.plots[ID].cobertura_vegetal_cobertura_copas = \
                        tools_lib.import_variable(row, 'gradoCoberturaCopas', 'code', 'ID', code_lists.cobertura_grado)
                    survey.plots[ID].cobertura_vegetal_cobertura_sotobosque = \
                        tools_lib.import_variable(row, 'gradoSotobosque', 'code', ID, code_lists.cobertura_grado)
                    if survey.plots[
                            ID].cobertura_vegetal_cobertura_sotobosque > 1:
                        survey.plots[ID].flora_soto_flora_soto_presencia = 1
                    else:
                        survey.plots[ID].flora_soto_flora_soto_presencia = 2
                    if row.has_key('coberturaHerbacea'):
                        survey.plots[ID].cobertura_vegetal_cobertura_herbacea = \
                        tools_lib.import_variable(row, 'coberturaHerbacea', 'code', ID, code_lists.cobertura_grado)
                    else:
                        survey.plots[ID].cobertura_vegetal_cobertura_herbacea = \
                        tools_lib.import_variable(row, 'coberturaHerbacea (%)', 'code', ID, code_lists.cobertura_grado)

                    survey.plots[ID].cobertura_vegetal_cobertura_residuos_plantas = \
                        tools_lib.import_variable(row, 'coberturaResiduosPlantas', 'code', ID, code_lists.cobertura_grado_residos)
                    survey.plots[ID].cobertura_vegetal_cobertura_residuos_cultivos = \
                        tools_lib.import_variable(row, 'coberturaResiduosCultivos', 'code', ID, code_lists.cobertura_grado_residos)

                if row['name'] == 'ProductosNoMadereros':
                    survey.plots[ID].ntfp_ntfp_ganado_tipo_1 = \
                        tools_lib.import_variable(row, 'tipoGanado', 'code', ID, code_lists.ntfp_ntfp_ganado_tipo)
                    survey.plots[ID].ntfp_ntfp_pastoreo_intens = \
                        tools_lib.import_variable(row, 'intensidadPastoreo', 'code', ID, code_lists.ntfp_ntfp_pastoreo_intens)
                    survey.plots[ID].ntfp_ntfp_prod_cultivo = \
                        tools_lib.import_variable(row, 'sistemasProduccion', 'code', ID, code_lists.ntfp_ntfp_prod_cultivo)
                    survey.plots[ID].ntfp_ntfp_prod_apicola = \
                        tools_lib.import_variable(row, 'produccionApicola', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_sombra = \
                        tools_lib.import_variable(row, 'sombra', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_rompe_vientos = \
                        tools_lib.import_variable(row, 'rompeVientos', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_hongos = \
                        tools_lib.import_variable(row, 'recoleccionHongos', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_aceites = \
                        tools_lib.import_variable(row, 'aceitesEsenciales', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_semillas = \
                        tools_lib.import_variable(row, 'obtencionSemillas', 'code', ID, code_lists.si_no)
                    #This variable is not available in all files
                    if row.has_key('actividadesCasaPesca'):
                        survey.plots[ID].ntfp_ntfp_caza_pesca = \
                            tools_lib.import_variable(row, 'actividadesCasaPesca', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_recreacion = \
                        tools_lib.import_variable(row, 'actividadesRecreacion', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_cientificos = \
                        tools_lib.import_variable(row, 'estudiosCientificos', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ntfp_ntfp_carbono = \
                        tools_lib.import_variable(row, 'fijacionCarbono', 'code', ID, code_lists.si_no)

                if row['name'] == 'ProblemasAmbientales':
                    survey.plots[ID].ambiental_ambiental_potabilidad = \
                        tools_lib.import_variable(row, 'pobreCalidadAgua', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ambiental_ambiental_polucion = \
                        tools_lib.import_variable(row, 'polucionAire', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ambiental_ambiental_fertalidad = \
                        tools_lib.import_variable(row, 'perdidaFertilidad', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ambiental_ambiental_invasion = \
                        tools_lib.import_variable(row, 'invasionEspecies', 'code', ID, code_lists.si_no)
                    survey.plots[ID].ambiental_ambiental_pesticida = \
                        tools_lib.import_variable(row, 'presenciaPesticidas', 'code', ID, code_lists.si_no)

                if row['name'] == 'Fuego':
                    survey.plots[ID].fuego_fuego_evidencia = \
                        tools_lib.import_variable(row, 'evidenciaFuego', 'code', ID, code_lists.fuego_fuego_evidencias)
                    survey.plots[ID].fuego_fuego_tipo = \
                        tools_lib.import_variable(row, 'tipoFuego', 'code', ID, code_lists.fuego_fuego_tipo)
                    survey.plots[ID].fuego_fuego_proposito = \
                        tools_lib.import_variable(row, 'propositoFuego', 'code', ID, code_lists.fuego_fuego_proposito)

                if survey.plots[ID].general_datos_parcela_bosque_tipo == 2:
                    if row['name'] == 'ForestacionMantenimientoEstructura':
                        survey.plots[ID].forestacion_forest_origen = \
                            tools_lib.import_variable(row, 'origenPlantacion', 'code', ID, code_lists.forestacion_forest_origen)
                        survey.plots[ID].forestacion_forest_estructura = \
                            tools_lib.import_variable(row, 'estructura_forestacion', 'code', ID,
                                                      code_lists.forestacion_forest_estructura)
                        survey.plots[ID].forestacion_forest_propiedad = \
                            tools_lib.import_variable(row, 'propiedadTierra', 'code', ID,
                                                      code_lists.forestacion_forest_propiedad)
                        survey.plots[ID].forestacion_forest_plan_manejo = \
                            tools_lib.import_variable(row, 'planManejo', 'code', ID,
                                                      code_lists.si_no)
                        survey.plots[ID].forestacion_forest_intervencion = \
                            tools_lib.import_variable(row, 'gradoIntervencion', 'code', ID,
                                                      code_lists.human_intervention_degree)
                        survey.plots[ID].forestacion_forest_madera_destino_1 = \
                            tools_lib.import_variable(row, 'destinoMadera', 'code', ID,
                                                      code_lists.forestacion_forest_madera_destino)
                        survey.plots[ID].forestacion_forest_silvicultura = \
                            tools_lib.import_variable(row, 'manejoSilvicultural', 'code', ID,
                                                      code_lists.si_no)
                        survey.plots[ID].forestacion_forest_tecnologia = \
                            tools_lib.import_variable(row, 'tecnologiaExplotacion', 'code', ID,
                                                      code_lists.forestacion_forest_tecnologia)
                    if row['name'] == 'Plantacion':
                        plant_especies = row['genero'] + ' ' + row[
                            'especie_plantacion']
                        index = tools_lib.find_species_scientific(
                            species_list, plant_especies)
                        warn_msg = "Could not find the species \"{species}\" in the species code list for plot: {plotid}" \
                            .format(species=plant_especies, plotid=ID)
                        try:
                            if index.__len__() > 0:
                                survey.plots[
                                    ID].plantacion_plant_especie_code = species_list[
                                        index[0]].species_code
                                survey.plots[
                                    ID].plantacion_plant_especie_scientific_name = species_list[
                                        index[0]].scientific_name
                                survey.plots[
                                    ID].plantacion_plant_especie_vernacular_name = species_list[
                                        index[0]].common_name
                            else:
                                logging.warn(warn_msg)
                        except ValueError:
                            logging.warn(warn_msg)

                        warn_msg = "Could not convert the variable \"rango_edad\" with value: \"{value}\" to edad class for plot{plotid}" \
                            .format(value=row['rangoEdad'], plotid=ID)
                        if row.has_key(
                                'rangoEdad') and row['rangoEdad'] not in [
                                    '', ' ', 'No se define'
                                ]:
                            try:
                                edad_nr = tools_lib.convert_text_to_numbers(
                                    row['rangoEdad'], 'max', 'real')
                                if edad_nr is not None:
                                    edad = tools_lib.convert_plantacion_edad(
                                        float(edad_nr))
                                    survey.plots[
                                        ID].plantacion_plant_edad = edad
                                else:
                                    logging.warn(warn_msg)
                            except ValueError:
                                logging.warn(warn_msg)
                        survey.plots[ID].plantacion_plant_regimen = \
                            tools_lib.import_variable(row, 'regimen', 'code', ID,
                                                      code_lists.plantacion_regimen)
                        survey.plots[ID].plantacion_plant_estado = \
                            tools_lib.import_variable(row, 'estadoGeneral', 'code', ID,
                                                      code_lists.plantacion_estado)
                        survey.plots[ID].plantacion_plant_raleo = \
                            tools_lib.import_variable(row, 'raleo', 'code', ID,
                                                      code_lists.plantacion_raleo)
                        survey.plots[ID].plantacion_plant_poda = \
                            tools_lib.import_variable(row, 'tienePoda', 'code', ID,
                                                      code_lists.si_no)
                        survey.plots[ID].plantacion_plant_poda_altura = \
                            tools_lib.import_variable(row, 'alturaPoda', 'float', ID)
                        survey.plots[
                            ID].plantacion_plant_poda_altura_unit_name = 'metros'
                        survey.plots[ID].plantacion_plant_dist_fila = \
                            tools_lib.import_variable(row, 'distanciaFila', 'float', ID)
                        survey.plots[
                            ID].plantacion_plant_dist_fila_unit_name = 'metros'
                        survey.plots[ID].plantacion_plant_dist_entrefila = \
                            tools_lib.import_variable(row, 'distanciaEntreFila', 'float', ID)
                        survey.plots[
                            ID].plantacion_plant_dist_entrefila_unit_name = 'metros'
                        survey.plots[ID].plantacion_plant_regular = \
                            tools_lib.import_variable(row, 'parcelaRegular', 'code', ID, code_lists.si_no)
                        survey.plots[ID].plantacion_plant_fila_cantidad = \
                            tools_lib.import_variable(row, 'cantidadFilas', 'int', ID)
                        survey.plots[ID].plantacion_plant_dist_silvopast = \
                            tools_lib.import_variable(row, 'distanciaSilvopastoreo', 'float', ID)
                        survey.plots[
                            ID].plantacion_plant_dist_silvopast_unit_name = 'metros'
                        survey.plots[ID].plantacion_plant_adaptacion = \
                            tools_lib.import_variable(row, 'adaptacionEspecie', 'code', ID, code_lists.plantacion_adaptation)

    info_msg = "Updated the plot information for {nplots} plots from the file: {file}"\
                    .format(nplots=counter.__len__(),file=os.path.basename(infile))
    print(info_msg)
    logging.info(info_msg)