Example #1
0
    def get_rand_landuse_offset():
        nrows = IGrid.nrows
        ncols = IGrid.ncols

        i_center = Random.get_int(0, nrows - 1)
        j_center = Random.get_int(0, ncols - 1)
        return int(i_center * ncols + j_center), i_center, j_center
    def phase1n3(diffusion_coeff, breed_coeff, z, delta, slope, excld,
                 slope_weights, sng, sdc):
        TimerUtility.start_timer("spr_phase1n3")
        diffusion_value = Spread.calculate_diffusion_value(diffusion_coeff)
        nrows = IGrid.nrows
        ncols = IGrid.ncols

        for k in range(1 + int(diffusion_value)):
            # get a random row and col index
            i = Random.get_int(0, nrows - 1)
            j = Random.get_int(0, ncols - 1)

            # check if it is an interior point
            if 0 < i < nrows - 1 and 0 < j < ncols - 1:
                success, sng = Spread.urbanize(i, j, z, delta, slope, excld,
                                               slope_weights,
                                               UGMDefines.PHASE1G, sng)
                if success and Random.get_int(0, 100) < breed_coeff:
                    count = 0
                    max_tries = 8
                    for tries in range(max_tries):
                        urbanized, sdc, i_neigh, j_neigh = Spread.urbanize_neighbor(
                            i, j, z, delta, slope, excld, slope_weights,
                            UGMDefines.PHASE3G, sdc)
                        if urbanized:
                            count += 1
                        if count == UGMDefines.MIN_NGHBR_TO_SPREAD:
                            break
        TimerUtility.stop_timer('spr_phase1n3')
        return sng, sdc
    def phase4(spread_coeff, z, excld, delta, slope, slope_weights, og):
        TimerUtility.start_timer('spr_phase4')
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        neighbor_options = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1),
                            (-1, 1), (-1, 0), (-1, -1)]

        # Loop over the interior pixels looking for urban from which to perform organic growth
        for row in range(1, nrows - 1):
            for col in range(1, ncols - 1):
                offset = row * ncols + col

                # Is this an urban pixel and do we pass the random spread coefficient test?
                if z[offset] > 0 and Random.get_int(0, 100) < spread_coeff:

                    # Examine the eight cell neighbors
                    # Spread at random if at least 2 are urban
                    # Pixel itself must be urban (3)
                    urb_count = Spread.count_neighbor(z, row, col)
                    if 2 <= urb_count < 8:
                        x_neigh, y_neigh = Random.get_element(neighbor_options)
                        row_neighbor = row + x_neigh
                        col_neighbor = col + y_neigh
                        success, og = Spread.urbanize(row_neighbor,
                                                      col_neighbor, z, delta,
                                                      slope, excld,
                                                      slope_weights,
                                                      UGMDefines.PHASE4G, og)
        TimerUtility.stop_timer('spr_phase4')
        return og
Example #4
0
def RandomPrecision(k,l):
	m = Random(2)
	bf = Random(pow(10,k))-1
	af = Random(pow(10,l))-1
	af = af / pow(10,l)
	x = bf+af
	if m == 1:
		x = x*(-1)
	return x
    def get_neighbor(row, col):
        neighbor_options = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1),
                            (-1, 1), (-1, 0), (-1, -1)]
        idx = Random.get_int(0, 7)

        idx_x, idx_y = neighbor_options[idx]
        neigh_row = row + idx_x
        neigh_col = col + idx_y

        return idx, int(neigh_row), int(neigh_col)
