def main(argv):
    current_fit_number, snr, project, existing_fits = (
        int(argv[1]), float(argv[2]), argv[3], int(argv[4]))

    noise_seed = current_fit_number + existing_fits

    if not os.path.isdir(os.path.join(project, defaults.RESULTS_DIR)):
        os.mkdir(os.path.join(project, defaults.RESULTS_DIR))

    g_parameters = galfun.GParameters(project)
    image_renderer = galfun.ImageRenderer(pixel_scale=defaults.PIXEL_SCALE,nx=defaults.NX,ny=defaults.NY)
    fish = fisher.Fisher(g_parameters=g_parameters,image_renderer=image_renderer, snr=snr)
    orig_image = deepcopy(fish.image)
    mins = defaults.getMinimums(g_parameters, orig_image)
    maxs = defaults.getMaximums(g_parameters, orig_image)
    init_values = defaults.getInitialValuesFit(g_parameters)
    nfit_params = g_parameters.nfit_params
    noisy_image, variance_noise = galfun.addNoise(orig_image, snr, noise_seed)

    fit_params = lmfit.Parameters()
    for param in g_parameters.fit_params:
        fit_params.add(param,
                       value=init_values[param],
                       min=mins[param],
                       max=maxs[param])

    results = lmfit.minimize(objFunc, fit_params, kws=dict(image_renderer=image_renderer,
                                                           data=noisy_image,
                                                           variance_noise=(variance_noise),
                                                           **nfit_params))
    

    filename = ''.join([defaults.RESULTS_DIR, str(noise_seed), '.csv'])
    result_filename = os.path.join(project, defaults.RESULTS_DIR, filename)

    # write results of fits into a file,
    with open(result_filename, 'w') as csvfile:
        row_to_write = fit_params.valuesdict()
        row_to_write['chi2'] = results.chisqr
        row_to_write['success'] = results.success
        row_to_write['errorbars'] = results.errorbars
        row_to_write['nfev'] = results.nfev
        row_to_write['nvarys'] = results.nvarys
        row_to_write['ndata'] = results.ndata
        row_to_write['nfree'] = results.nfree
        row_to_write['redchi'] = results.redchi
        writer = csv.DictWriter(csvfile, fieldnames=row_to_write.keys())
        writer.writeheader()
        writer.writerow(row_to_write)
def read_results(project,g_parameters, fish):
    orig_image = fish.image
    mins = defaults.getMinimums(g_parameters, orig_image)
    maxs = defaults.getMaximums(g_parameters, orig_image)
    
    residuals = {}
    pulls = {}
    redchis = [] #list containing values of reduced chi2 for each fit.
    rltsdir = os.path.join(project, defaults.RESULTS_DIR)

    # read results from rltsdir's files.
    for filename in os.listdir(rltsdir):
        with open(os.path.join(rltsdir, filename)) as csvfile:
            reader = csv.DictReader(csvfile)
            for i,row in enumerate(reader):
                print i,row
                redchis.append(float(row['redchi']))
                for param in g_parameters.fit_params:
                    if param not in residuals:
                        residuals[param] = []
                    if param not in pulls:
                        pulls[param] = []
                    residual = (float(row[param]) -
                                float(g_parameters.params[param]))
                    pull = (residual /
                            math.sqrt(fish.covariance_matrix[param, param]))

                    residuals[param].append(residual)
                    pulls[param].append(pull)

    biases = {param: np.mean(residuals[param]) for param in residuals}
    pull_means = {param: np.mean(pulls[param]) for param in residuals}
    res_stds = {param: np.std(residuals[param]) for param in residuals}
    pull_mins = {param: ((mins[param] - float(g_parameters.params[param])) /
                         math.sqrt(fish.covariance_matrix[param, param])) for
                 param in residuals}
    pull_maxs = {param: ((maxs[param] - float(g_parameters.params[param])) /
                         math.sqrt(fish.covariance_matrix[param, param])) for
                 param in residuals}

    return pulls,residuals,biases,pull_means,res_stds,pull_mins,pull_maxs,redchis