def get_climate_zones(configurationYaml, gisPath):
    '''
    Get the climate zones that are defined in the configuration.
    
    configurationYaml - The loaded configuration to examine.
    gisPath - The path to append to GIS files in the configuration.
    
    Returns a matrix contianing the climate zones, locations without a zone will use the common nodata value.
    '''

    # Start by checking if there is a raster defined, if so just load and return that
    if 'ecoclimatic_raster' in configurationYaml['raster_db']:
        filename = str(configurationYaml['raster_db']['ecoclimatic_raster'])
        filename = os.path.join(gisPath, filename)
        [_, ascData] = load_asc(filename)
        return ascData

    # There is not, make sure there is a single zone defined before continuing
    if len(configurationYaml["seasonal_info"]["base"]) != 1:
        print("Multiple climate zones, but no raster defined.")
        exit(1)

    # Get the zone value
    ecozone = len(
        configurationYaml["seasonal_info"]["base"]) - 1  # Zero indexed

    # Districts need to be defined, so use that as our template raster
    filename = str(configurationYaml['raster_db']['district_raster'])
    filename = os.path.join(gisPath, filename)
    return generate_raster(filename, ecozone)
def get_treatments_raster(configurationYaml, gisPath):
    '''
    Get the treatment raster that is defined in the configuration

    configurationYaml - The loaded configuration to examine.
    gisPath - The path to append to GIS files in the configuration.

    Returns a matrix contianing the climate zones, locations without a zone will use the common nodata value.
    '''

    # Start by checking if there is a raster defined, if so just load and return that
    if 'pr_treatment_under5' in configurationYaml['raster_db']:
        filename = str(configurationYaml['raster_db']['pr_treatment_under5'])
        filename = os.path.join(gisPath, filename)
        [_, ascData] = load_asc(filename)
        return ascData

    # There is not, make sure there is a single value defined before continuing
    underFive = float(configurationYaml['raster_db']
                      ['p_treatment_for_less_than_5_by_location'][0])
    overFive = float(configurationYaml['raster_db']
                     ['p_treatment_for_more_than_5_by_location'][0])

    # There is not, make sure there is a single zone defined before continuing
    if underFive != overFive:
        print(
            "Different treatments defined for under and over five, not supported."
        )
        exit(1)

    # Generate and return the reference raster
    filename = str(configurationYaml['raster_db']['district_raster'])
    filename = os.path.join(gisPath, filename)
    return generate_raster(filename, underFive)
Пример #3
0
def main(method, filename, progress=True):
    # Load the relevent ASC data
    [ascHeader, pfpr] = load_asc("../../GIS/rwa_pfpr2to10.asc")
    [_, population] = load_asc("../../GIS/rwa_population.asc")
    [_, treatments] = load_asc("../../GIS/rwa_treatment.asc")

    beta = []
    for row in range(0, ascHeader['nrows']):
        beta.append([])
        for col in range(0, ascHeader['ncols']):

            # Append no data and continue
            if pfpr[row][col] == ascHeader['nodata']:
                beta[row].append(ascHeader['nodata'])
                continue

            # If PfPR is zero, then beta is zero
            if pfpr[row][col] == 0:
                beta[row].append(0)
                continue

            # Get the population bin, find the beta for the cell
            popBin = get_bin(population[row][col], POPULATION_BINS)
            target = round(pfpr[row][col] * 100.0, 8)
            result = method("data/calibration.csv", popBin,
                            treatments[row][col], target)

            # Check for errors before updating the array
            if result is None:
                sys.stderr.write("Null value returned for beta, exiting\n")
                sys.exit(1)
            if result < 0:
                sys.stderr.write(
                    "Projected beta {} is less than zero, exiting\n".format(
                        result))
                # Only exit if the debug flag isn't set
                if progress:
                    sys.exit(1)
            beta[row].append(result)

        # Note the progress
        if progress:
            progressBar(row + 1, ascHeader['nrows'])

    # Save the calculated beta values
    print("Saving {}".format(filename))
    write_asc(ascHeader, beta, filename)
def generate_raster(filename, value):
    '''Generate a reference raster using the data in the filename and the value provided'''

    [ascHeader, ascData] = load_asc(filename)
    for row in range(0, ascHeader['nrows']):
        for col in range(0, ascHeader['ncols']):
            if ascData[row][col] == ascHeader['nodata']:
                continue
            ascData[row][col] = value
    return ascData
def get_treatments_list(configurationYaml, gisPath):
    '''
    Extract the treatments from the configuration that is supplied.

    configurationYaml - The loaded configuration to examine.
    gisPath - The path to append to GIS files in the configuration.

    Returns [results, needsBinning] where results are the parsed treatments and needsBinning indicates that the treatments need to be binned if True.
    '''

    # Start by checking the district level treatment values, note the zero index
    underFive = float(configurationYaml['raster_db']
                      ['p_treatment_for_less_than_5_by_location'][0])
    overFive = float(configurationYaml['raster_db']
                     ['p_treatment_for_more_than_5_by_location'][0])

    # If both are not equal to the sentinel then they are set via a raster
    if not (underFive == overFive == YAML_SENTINEL):
        results = []
        if underFive != YAML_SENTINEL:
            results.append(underFive)
        if overFive != YAML_SENTINEL:
            results.append(overFive)
        return results, False

    # Get the unique under five treatments
    try:
        filename = str(configurationYaml['raster_db']['pr_treatment_under5'])
        filename = os.path.join(gisPath, filename)
        [acsHeader, ascData] = load_asc(filename)
        underFive = list(set(i for j in ascData for i in j))
        underFive.remove(acsHeader['nodata'])
    except FileNotFoundError:
        # Warn and return when the U5 treatment rate cannot be opened
        sys.stderr.write(
            "ERROR: Unable to open file associated with under five treatment rate: {}\n"
            .format(filename))
        return None

    # Get the unique over five treatments
    try:
        filename = str(configurationYaml['raster_db']['pr_treatment_over5'])
        filename = os.path.join(gisPath, filename)
        [_, ascData] = load_asc(filename)
        overFive = list(set(i for j in ascData for i in j))
        overFive.remove(acsHeader['nodata'])
    except FileNotFoundError:
        # Warn and continue when the O5 rate cannot be opened
        sys.stderr.write(
            "WARNING: Unable to open file associated with over five treatment rate: {}\n"
            .format(filename))
        sys.stderr.write(
            "WARNING: Continued without over five treatment rates.\n")
        overFive = []

    # Get the unique district ids
    filename = str(configurationYaml['raster_db']['district_raster'])
    filename = os.path.join(gisPath, filename)
    [_, ascData] = load_asc(filename)
    districts = list(set(i for j in ascData for i in j))
    districts.remove(acsHeader['nodata'])

    # If either treatment list is greater than districts, binning is needed
    # NOTE This is just a rough heuristic for the time being
    needsBinning = (len(underFive) > len(districts)) or (len(overFive) >
                                                         len(districts))

    # Merge the under five and over five into a single set and return
    results = set(underFive + overFive)
    return results, needsBinning