Example #6
0
    def __init__(self, DorR, cat_corr, **kwargs): 
        """ A class that describes the FFT of galaxy simulated/observed data 
        """
        if 'spec' not in cat_corr.keys(): 
            # default spectrum parameters
            cat_corr['spec'] = {
                    'P0': 20000, #P0 
                    'Lbox': 3600, 
                    'Ngrid':360, 
                    'ell': 0 
                    }

        self.cat_corr = cat_corr.copy()
        self.kwargs = kwargs
        self.type = DorR

        if self.type == 'data': 
            self.galdata = CorrData(self.cat_corr, **self.kwargs)  # data class 
        elif self.type == 'random': 
            self.galdata = Random(self.cat_corr, **self.kwargs)  # data class 
        
        self.file_name = self.file()
    def urbanize(row, col, z, delta, slope, excld, slope_weights, pixel_val,
                 stat):
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        offset = row * ncols + col

        flag = False
        if z[offset] == 0:
            if delta[offset] == 0:
                if Random.get_float() > slope_weights[slope[offset]]:
                    if excld[offset] < Random.get_int(0, 99):
                        flag = True
                        delta[offset] = pixel_val
                        stat += 1
                    else:
                        Stats.increment_excluded_failure()
                else:
                    Stats.increment_slope_failure()
            else:
                Stats.increment_delta_failure()
        else:
            Stats.increment_z_failure()

        return flag, stat
Example #8
0
    def get_new_landuse(class_indices, landuse_classes, local_slope,
                        class_slope):

        # Find two unique land classes
        first_choice, second_choice = Random.get_unique_elements(
            class_indices, 2)

        # Choose landuse with the most similar topographical slope
        slope_diff1 = local_slope - class_slope[first_choice.idx]
        slope_diff2 = local_slope - class_slope[second_choice.idx]

        if slope_diff1 * slope_diff2 < slope_diff2 * slope_diff2:
            new_landuse = landuse_classes[first_choice.idx].num
        else:
            new_landuse = landuse_classes[second_choice.idx].num

        return new_landuse
    def get_valid_neighbor(row, col):
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        neighbor_options = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1),
                            (-1, 1), (-1, 0), (-1, -1)]
        idx = Random.get_int(0, 7)

        valid = False
        neigh_row = 0
        neigh_col = 0
        while not valid:
            idx_x, idx_y = neighbor_options[idx]
            neigh_row = row + idx_x
            neigh_col = col + idx_y
            if 0 <= neigh_row < nrows and 0 <= neigh_col < ncols:
                valid = True
            else:
                # The neighbor chosen isn't valid, go to next index in neighbor list and try again
                idx = (idx + 1) % 8

        return neigh_row, neigh_col
