Exemple #1
0
    def initialize(self,
                   grid_size=(5, 5),
                   report_interval=5.0,
                   grid_orientation="vertical",
                   node_layout="rect",
                   show_plots=False,
                   cts_type="oriented_hex",
                   run_duration=1.0,
                   output_interval=1.0e99,
                   plot_every_transition=False,
                   **kwds):

        # Remember the clock time, and calculate when we next want to report
        # progress.
        self.current_real_time = time.time()
        self.next_report = self.current_real_time + report_interval
        self.report_interval = report_interval

        # Interval for output
        self.output_interval = output_interval

        # Duration for run
        self.run_duration = run_duration

        # Create a grid
        self.create_grid_and_node_state_field(grid_size[0], grid_size[1],
                                              grid_orientation, node_layout,
                                              cts_type)

        # Create the node-state dictionary
        ns_dict = self.node_state_dictionary()

        # Initialize values of the node-state grid
        nsg = self.initialize_node_state_grid()

        # Create the transition list
        xn_list = self.transition_list()

        # Create the CA object
        if cts_type == "raster":
            from landlab.ca.raster_cts import RasterCTS

            self.ca = RasterCTS(self.grid, ns_dict, xn_list, nsg)
        elif cts_type == "oriented_raster":
            from landlab.ca.oriented_raster_cts import OrientedRasterCTS

            self.ca = OrientedRasterCTS(self.grid, ns_dict, xn_list, nsg)
        elif cts_type == "hex":
            from landlab.ca.hex_cts import HexCTS

            self.ca = HexCTS(self.grid, ns_dict, xn_list, nsg)
        else:
            from landlab.ca.oriented_hex_cts import OrientedHexCTS

            self.ca = OrientedHexCTS(self.grid, ns_dict, xn_list, nsg)

        # Initialize graphics
        self._show_plots = show_plots
        if show_plots:
            self.initialize_plotting(**kwds)
Exemple #2
0
def test_transitions_as_ids():
    """Test passing from-state and to-state IDs instead of tuples """

    mg = HexModelGrid(3, 2, 1.0, orientation="vertical", reorient_links=True)
    nsd = {0: "zero", 1: "one"}
    xnlist = []
    xnlist.append(Transition(2, 3, 1.0, "transitioning"))
    nsg = mg.add_zeros("node", "node_state_grid")
    cts = HexCTS(mg, nsd, xnlist, nsg)
    assert cts.num_link_states == 4, "wrong number of transitions"
