def test_values(self):
     dtype = [('iso3','|S16'),('year','<i4'),('y','<f8')]
     self.data = utilities.read('test_read.csv', dtype)
     
     self.assertTrue((self.data['iso3'] == ['USA','USA','USA']).all() == True)
     self.assertTrue((self.data['year'] == range(1970,1973)).all() == True)
     self.assertTrue((self.data['y'][0:2] == [0,1]).all() == True)
     # test for nan
     self.assertTrue((self.data['y'][2] != self.data['y'][2]))
示例#2
0
def Mon_Jasnow(sub_dir):
    Ns = read(sub_dir, "sizes")
    Ts = read(sub_dir, "temps")
    name = "tau_MJ"
    tau = read(sub_dir, name)

    fig, ax = plt.subplots(figsize=(6, 4))
    ax.set_ylabel("$\\tau/[J]$")
    ax.set_xlabel("$T/[J]$")
    for i, N in enumerate(Ns):
        ax.plot(Ts, tau[i], "--.", label="$N={}$".format(int(N)))
    ax.plot([Tc, Tc], ax.get_ylim(), "k--", label="$T_c$")
    ax.legend()
    ax.grid(True)

    plt.tight_layout()
    plt.savefig("figs/" + sub_dir + name + ".png", dpi=300)
    plt.close(fig)
def evaluate_estimates(out_file, key, est_dir, est_y, gold_standard_file, y):
    """
    Evaluate estimates stored in a directory of csvs against the gold standard.

    Parameters
    ----------
    out_file : string
        A path to a csv in which to store summary error metrics
    key : list of strings
        A list of strings that correspond to columns in the estimates files and in the gold standard files
        to serve as the key in merging these files. If evaluates_estimates is being run from
        the command line, then key must be enclosed in double quotes (e.g. \"['iso3','year']\")
    est_dir : string
        The path to a directory with the csvs of the estimates. All csvs in this directory will be assumed to contain
        estimates. The path should end with a /
    est_y : string
        The name of the column in the estimate files that holds the predictions from the model
    y : string
        The name of the column in the gold standard file that holds the response variable. This should also
        be the name of the column in the estimates files that holds the knocked out and noised response variable.
    gold_standard_file : string
        The path to the gold standard file

    Notes
    -----
    see parse_filename for a guide to the naming convention of the predicted response variables
    """

    model_design_vars = {}

    data = utilities.read(gold_standard_file)

    data = utilities.add_unique_id(data, key, 'unique_id_for_join_by')
    
    files = os.listdir(est_dir)
    for file in files:        
        file_key = parse_filename(file)
                  
        path = est_dir + file
        new_data = utilities.read(path)

        # rename variable
        names = []
        for name in new_data.dtype.names:
            if name == est_y:
                est_y_name = est_y + '_' + str(file_key['model']) + '_' + str(file_key['design']) + '_' + str(file_key['rep'])
                names.append(est_y_name)
            elif name == y:
                y_name = y + '_' + str(file_key['model']) + '_' + str(file_key['design']) + '_' + str(file_key['rep'])
                names.append(y_name)
            else:
                names.append(name)
        new_data.dtype.names = tuple(names)

        # collect up variables corresponding to a certain model and design
        if model_design_vars.has_key(file_key['model']) == False:
            model_design_vars[file_key['model']] = {}

        if model_design_vars[file_key['model']].has_key(file_key['design']) == False:
            model_design_vars[file_key['model']][file_key['design']] = []

        model_design_vars[file_key['model']][file_key['design']].append(est_y_name)

        new_data = utilities.add_unique_id(new_data, key, 'unique_id_for_join_by')
        new_data = new_data[['unique_id_for_join_by', est_y_name, y_name]]
        
        # http://stackoverflow.com/questions/2774949/merging-indexed-array-in-python
        data = numpy.lib.recfunctions.join_by('unique_id_for_join_by', data, new_data)

    # this would write a file with the gold standard and all the predictions
    #utilities.write(out_predictions_file, data)

    data = numpy.lib.recfunctions.drop_fields(data, 'unique_id_for_join_by')

    model_design_errors = {}
    for model in model_design_vars.keys():
        model_design_errors[model] = {}
        for design in model_design_vars[model].keys():
            model_design_errors[model][design] = {}
            truth = []
            obs = []
            for var in model_design_vars[model][design]:
                y_var = var.replace(est_y, y)
                for i in range(0, len(data[y])):
                    if utilities.is_nan(data[y_var][i]) == True:
                        pdb.set_trace()
                        truth.append(data[y][i])
                        obs.append(data[var][i])
                
            truth = np.array(truth)
            obs = np.array(obs)

            model_design_errors[model][design] = {}
            errors = errormetrics.get_error_metrics()
            for error in errors:
                error_str = 'errormetrics.' + error + '()'
                error_class = eval(error_str)
                model_design_errors[model][design][error] = error_class.calc_error(truth, obs, True)
                
    errors = [] 
    for model in model_design_errors.keys():
        for design in model_design_errors[model].keys():
            for error in model_design_errors[model][design].keys():
                errors.append(error)
    errors = np.unique(errors)

    writer = csv.writer(open(out_file, 'wb'))
    fieldnames = ['model','design'] + errors.tolist()
    writer.writerow(fieldnames)
    for model in model_design_errors.keys():
        for design in model_design_errors[model].keys():
            row = [model, design]
            for error in errors:
                if model_design_errors[model][design].has_key(error) == True:
                    row.append(model_design_errors[model][design][error])
                else:
                    row.append('')
                    
            writer.writerow(row)
    writer = []