Example #10
0
class Fft(object): 

    def __init__(self, DorR, cat_corr, **kwargs): 
        """ A class that describes the FFT of galaxy simulated/observed data 
        """
        if 'spec' not in cat_corr.keys(): 
            # default spectrum parameters
            cat_corr['spec'] = {
                    'P0': 20000, #P0 
                    'Lbox': 3600, 
                    'Ngrid':360, 
                    'ell': 0 
                    }

        self.cat_corr = cat_corr.copy()
        self.kwargs = kwargs
        self.type = DorR

        if self.type == 'data': 
            self.galdata = CorrData(self.cat_corr, **self.kwargs)  # data class 
        elif self.type == 'random': 
            self.galdata = Random(self.cat_corr, **self.kwargs)  # data class 
        
        self.file_name = self.file()

    def file(self): 
        """ FFT data file name 
        """

        #corrdict = (self.cat_corr)['correction']
        specdict = (self.cat_corr)['spec'] 
    
        fft_dir = direc('fft', self.cat_corr)
        
        self.data_file = self.galdata.file_name # galaxy data file

        # FFT label 
        fft_str = 'FFT_'
        if specdict['ell'] != 0: 
            fft_str += 'Q_'
    
        #if (corrdict['name'].lower() in ('floriansn', 'hectorsn')) & (self.type != 'random'):
        #    fft_corr_str = ''.join(['.', corrdict['name'].lower()])

        # FFTs from data file 
        fft_file = ''.join([
            fft_dir, 
            fft_str, (self.data_file).rsplit('/')[-1], 
            '.grid', str(specdict['Ngrid']), 
            '.P0', str(specdict['P0']), 
            '.box', str(int(specdict['Lbox']))
            ])

        return fft_file  

    def build(self): 
        """ Run FFT FORTRAN code to calculate FFT of data
        """
        specdict = (self.cat_corr)['spec'] 
        
        if not os.path.isfile(self.data_file):
            self.galdata.build()

        #if 'quad' not in specdict.keys(): 
        #    raise KeyError(" 'quad' must be specified ") 
        #if not specdict['quad']:       # quadrupole or regular FFT code
        #    fft_type = 'fft'
        #else:  
        #    fft_type = 'quad_fft'
    
        #if specdict['ell'] == 0: 
        fft_type = 'fft'
        #else: 
        #    fft_type = 'quad_fft'       # (outdated naming convention but too lazy to fully change)

        codeclass = Fcode(fft_type, self.cat_corr) 
        fftcode = codeclass.code
        fftexe = codeclass.fexe()
        
        # code and exe modification time 
        fftcode_t_mod, fftexe_t_mod = codeclass.mod_time()

        if fftexe_t_mod < fftcode_t_mod: 
            codeclass.compile()
                
        fft_file = self.file() 

        if specdict['ell'] == 0:       # Monopole 
            
            # command line call 
            FFTcmd = codeclass.commandline_call(
                    DorR = self.type, 
                    datafile = self.data_file,
                    fftfile = self.file_name
                    ) 

            if 'clobber' not in (self.kwargs).keys(): 
                bool_clobber = False
            else: 
                bool_clobber = self.kwargs['clobber']

            if any([not os.path.isfile(self.file_name), bool_clobber]):
                print ''
                print '-----------------------'
                print 'Constructing '
                print self.file_name  
                print '-----------------------'
                print ''
                print FFTcmd
                print '-----------------------'

                subprocess.call(FFTcmd.split())
            else: 
                print ''
                print '-----------------------'
                print self.file_name  
                print 'Already Exists'
                print '-----------------------'
                print ''

        else:                           # others Quadrupole
            # command line call 
            FFTcmd = codeclass.commandline_call(
                    DorR = self.type, 
                    datafile = self.data_file,
                    fftfile = self.file_name
                    ) 

            if 'clobber' not in (self.kwargs).keys(): 
                bool_clobber = False
            else: 
                bool_clobber = self.kwargs['clobber']

            if any([not os.path.isfile(self.file_name), bool_clobber]):
                print ''
                print '-----------------------'
                print 'Constructing '
                print self.file_name  
                print '-----------------------'
                print ''
                print FFTcmd
                print '-----------------------'

                subprocess.call(FFTcmd.split())
            else: 
                print ''
                print '-----------------------'
                print self.file_name  
                print 'Already Exists'
                print '-----------------------'
                print ''

        return None 
Example #11
0
def RandomInterval(k,l):
	x = Random(l-k+1)+k-1
	return x
Example #12
0
def main():
    """Starts the program"""

    # check command lines argument count
    if len(sys.argv) < 3:
        print("Not enough arguments:\n\tUsage: ./test.py path/to/board" +
              " random/breadth/depth [amount of tries]")
        sys.exit(1)

    # defines how many times a solution is searched for
    if len(sys.argv) == 4:
        tries = int(sys.argv[3])
    else:
        tries = 1

    # defines the path to the board that needs solving
    path = str(sys.argv[1])

    # counts how many solutions have been found already
    count = 0

    # get start time for basic benchmarking
    t0 = time.time()

    # solve using random search
    if sys.argv[2] == "random":
        while count < tries:

            # get current system time
            time0 = time.time()

            # sets up a start board from file
            board = setup_board(path)

            # creates a random instance
            random = Random(board)

            # starts the random algorithm to solve the puzzle
            random.solve()

            # count how many solutions have been found
            count += 1

    # solve using breadth first
    elif sys.argv[2] == "breadth":
        board = setup_board(path)
        breadth = Breadth(board)
        breadth.solve()

    # solve using depth first
    elif sys.argv[2] == "depth":
        board = setup_board(path)
        depth = Depth(board)
        depth.solve()

    # invalid commandline arguments
    else:
        print("Usage: ./test.py path/to/board random/breadth/depth" +
              "[amount of tries]")
        sys.exit(2)

    # print benchmark time
    t1 = time.time()
    print("Total time: {}".format(t1 - t0))
