Beispiel #1
0
def generate_test_ukf(n, prop, start_model):
    """ generate a seeded ukf_model for testing
    
    """
    test_model = deepcopy(start_model)
    n = model_params["pop_total"]
    model_params, ukf_params = omission_params(n, prop)
    u = ukf_ss(model_params, ukf_params, test_model)
    u.main()

    obs, preds, truths, nan_array = u.data_parser()

    return u, obs, preds, truths
Beispiel #2
0
def ex3_main(n, recall, do_pickle, source, destination):
    """main function to run experiment 1
    
    - build model and ukf dictionary parameters based on n and prop
    - initiate Model and ukf_ss based on new dictionaries
    - run ABM with filtering on top
    - make plots using finished run data
    
    Parameters
    ------
    n, prop : float
        `n` population and proportion observed 0<=`prop`<=1
    
    recall, do_pickle : bool
        `recall` a previous run or  `do_pickle` pickle a new one?
        
    pickle_source : str
        `pickle_source` where to load/save any pickles.
    """

    if not recall:
        model_params = configs.model_params
        ukf_params = configs.ukf_params
        model_params, ukf_params, base_model = ex3_params(
            n, model_params, ukf_params)
        base_models = []
        for i in range(int((4 * n) + 1)):
            base_models.append(deepcopy(base_model))

        print(f"Population: {n}")
        u = ukf_ss(model_params, ukf_params, base_model, base_models)
        u.main()
        pickle_main(ukf_params["file_name"], pickle_source, do_pickle, u)

    else:
        "if recalling, load a pickle."
        f_name = ex3_pickle_name(n)

        "try loading class_dicts first. If no dict then class instance."
        try:
            u = pickle_main("dict_" + f_name, source, do_pickle)
        except:
            u = pickle_main(f_name, source, do_pickle)

        model_params, ukf_params = u.model_params, u.ukf_params

    ex3_plots(u, destination, "ukf_", True, False)

    return u
Beispiel #3
0
def ex2_main(n, bin_size, recall, do_pickle, source, destination):
    """main function to run experiment 2
    
    - build model and ukf dictionary parameters based on n and bin_size
    - initiate Model and ukf_ss based on new dictionaries
    - run ABM with filtering on top
    - make plots using finished run data
    
    Parameters
    ------
    n, bin_size : float
        `n` population and aggregate grid square size `bin_size`
    
    recall, do_pickle : bool
        `recall` a previous run or  `do_pickle` pickle a new one?
        
    source, destination : str
        `source` where to load/save any pickles and the `destination` of 
        any plots
    """

    if not recall:
        model_params = configs.model_params
        ukf_params = configs.ukf_params

        model_params, ukf_params, base_model = aggregate_params(
            n, bin_size, model_params, ukf_params)

        print(f"Population: {n}")
        print(f"Square grid size: {bin_size}")

        u = ukf_ss(model_params, ukf_params, base_model)
        u.main()
        pickle_main(ukf_params["file_name"], pickle_source, do_pickle, u)

    else:
        f_name = ex2_pickle_name(n, bin_size)
        try:
            u = pickle_main("dict_" + f_name, source, do_pickle)
        except:
            print(f_name)
            print("dictionary not found. trying to load class")
            u = pickle_main(f_name, source, do_pickle)

    ex2_plots(u, destination, "agg_ukf_", True, True)
    return u
Beispiel #4
0
def ex0_main(n, noise, sampling_rate):
    """ main ex0 function 
    
    - assign population size, observation noise, and sampling rate
    - build ukf and model parameter dictionariues
    - build base model and init ukf_ss class
    - run stationsim with ukf filtering
    """

    model_params = default_ukf_configs.model_params
    ukf_params = default_ukf_configs.ukf_params

    model_params, ukf_params, base_model = ex0_params(n, noise, sampling_rate,
                                                      model_params, ukf_params)
    print(model_params)
    print(ukf_params)

    u = ukf_ss(model_params, ukf_params, base_model)
    u.main()
    ex0_save(u, "../ukf_results/", ukf_params["file_name"])