def simulate_data(out_dir, y, se, gold_standard_file, design_file):
    """
    Simulate data by knocking out and adding noise to a gold standard file. How data is knocked out and
    how noise is added is determined by parameters specified in the design file.

    Parameters
    ----------
    out_dir : string
        The path to a directory in which to output the noisy and knocked out data. The path should end with a /
    y : string
        The column name in the gold standard file corresponding to the response to be knocked out and noised up.
    se : string
        The column name in the gold standard file corresponding to the standard error of the response.
        If se == '', then a se variable will be created named 'se' and filled with 0's. If noise is added, then
        this se variable will be set to the standard error of the noise.
    gold_standard_file : string
        The path to a csv.
    design_file : string
        The path to a csv. If a knock out test is to be performed, there must be a column called knockerouters.
        If noise is to be added, there must be a column called noisers. If there is a column called rep, then
        each test will be repeated rep times. If no such column is provided, each test will only be run once.
        All other columns are parameters for the knockerouter function or the noiser function. These two functions
        must not not share column names for parameters. All column entries (not the header) must be enclosed in
        double quotes. A string will be enclosed in single quotes and then double quotes (e.g. \"'USA'\"), whereas
        a number or an array will be enclosed only in double quotes (e.g. \"2\", \"[1,2,3]\").
        
    See Also
    --------
    utilities.read
    """

    if os.path.isdir(out_dir) == False:
        os.mkdir(out_dir)

    gold_data = utilities.read(gold_standard_file)

    if se == "":
        gold_data = numpy.lib.recfunctions.append_fields(gold_data, "se", [0] * len(gold_data), "<f4")
        se = "se"

    reader = csv.reader(open(design_file))

    on_header = True
    index = 0
    rep_index = np.nan
    for row in reader:
        if on_header == True:
            header = row
            on_header = False

            for i in range(0, len(header)):
                if header == "rep":
                    rep_index = i
        else:
            if utilities.is_nan(rep_index) == True:
                reps = 1
            else:
                reps = int(row[rep_index])

            for i in range(0, reps):
                data = gold_data

                row_dict = {}
                for j, name in enumerate(header):
                    row_j = eval(row[j])

                    row_dict[name] = row_j

                for func_collection in ["knockerouters", "noisers", "biasers"]:
                    if row_dict.has_key(func_collection) == True:
                        fun_str = func_collection + "." + row_dict[func_collection]
                        if func_collection == "biasers":
                            fun_str = fun_str + "(data, y"
                        else:
                            fun_str = fun_str + "(data, y, se"

                        get_args_str = "inspect.getargspec(" + func_collection + "." + row_dict[func_collection] + ")"

                        args = eval(get_args_str)[0]
                        for arg in args:
                            if (arg in ["data", "y", "se"]) == False:
                                fun_str = fun_str + ", row_dict['" + arg + "']"
                        fun_str = fun_str + ")"

                        data = eval(fun_str)

                gold_standard_file = gold_standard_file.split("/")
                gold_standard_file = gold_standard_file[len(gold_standard_file) - 1]

                new_file = (
                    out_dir + "sim_" + gold_standard_file.replace(".csv", "") + "_" + str(index) + "_" + str(i) + ".csv"
                )

                utilities.write(new_file, data)
                index = index + 1