Example #13
0
    def get_neighbor(i_in, j_in):
        neighbor_options = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)]
        i_offset, j_offset = Random.get_element(neighbor_options)

        return i_in + i_offset, j_in + j_offset
Example #14
0
    def phase5(road_gravity, diffusion_coeff, breed_coeff, z, delta, slope,
               excld, roads, slope_weights, rt):
        TimerUtility.start_timer('spr_phase5')
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        total_pixels = nrows * ncols

        # Determine the total growth count and save the row and col locations of the new growth
        growth_tracker = []
        growth_count = 0
        for i in range(total_pixels):
            if delta[i] > 0:
                growth_tracker.append((int(i / ncols), i % ncols))
                growth_count += 1

        # Phase 5: Road Trips
        # If there is new growth, begin processing road trips
        if growth_count > 0:
            for i in range(1 + int(breed_coeff)):
                """Determine the Max Index into the Global_Road_Seach_Incices Array
                 for road_gravity of 1 we have 8 values
                 for road_gravity of 2 we have 16 values
                 for road_gravity of 3 we have 24 values
                    and so on...
                    
                if we need to cover N road_gravity values, then the total number of 
                indexed values woud be
                8 + 16 + 24 + ... + (8*N) = 8 *(1+2+3+...+N) = 8*(N(1+N))/2
                """

                int_road_gravity = Spread.get_road_gravity_val(road_gravity)
                max_search_index = 4 * (int_road_gravity *
                                        (1 + int_road_gravity))
                max_search_index = max(max_search_index, nrows)
                max_search_index = max(max_search_index, ncols)

                # Randomly select a growth pixel to start search for road
                growth_row, growth_col = Random.get_element(growth_tracker)

                # Search for road about this growth point
                road_found, i_road_start, j_road_start = Spread.road_search(
                    growth_row, growth_col, max_search_index, roads)

                # If there is a road found, then walk along it
                i_road_end = 0
                j_road_end = 0
                spread = False
                if road_found:
                    #print(roads)
                    spread, i_road_end, j_road_end = Spread.road_walk(
                        i_road_start, j_road_start, roads, diffusion_coeff)

                if spread:
                    urbanized, rt, i_neigh, j_neigh = Spread.urbanize_neighbor(
                        i_road_end, j_road_end, z, delta, slope, excld,
                        slope_weights, UGMDefines.PHASE5G, rt)
                    if urbanized:
                        max_tries = 3
                        for tries in range(3):
                            urbanized, rt, i_neigh_neigh, j_neigh_neigh = Spread.urbanize_neighbor(
                                i_neigh, j_neigh, z, delta, slope, excld,
                                slope_weights, UGMDefines.PHASE5G, rt)
        TimerUtility.stop_timer('spr_phase5')
        return rt