Exemple #3
0
def test_hex_cts():
    """Tests instantiation of a HexCTS() object"""
    mg = HexModelGrid(3, 2, 1.0, orientation="vertical", reorient_links=True)
    nsd = {0: "zero", 1: "one"}
    xnlist = []
    xnlist.append(Transition((0, 1, 0), (1, 1, 0), 1.0, "transitioning"))
    nsg = mg.add_zeros("node", "node_state_grid")
    hcts = HexCTS(mg, nsd, xnlist, nsg)

    assert hcts.num_link_states == 4
    assert_array_equal(hcts.link_orientation, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Exemple #4
0
def test_hex_cts():
    """Tests instantiation of a HexCTS() object"""
    mg = HexModelGrid(3, 2, 1.0, orientation='vertical', reorient_links=True)
    nsd = {0 : 'zero', 1 : 'one'}
    xnlist = []
    xnlist.append(Transition((0,1,0), (1,1,0), 1.0, 'transitioning'))
    nsg = mg.add_zeros('node', 'node_state_grid')
    hcts = HexCTS(mg, nsd, xnlist, nsg)

    assert_equal(hcts.num_link_states, 4)
    assert_array_equal(hcts.link_orientation, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Exemple #5
0
    def initialize(self,
                   grid_size=(5, 5),
                   report_interval=5.0,
                   grid_orientation='vertical',
                   grid_shape='rect',
                   show_plots=False,
                   cts_type='oriented_hex',
                   run_duration=1.0,
                   output_interval=1.0e99,
                   plot_every_transition=False,
                   initial_state_grid=None,
                   prop_data=None,
                   prop_reset_value=None,
                   **kwds):
        """Initialize CTSModel."""
        # Remember the clock time, and calculate when we next want to report
        # progress.
        self.current_real_time = time.time()
        self.next_report = self.current_real_time + report_interval
        self.report_interval = report_interval

        # Interval for output
        self.output_interval = output_interval

        # Duration for run
        self.run_duration = run_duration

        # Create a grid
        self.create_grid_and_node_state_field(grid_size[0], grid_size[1],
                                              grid_orientation, grid_shape,
                                              cts_type)

        # If prop_data is a string, we assume it is a field name
        if isinstance(prop_data, string_types):
            prop_data = self.grid.add_zeros('node', prop_data)

        # Create the node-state dictionary
        ns_dict = self.node_state_dictionary()

        # Initialize values of the node-state grid
        if initial_state_grid is None:
            nsg = self.initialize_node_state_grid()
        else:
            try:
                nsg = initial_state_grid
                self.grid.at_node['node_state'][:] = nsg
            except:
                #TODO: use new Messaging capability
                print('If initial_state_grid given, must be array of int')
                raise

        # Create the transition list
        xn_list = self.transition_list()

        # Create the CA object
        if cts_type == 'raster':
            from landlab.ca.raster_cts import RasterCTS
            self.ca = RasterCTS(self.grid, ns_dict, xn_list, nsg, prop_data,
                                prop_reset_value)
        elif cts_type == 'oriented_raster':
            from landlab.ca.oriented_raster_cts import OrientedRasterCTS
            self.ca = OrientedRasterCTS(self.grid, ns_dict, xn_list, nsg,
                                        prop_data, prop_reset_value)
        elif cts_type == 'hex':
            from landlab.ca.hex_cts import HexCTS
            self.ca = HexCTS(self.grid, ns_dict, xn_list, nsg, prop_data,
                             prop_reset_value)
        else:
            from landlab.ca.oriented_hex_cts import OrientedHexCTS
            self.ca = OrientedHexCTS(self.grid, ns_dict, xn_list, nsg,
                                     prop_data, prop_reset_value)

        # Initialize graphics
        self._show_plots = show_plots
        if show_plots == True:
            self.initialize_plotting(**kwds)
Exemple #6
0
def main():

    # INITIALIZE

    # User-defined parameters
    nr = 80
    nc = 41
    plot_interval = 0.25
    run_duration = 5.0
    report_interval = 5.0  # report interval, in real-time seconds
    infection_rate = 8.0
    outfilename = 'sirmodel'+str(int(infection_rate))+'ir'

    # Remember the clock time, and calculate when we next want to report
    # progress.
    current_real_time = time.time()
    next_report = current_real_time + report_interval

    time_slice = 0

    # Create a grid
    hmg = HexModelGrid(nr, nc, 1.0)

    # Set up the states and pair transitions.
    # Transition data here represent the disease status of a population.
    ns_dict = { 0 : 'susceptible', 1 : 'infectious', 2: 'recovered' }
    xn_list = setup_transition_list(infection_rate)

    # Create data and initialize values
    node_state_grid = hmg.add_zeros('node', 'node_state_grid')
    wid = nc-1.0
    ht = (nr-1.0)*0.866
    is_middle_rows = logical_and(hmg.node_y>=0.4*ht, hmg.node_y<=0.5*ht)
    is_middle_cols = logical_and(hmg.node_x>=0.4*wid, hmg.node_x<=0.6*wid)
    middle_area = where(logical_and(is_middle_rows, is_middle_cols))[0]
    node_state_grid[middle_area] = 1
    node_state_grid[0] = 2  # to force full color range, set lower left to 'recovered'

    # Create the CA model
    ca = HexCTS(hmg, ns_dict, xn_list, node_state_grid)

    # Set up the color map
    import matplotlib
    susceptible_color = (0.5, 0.5, 0.5)  # gray
    infectious_color = (0.5, 0.0, 0.0)  # dark red
    recovered_color = (0.0, 0.0, 1.0)  # blue
    clist = [susceptible_color, infectious_color, recovered_color]
    my_cmap = matplotlib.colors.ListedColormap(clist)

    # Create a CAPlotter object for handling screen display
    ca_plotter = CAPlotter(ca, cmap=my_cmap)

    # Plot the initial grid
    ca_plotter.update_plot()
    pylab.axis('off')
    savename = outfilename+'0'
    pylab.savefig(savename+'.pdf', format='pdf')

    # RUN
    current_time = 0.0
    while current_time < run_duration:

        # Once in a while, print out simulation and real time to let the user
        # know that the sim is running ok
        current_real_time = time.time()
        if current_real_time >= next_report:
            print('Current sim time',current_time,'(',100*current_time/run_duration,'%)')
            next_report = current_real_time + report_interval

        # Run the model forward in time until the next output step
        ca.run(current_time+plot_interval, ca.node_state,
               plot_each_transition=False) #True, plotter=ca_plotter)
        current_time += plot_interval

        # Plot the current grid
        ca_plotter.update_plot()
        pylab.axis('off')
        time_slice += 1
        savename = outfilename+str(time_slice)
        pylab.savefig(savename+'.pdf', format='pdf')

    # FINALIZE

    # Plot
    ca_plotter.finalize()
Exemple #7
0
def main():

    # INITIALIZE

    # User-defined parameters
    nr = 80
    nc = 41
    plot_interval = 0.25
    run_duration = 5.0
    report_interval = 5.0  # report interval, in real-time seconds
    infection_rate = 8.0
    outfilename = 'sirmodel' + str(int(infection_rate)) + 'ir'

    # Remember the clock time, and calculate when we next want to report
    # progress.
    current_real_time = time.time()
    next_report = current_real_time + report_interval

    time_slice = 0

    # Create a grid
    hmg = HexModelGrid(nr, nc, 1.0)

    # Set up the states and pair transitions.
    # Transition data here represent the disease status of a population.
    ns_dict = {0: 'susceptible', 1: 'infectious', 2: 'recovered'}
    xn_list = setup_transition_list(infection_rate)

    # Create data and initialize values
    node_state_grid = hmg.add_zeros('node', 'node_state_grid')
    wid = nc - 1.0
    ht = (nr - 1.0) * 0.866
    is_middle_rows = logical_and(hmg.node_y >= 0.4 * ht,
                                 hmg.node_y <= 0.5 * ht)
    is_middle_cols = logical_and(hmg.node_x >= 0.4 * wid,
                                 hmg.node_x <= 0.6 * wid)
    middle_area = where(logical_and(is_middle_rows, is_middle_cols))[0]
    node_state_grid[middle_area] = 1
    node_state_grid[
        0] = 2  # to force full color range, set lower left to 'recovered'

    # Create the CA model
    ca = HexCTS(hmg, ns_dict, xn_list, node_state_grid)

    # Set up the color map
    import matplotlib
    susceptible_color = (0.5, 0.5, 0.5)  # gray
    infectious_color = (0.5, 0.0, 0.0)  # dark red
    recovered_color = (0.0, 0.0, 1.0)  # blue
    clist = [susceptible_color, infectious_color, recovered_color]
    my_cmap = matplotlib.colors.ListedColormap(clist)

    # Create a CAPlotter object for handling screen display
    ca_plotter = CAPlotter(ca, cmap=my_cmap)

    # Plot the initial grid
    ca_plotter.update_plot()
    pylab.axis('off')
    savename = outfilename + '0'
    pylab.savefig(savename + '.pdf', format='pdf')

    # RUN
    current_time = 0.0
    while current_time < run_duration:

        # Once in a while, print out simulation and real time to let the user
        # know that the sim is running ok
        current_real_time = time.time()
        if current_real_time >= next_report:
            print('Current sim time', current_time, '(',
                  100 * current_time / run_duration, '%)')
            next_report = current_real_time + report_interval

        # Run the model forward in time until the next output step
        ca.run(current_time + plot_interval,
               ca.node_state,
               plot_each_transition=False)  #True, plotter=ca_plotter)
        current_time += plot_interval

        # Plot the current grid
        ca_plotter.update_plot()
        pylab.axis('off')
        time_slice += 1
        savename = outfilename + str(time_slice)
        pylab.savefig(savename + '.pdf', format='pdf')

    # FINALIZE

    # Plot
    ca_plotter.finalize()