Beispiel #5
0
def ex2_main(n, bin_size, recall, do_pickle, source, destination):
    """main function to run experiment 2
    
    - build model and ukf dictionary parameters based on n and bin_size
    - initiate Model and ukf_ss based on new dictionaries
    - run ABM with filtering on top
    - make plots using finished run data
    
    Parameters
    ------
    n, bin_size : float
        `n` population and aggregate grid square size `bin_size`
    
    recall, do_pickle : bool
        `recall` a previous run or  `do_pickle` pickle a new one?
        
    source, destination : str
        `source` where to load/save any pickles and the `destination` of 
        any plots
    """

    if not recall:

        model_params = configs.model_params
        model_params["random_seed"] = 15
        ukf_params = configs.ukf_params

        model_params, ukf_params, base_model = aggregate_params(
            n, bin_size, model_params, ukf_params)

        batch = False
        ukf_params["batch"] = batch
        if batch:
            print(
                "WARNING: Batch set to true and will not generate a random model each time."
            )
            try:
                seed = 50
                file_name = f"batch_test_{n}_{seed}.pkl"
                batch_truths, batch_start_model = batch_load(file_name)
                print("batch data found.")
            except:
                print("no model found. generating one with given seed")
                file_name = f"batch_test_{n}_{seed}.pkl"
                batch_save(model_params, n, seed)
                batch_truths, batch_start_model = batch_load(file_name)
                print("new model generated.")
                new_seed = int.from_bytes(
                    os.urandom(4),
                    byteorder='little') if seed == None else seed
                np.random.seed(new_seed)

            base_model = batch_start_model

        print(f"Population: {n}")
        print(f"Square grid size: {bin_size}")

        u = ukf_ss(model_params, ukf_params, base_model)
        u.main()
        if do_pickle:
            pickle_main(ukf_params["file_name"], pickle_source, do_pickle, u)

    else:
        f_name = ex2_pickle_name(n, bin_size)
        try:
            u = pickle_main("dict_" + f_name, source, do_pickle)
        except:
            print(f_name)
            print("dictionary not found. trying to load class")
            u = pickle_main(f_name, source, do_pickle)

    ex2_plots(u, destination, "agg_ukf_", True, False)
    return u
Beispiel #6
0
def main(ex_input,ex_save=None, test = False):
    
    
    """main function for running ukf experiments in arc.
    
    Runs an instance of ukf_ss for some experiment and associated parameters.
    Either pickles the run or saves some user defined aspect of said run.
    
    - define some input experiment for arc
    - update model_params and ukf_params dictionaries for said experiment
    - run ukf_ss with said parameters
    - pickle or save metrics when run finishes.
    
    Parameters
    ------
    ex_input : func
        `ex_input` some experiment input that updates the default model_params
        and ukf_params dicitonaries with items needed for filter to run given
        experiment.
        
    ex_save : func
        `ex_save` if we want to pickle the whole class instance set this to none.
        Else provides some alternate function that saves something else. 
        Experiment 0 has a funciton ex0 save which saves a numpy array of 
        error metric instead
    
    """

    if not test:
        __spec__ = None

        if len(sys.argv) != 2:
            print("I need an integer to tell me which experiment to run. \n\t"
                 "Usage: python run_pf <N>")
            sys.exit(1)
    
    model_params = configs.model_params
    ukf_params = configs.ukf_params
    
    model_params, ukf_params, base_model = ex_input(model_params, ukf_params, test)
    
    print("UKF params: " + str(ukf_params))
    print("Model params: " + str(model_params))
    
    #init and run ukf
    u = ukf_ss(model_params, ukf_params, base_model)
    u.main()
        
    if ukf_params["do_pickle"]:
        #store final class instance via pickle
        f_name = ukf_params["file_name"]
        pickler(u, "results/", f_name)
    
    else:
        #alternatively save whatever necessary using some ex_save function.
        # requires, the instance and some directory + name to save to.
        f_name = ukf_params["f_name"]
        ex_save(u, "results/", ukf_params["f_name"])

    if test:
        print(f"Test successful. Deleting the saved test file : {f_name}")
        remove("results/" + ukf_params["full_file_name"])
    marker_attributes = {
        "markers": {
            -1: "o"
        },
        "colours": {
            -1: "black"
        },
        "labels": {
            -1: "Pseudo-Truths"
        }
    }

    "dummy ukf params and class for plots"
    ukf_params = {}
    u = ukf_ss(model_params, ukf_params, model)

    plts = ukf_plots(u, "../plots/", "crowd_test_", False, True,
                     marker_attributes)

    truths = np.array(model.history_state).flatten().reshape(
        (model.step_id, 2 * model.pop_total))

    nan_array = np.ones(shape=truths.shape) * np.nan
    for i, agent in enumerate(model.agents):
        "find which rows are  NOT (None, None). Store in index. "
        array = np.array(agent.history_locations)
        index = ~np.equal(array, None)[:, 0]
        "set anything in index to 1. I.E which agents are still in model."
        nan_array[index, 2 * i:(2 * i) + 2] = 1
Beispiel #8
0
def ex4_pickle_name(n, cameras):
    pass


if __name__ == "__main__":

    model_params = configs.model_params
    ukf_params = configs.ukf_params
    n = 5

    camera_poles = [np.array([10, 0]), np.array([150, 0])]
    camera_centres = [np.array([0, 100]), np.array([150, 200])]
    camera_arcs = [0.125] * 2
    boundary = boundary_Polygon(model_params["width"], model_params["height"])

    cameras = []
    for i in range(len(camera_poles)):
        pole = camera_poles[i]
        centre = camera_centres[i]
        arc = camera_arcs[i]
        cameras.append(camera_Sensor(pole, centre, arc, boundary))

    model_params, ukf_params, base_model = cone_params(n, cameras,
                                                       model_params,
                                                       ukf_params)

    for _ in range(5):
        base_model.step()
    u = ukf_ss(model_params, ukf_params, base_model)
    u.main()