Example #15
0
def main():
    TimerUtility.start_timer('total_time')
    valid_modes = ["predict", "restart", "test", "calibrate"]

    Globals.mype = 0
    Globals.npes = 1
    packing = False
    restart_run = 0

    # Parse command line

    if len(sys.argv) != 3:
        __print_usage(sys.argv[0])
        sys.exit(1)

    if len(sys.argv) != 3 or sys.argv[1] not in valid_modes:
        __print_usage(sys.argv[0])
        sys.exit(1)

    Processing.set_processing_type(Globals.mode_enum[sys.argv[1]])

    if Processing.get_processing_type() == Globals.mode_enum['restart']:
        Processing.set_restart_flag(True)

    Scenario.init(sys.argv[2], Processing.get_restart_flag())

    try:

        log_it = Scenario.get_scen_value("logging")
        random_seed = Scenario.get_scen_value("random_seed")
        Random.set_seed(random_seed)

        landuse_class_info = Scenario.get_scen_value("landuse_class_info")
        LandClass.num_landclasses = len(landuse_class_info)
        # filling in the class array in Land_Class
        for i, landuse_class in enumerate(landuse_class_info):
            # num, class_id, name, idx, hexColor
            landuse_class_meta = LanduseMeta(landuse_class.grayscale,
                                             landuse_class.type,
                                             landuse_class.name, i,
                                             landuse_class.color[2:])
            LandClass.landuse_classes.append(landuse_class_meta)

        # Set up Coefficients
        if sys.argv[1] == 'restart':
            if log_it:
                print("Implement log here")

            diffusion, breed, spread, slope_resistance, road_gravity, random_seed, restart_run = \
                Input.read_restart_file(Scenario.get_scen_value("output_dir"))
            Processing.set_current_run(restart_run)

        else:
            Processing.set_current_run(0)

        Coeff.set_start_coeff(
            Scenario.get_scen_value("calibration_diffusion_start"),
            Scenario.get_scen_value("calibration_spread_start"),
            Scenario.get_scen_value("calibration_breed_start"),
            Scenario.get_scen_value("calibration_slope_start"),
            Scenario.get_scen_value("calibration_road_start"))
        Coeff.set_stop_coeff(
            Scenario.get_scen_value("calibration_diffusion_stop"),
            Scenario.get_scen_value("calibration_spread_stop"),
            Scenario.get_scen_value("calibration_breed_stop"),
            Scenario.get_scen_value("calibration_slope_stop"),
            Scenario.get_scen_value("calibration_road_stop"))
        Coeff.set_step_coeff(
            Scenario.get_scen_value("calibration_diffusion_step"),
            Scenario.get_scen_value("calibration_spread_step"),
            Scenario.get_scen_value("calibration_breed_step"),
            Scenario.get_scen_value("calibration_slope_step"),
            Scenario.get_scen_value("calibration_road_step"))
        Coeff.set_best_fit_coeff(
            Scenario.get_scen_value("prediction_diffusion_best_fit"),
            Scenario.get_scen_value("prediction_spread_best_fit"),
            Scenario.get_scen_value("prediction_breed_best_fit"),
            Scenario.get_scen_value("prediction_slope_best_fit"),
            Scenario.get_scen_value("prediction_road_best_fit"))

        # Initial IGrid
        IGrid.init(packing, Processing.get_processing_type())
        '''
        Skipped memory and logging stuff for now, don't know if I'll need it
        If there is a problem, I can go back and implement
        '''

        # Initialize Landuse
        if len(Scenario.get_scen_value("landuse_data_file")) > 0:
            LandClass.init()
            if Scenario.get_scen_value("log_landclass_summary"):
                if log_it:
                    # this is where we would log
                    Logger.log("Test log")

        # Initialize Colortables
        Color.init(IGrid.ncols)

        # Read and validate input
        IGrid.read_input_files(packing,
                               Scenario.get_scen_value("echo_image_files"),
                               Scenario.get_scen_value("output_dir"))
        IGrid.validate_grids(log_it)

        # Normalize Roads
        IGrid.normalize_roads()

        landuse_flag = len(Scenario.get_scen_value("landuse_data_file")) != 0
        IGrid.verify_inputs(log_it, landuse_flag)

        # Initialize PGRID Grids
        PGrid.init(IGrid.get_total_pixels())

        if log_it and Scenario.get_scen_value("log_colortables"):
            Color.log_colors()

        # Count the Number of Runs
        Processing.set_total_runs()
        Processing.set_last_monte(
            int(Scenario.get_scen_value("monte_carlo_iterations")) - 1)
        if log_it:
            if Processing.get_processing_type(
            ) == Globals.mode_enum["calibrate"]:
                Logger.log(
                    f"Total Number of Runs = {Processing.get_total_runs()}")

        # Compute Transition Matrix
        if len(Scenario.get_scen_value("landuse_data_file")) > 0:
            Transition.create_matrix()
            if log_it and Scenario.get_scen_value("log_transition_matrix"):
                Transition.log_transition()

        # Compute the Base Statistics against which the calibration will take place
        Stats.set_base_stats()
        if log_it and Scenario.get_scen_value("log_base_statistics"):
            Stats.log_base_stats()

        if log_it and Scenario.get_scen_value("log_debug"):
            IGrid.debug("main.py")

        Processing.set_num_runs_exec_this_cpu(0)
        if Processing.get_current_run() == 0 and Globals.mype == 0:
            output_dir = Scenario.get_scen_value("output_dir")
            if Processing.get_processing_type(
            ) != Globals.mode_enum["predict"]:
                filename = f"{output_dir}control_stats.log"
                Stats.create_control_file(filename)

            if Scenario.get_scen_value("write_std_dev_file"):
                filename = f"{output_dir}std_dev.log"
                Stats.create_stats_val_file(filename)

            if Scenario.get_scen_value("write_avg_file"):
                filename = f"{output_dir}avg.log"
                Stats.create_stats_val_file(filename)

        if Scenario.get_scen_value("write_coeff_file"):
            output_dir = Scenario.get_scen_value("output_dir")
            filename = f"{output_dir}coeff.log"
            Coeff.create_coeff_file(filename, True)

        if Processing.get_processing_type() == Globals.mode_enum["predict"]:
            # Prediction Runs
            Processing.set_stop_year(
                Scenario.get_scen_value("prediction_stop_date"))
            Coeff.set_current_coeff(Coeff.get_best_diffusion(),
                                    Coeff.get_best_spread(),
                                    Coeff.get_best_breed(),
                                    Coeff.get_best_slope_resistance(),
                                    Coeff.get_best_road_gravity())
            if Globals.mype == 0:
                Driver.driver()
                Processing.increment_num_runs_exec_this_cpu()

            # Timing stuff
            if log_it and int(Scenario.get_scen_value('log_timings')) > 1:
                TimerUtility.log_timers()

        else:
            # Calibration and Test Runs
            Processing.set_stop_year(
                IGrid.igrid.get_urban_year(IGrid.igrid.get_num_urban() - 1))

            output_dir = Scenario.get_scen_value('output_dir')
            d_start, d_step, d_stop = Coeff.get_start_step_stop_diffusion()
            for diffusion_coeff in range(d_start, d_stop + 1, d_step):
                b_start, b_step, b_stop = Coeff.get_start_step_stop_breed()
                for breed_coeff in range(b_start, b_stop + 1, b_step):
                    s_start, s_step, s_stop = Coeff.get_start_step_stop_spread(
                    )
                    for spread_coeff in range(s_start, s_stop + 1, s_step):
                        sr_start, sr_step, sr_stop = Coeff.get_start_step_stop_slope_resistance(
                        )
                        for slope_resist_coeff in range(
                                sr_start, sr_stop + 1, sr_step):
                            rg_start, rg_step, rg_stop = Coeff.get_start_step_stop_road_gravity(
                            )
                            for road_grav_coeff in range(
                                    rg_start, rg_stop + 1, rg_step):
                                filename = f"{output_dir}{UGMDefines.RESTART_FILE}{Globals.mype}"
                                Output.write_restart_data(
                                    filename, diffusion_coeff, breed_coeff,
                                    spread_coeff, slope_resist_coeff,
                                    road_grav_coeff,
                                    Scenario.get_scen_value('random_seed'),
                                    restart_run)

                                restart_run += 1
                                Coeff.set_current_coeff(
                                    diffusion_coeff, spread_coeff, breed_coeff,
                                    slope_resist_coeff, road_grav_coeff)
                                Driver.driver()
                                Processing.increment_num_runs_exec_this_cpu()
                                # Timing Logs
                                if log_it and int(
                                        Scenario.get_scen_value(
                                            'log_timings')) > 1:
                                    TimerUtility.log_timers()

                                Processing.increment_current_run()

                                if Processing.get_processing_type(
                                ) == Globals.mode_enum['test']:
                                    TimerUtility.stop_timer('total_time')
                                    if log_it and int(
                                            Scenario.get_scen_value(
                                                'log_timings')) > 0:
                                        TimerUtility.log_timers()
                                    Logger.close()
                                    sys.exit(0)

        # Stop timer
        TimerUtility.stop_timer('total_time')
        if log_it and int(Scenario.get_scen_value('log_timings')) > 0:
            TimerUtility.log_timers()
        # Close Logger
        Logger.close()

    except KeyError as err:
        traceback.print_exc()
        print("{0} is not set. Please set it in your scenario file".format(
            str(err).upper()))
        Logger.log("Something went wrong")
        Logger.close()
        sys.exit(1)
    except FileNotFoundError as err:
        traceback.print_exc()
        print(err)
        Logger.log("Something went wrong")
        Logger.close()
        sys.exit(1)
    except Exception:
        traceback.print_exc()
        Logger.log("Something went wrong")
        Logger.close()
        sys.exit(1)
Example #16
0
    def phase1(drive, urban_land, slope, deltatron, landuse_classes,
               class_indices, new_indices, class_slope, ftransition):
        TimerUtility.start_timer('delta_phase1')
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        phase1_land = []
        # Copy input land grid into output land grid
        for urban in urban_land:
            phase1_land.append(urban)

        # Try to make Transitions
        for tries in range(drive):
            # Select a transition pixel to e center of spreading cluster
            offset, i_center, j_center = Deltatron.get_rand_landuse_offset()
            index = new_indices[urban_land[offset]]
            while not landuse_classes[index].trans:
                offset, i_center, j_center = Deltatron.get_rand_landuse_offset(
                )
                index = new_indices[urban_land[offset]]

            # Randomly choose new landuse number
            new_landuse = Deltatron.get_new_landuse(class_indices,
                                                    landuse_classes,
                                                    slope[offset], class_slope)

            # Test transition probability for new cluster
            new_i = new_indices[urban_land[offset]]
            new_j = new_indices[new_landuse]
            trans_offset = new_i * LandClass.get_num_landclasses() + new_j
            if Random.get_float() < ftransition[trans_offset]:
                # Transition the center pixel
                phase1_land[offset] = new_landuse
                deltatron[offset] = 1

                # Try building up cluster around this center pixel
                i = i_center
                j = j_center
                for regions in range(UGMDefines.REGION_SIZE):
                    # Occasionally Reset to center of cluster
                    random_int = Random.get_int(0, 7)
                    if random_int == 7:
                        i = i_center
                        j = j_center
                    # Get a neighbor
                    i, j = Utilities.get_neighbor(i, j)
                    if 0 <= i < nrows and 0 <= j < ncols:
                        # Test new pixel against transition probability
                        offset = i * ncols + j
                        # print(f"{len(urban_land)} | {i} {j} -> {offset}")
                        urban_index = urban_land[offset]
                        new_i = new_indices[urban_index]
                        new_j = new_indices[new_landuse]
                        trans_offset = new_i * LandClass.get_num_landclasses(
                        ) + new_j
                        if Random.get_float() < ftransition[trans_offset]:
                            # If the immediate pixel is allowed to transition, then change it
                            index = new_indices[urban_land[offset]]
                            if landuse_classes[index].trans:
                                phase1_land[offset] = new_landuse
                                deltatron[offset] = 1

                            # Try to transition a neighboring pixel
                            i, j = Utilities.get_neighbor(i, j)
                            if 0 <= i < nrows and 0 <= j < ncols:
                                offset = i * ncols + j
                                index = new_indices[urban_land[offset]]
                                if landuse_classes[index].trans:
                                    phase1_land[offset] = new_landuse
                                    deltatron[offset] = 1
        TimerUtility.stop_timer('delta_phase1')
        return phase1_land
Example #17
0
File: car.py Project: CErgusa/ADT
    def which_way_to_turn(self):
        # create a random number generator
        rand = Random()
        if self.intersectionID == predefines.INTERSECTION1:
            # can't be coming down
            if self.direction == predefines.UP:
                # can go down, left, or right
                self.path = rand.og_randint(1, 3)
            elif self.direction == predefines.LEFT:
                # down, left or up
                self.path = rand.og_randint(0, 2)
            elif self.direction == predefines.RIGHT:
                # up, down, or right
                self.path = rand.skip_randint(0, 3, 2)
            else:
                return
        elif self.intersectionID == predefines.INTERSECTION2:
            # can't be coming right
            if self.direction == predefines.UP:
                # can go up, down, or right
                self.path = rand.skip_randint(0, 3, 2)
            elif self.direction == predefines.DOWN:
                # up, down, left
                self.path = rand.og_randint(0, 2)
            elif self.direction == predefines.LEFT:
                # down, left, right
                self.path = rand.og_randint(1, 3)
            else:
                return
        elif self.intersectionID == predefines.INTERSECTION3:
            # can go anywhere
            self.path = rand.og_randint(0, 3) # up, down, left, right

        elif self.intersectionID == predefines.INTERSECTION4:
            # can't be coming left
            if self.direction == predefines.UP:
                # can go up, down, or left
                self.path = rand.og_randint(0, 2)
            elif self.direction == predefines.DOWN:
                # up, down, right
                self.path = rand.skip_randint(0, 3, 2)
            elif self.direction == predefines.RIGHT:
                # down, left, right
                self.path = rand.og_randint(1, 3)
            else:
                return
        elif self.intersectionID == predefines.INTERSECTION5:
            # can't be coming up
            if self.direction == predefines.RIGHT:
                # can go up, down, or right
                self.path = rand.og_randint(0, 2)
            elif self.direction == predefines.DOWN:
                # down, left, right (can't go up)
                self.path = rand.og_randint(1, 3)
            elif self.direction == predefines.LEFT:
                # up, down, left
                self.path = rand.skip_randint(0, 3, 2)
            else:
                return
        else:
            return
Example #18
0
    def phase2(urban_land, phase1_land, deltatron, landuse_classes,
               new_indices, ftransition):
        TimerUtility.start_timer('delta_phase2')
        nrows = IGrid.nrows
        ncols = IGrid.ncols
        phase2_land = []

        # Copy current land to phase2_land
        for pixel in phase1_land:
            phase2_land.append(pixel)

        # For each interior point
        for i in range(1, nrows - 1):
            for j in range(1, ncols - 1):
                offset = i * ncols + j
                index = new_indices[phase1_land[offset]]
                if landuse_classes[index].trans and deltatron[offset] == 0:
                    """
                    I,J is a Transitional Pixel which was not transitioned within the last 
                    min_years_between_transitions years; count its neighbors which have transitioned
                    in previous year (IE Deltatron == 2)
                    """
                    deltatron_neighbors = Deltatron.count_neighbor(
                        deltatron, i, j)
                    random_int = 1 + Random.get_int(0, 1)
                    if deltatron_neighbors >= random_int:
                        max_tries = 16
                        for tries in range(max_tries):
                            i_neigh, j_neigh = Utilities.get_neighbor(i, j)
                            offset_neigh = i_neigh * ncols + j_neigh
                            index = new_indices[phase1_land[offset_neigh]]
                            if deltatron[offset_neigh] == 2 and landuse_classes[
                                    index]:
                                trans_i = new_indices[phase2_land[offset]]
                                trans_j = new_indices[urban_land[offset_neigh]]
                                offset_trans = trans_i * LandClass.get_num_landclasses(
                                ) + trans_j
                                if Random.get_float(
                                ) < ftransition[offset_trans]:
                                    phase2_land[offset] = urban_land[
                                        offset_neigh]
                                    deltatron[offset] = 1
                                break
        if Scenario.get_scen_value('view_deltatron_aging'):
            if IGrid.using_gif:
                filename = f"{Scenario.get_scen_value('output_dir')}deltatron_{Processing.get_current_run()}_" \
                           f"{Processing.get_current_monte()}_{Processing.get_current_year()}.gif"
            else:
                filename = f"{Scenario.get_scen_value('output_dir')}deltatron_{Processing.get_current_run()}_" \
                           f"{Processing.get_current_monte()}_{Processing.get_current_year()}.tif"

            date = f"{Processing.get_current_year()}"
            ImageIO.write_gif(deltatron, Color.get_deltatron_table(), filename,
                              date, nrows, ncols)

        # Age the Deltatrons
        for i in range(nrows * ncols):
            if deltatron[i] > 0:
                deltatron[i] += 1

        # Kill old deltatrons
        Utilities.condition_gt_gif(deltatron,
                                   UGMDefines.MIN_YEARS_BETWEEN_TRANSITIONS,
                                   deltatron, 0)
        TimerUtility.stop_timer("delta_phase2")
        return phase2_land