예제 #1
0
    def combine_landmarks_sort(self, add_landmark_path):

        origin_landmarks = {
            elem.split('_landmarks.txt')[0]: elem
            for elem in os.listdir(self.input_path) if elem.endswith('.txt')
        }
        add_landmarks = {
            elem.split('_noface')[0]: elem
            for elem in os.listdir(add_landmark_path) if elem.endswith('.txt')
        }
        utility.create_dir(self.output_path)

        for key in add_landmarks.keys():
            if key not in origin_landmarks.keys():
                print("{} is not exists in original list".format(key))
                continue
            add_landmark_file_path = "{}/{}".format(add_landmark_path,
                                                    add_landmarks[key])
            origin_landmarks_file_path = "{}/{}".format(
                self.input_path, origin_landmarks[key])
            origin_data = utility.read_file(origin_landmarks_file_path)
            add_data = utility.read_file(add_landmark_file_path)
            origin_data += add_data
            origin_data = sorted(origin_data)

            #print(key, add_landmarks[key],  origin_landmarks[key])

            dst_combine_landmark_path = '{}/{}_add_landmarks.txt'.format(
                self.output_path, key)
            utility.write_into_file(origin_data, dst_combine_landmark_path)
예제 #2
0
 def save(self,
          name='',
          directory=CONTROLLER_FOLDER,
          screenshot=True,
          **info):
     """
     [CM]- SAVE() Saving out Controller geometry and its relevant info
         :param name:(string) File name
         :param directory:(string) default path to {$MAYA_USER_DIR}/{$CONTROLLER_FOLDER}
         :param screenshot (Boolean) if saving the screenshot to dist
         :param info: (Dict) extra properties to burn to meta data
         :return:
     """
     # construct the file path for geo and json
     geo_path = util.join_file_dir(directory, name, 'ma')
     info_path = util.join_file_dir(directory, name, 'json')
     # create the directory folder to save
     util.create_dir(directory)
     # save geometry(prompt window appear if no selection)
     util.save_maya_file(geo_path)
     # save screenshot
     if screenshot:
         info['screenshot'] = util.save_screenshot(name, directory)
     # store Meta-data block to CM's dictionary(memory)
     info['name'] = name
     info['path'] = geo_path
     # append other information down here
     self[name] = info
     # [LAST STEP] save out info-block to json
     util.save_json_file(info, info_path)
    def select_one_image_from_file(self, input_file, output_file, select_num):

        if not os.path.exists(input_file):
            print "{} is not exists".format(input_file)
            return

        utility.create_dir(output_file)
        counter = 1
        for root_path, folder_path, filenames in os.walk(input_file):

            if len(filenames) > 0:
                if counter > select_num:
                    break

                if filenames[0].endswith('.jpg') or filenames[0].endswith('.png') or   \
                    filenames[0].endswith('.bmp') or  filenames[0].endswith('.JPG'):

                    image_path = '{}/{}'.format(root_path, filenames[0])
                    dst_image_name = str(counter).zfill(5)
                    dst_path = '{}/{}.jpg'.format(output_file, dst_image_name)
                    shutil.copy(image_path, dst_path)

                    sys.stdout.write('{}/{}\r'.format(counter, select_num))
                    sys.stdout.flush()
                    counter += 1
예제 #4
0
    def __init__(self, input_folder_path="", dst_folder_path=""):

        if dst_folder_path != "":
            utility.create_dir(dst_folder_path)
        input_folder_path = input_folder_path.rstrip('/')

        self.input_folder_path = input_folder_path
        self.dst_folder_path = dst_folder_path
예제 #5
0
파일: backup.py 프로젝트: zhongyn/newtest
def backup_rails_database():
    db_info = get_rails_db_info()
    create_dir(env.backups_path, env.release)
    with hide('running', 'stdout', 'stderr'):
        run("mysqldump -h %s -u %s -p%s %s > %s/%s/%s.dump" \
             % (db_info.get('host'), db_info.get('user'), db_info.get('password'), \
                db_info.get('database'), env.backups_path, env.release, env.app_name))
        puts("mysqldump -h %s -u %s -p<PASSWORD> %s > %s/%s/%s.dump" \
             % (db_info.get('host'), db_info.get('user'), db_info.get('database'), env.backups_path, env.release, env.app_name))
예제 #6
0
    def create_work_dir(self):
        self.logger.info("===== SETUP INITIALIZATION =====")
        engine_conf = conf.get_engine_conf()
        if engine_conf is None:
            return
        data_dir = engine_conf["network_data_dir"]
        utility.remove_dir(data_dir)
        utility.create_dir(data_dir)

        for client in self.clients:
            client.create_work_dir(data_dir)
    def extract_noface_image(self, image_list, root_path, dst_path):

        utility.create_dir(dst_path)
        f = open(image_list, 'r')
        data = f.read().splitlines()
        f.close()

        for index, elem in enumerate(data):
            utility.show_process_percentage(index, len(data), 50)
            srcimage_path = '{}/{}'.format(root_path, elem)
            if os.path.isfile(srcimage_path):
                dst_move_path = '{}/{}'.format(dst_path, elem.split('/')[-1])
                shutil.move(srcimage_path, dst_move_path)
 def rename_image_names(self, input_file, output_file, image_prefix):
     if not os.path.exists(input_file):
         print "{} is not exists".format(input_file)
         return
     utility.create_dir(output_file)
     counter = 1
     for root_path, folder_path, filenames in os.walk(input_file):
         for elem in filenames:
             srcImage_path = '{}/{}'.format(root_path, elem)
             dst_name = str(counter).zfill(5)
             dst_path = '{}/{}-{}.jpg'.format(output_file, image_prefix,
                                              dst_name)
             shutil.copy(srcImage_path, dst_path)
             counter += 1
     print("Done!!")
예제 #9
0
def train_model(model, train_dataset, validation_dataset, test_dataset,
                model_name, base_path):
    """

    :param model:
    :param train_dataset:
    :param validation_dataset:
    :param model_name: name of the base model
    :return:
    """
    EPOCHS = 4
    steps_p_epoch = 5  # train_dataset.samples // train_dataset.batch_size +1
    validation_steps = 5  # validation_dataset.samples // validation_dataset.batch_size +1

    time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    print("Start at ", time)

    # Setup folder for evaluation process logs etc
    parent_dir = create_dir(base_path, time + "_" + model_name)

    callbacks = generate_callbacks(parent_dir)
    history = model.fit(train_dataset,
                        epochs=EPOCHS,
                        steps_per_epoch=steps_p_epoch,
                        validation_data=validation_dataset,
                        validation_steps=validation_steps,
                        callbacks=callbacks)

    time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    print("Finished Training at ", time)

    evaluate_model(model, test_dataset, parent_dir, history)
    time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    print("Finished Evaluation at ", time)
예제 #10
0
 def test(self):
     self.load()
     self.model.eval()
     print(len(self.loader_test))
     utility.create_dir('./result/{}'.format(self.args.file_name))
     for _, (lr, gt, file_name) in enumerate(self.loader_test):
         lr, _ = self.prepare(lr, gt)
         with torch.no_grad():
             output = self.model(lr)
         for _num in range(output.shape[0]):
             tmp = utility.quantize(output[_num])
             imageio.imwrite(
                 './result/{}/'.format(self.args.file_name) +
                 str(file_name[_num].numpy()) + '.png', np.array(tmp[0]))
             print('Img: {} saved to ./result/{}/...'.format(
                 str(file_name[_num].numpy()) + '.png',
                 self.args.file_name))
예제 #11
0
	def sample(self, show=True):
		print("TESTING START...")
		input_rgb = next(self.sample_generator)
		feed_dic = {self.input_rgb: input_rgb}
		outputs_path = create_dir(self.options.checkpoints_path + '/output')
		step, rate = self.sess.run([self.global_step, self.learning_rate])
		fake_image, input_gray = self.sess.run([self.sampler, self.input_gray], feed_dict=feed_dic)
		fake_image = postprocess(tf.convert_to_tensor(fake_image), colorspace_in='LAB', colorspace_out=COLORSPACE_RGB)
		stitch_images(input_gray, input_rgb, fake_image.eval(),outputs_path,self.options.dataset + "_" + str(step).zfill(5))
    def select_certain_image_from_file(self, input_file, output_file,
                                       select_image, select_num):

        if not os.path.exists(input_file):
            print "{} is not exists".format(input_file)
            return

        utility.create_dir(output_file)
        counter = 1
        for root_path, folder_path, filenames in os.walk(input_file):

            for elem in filenames:

                if elem == select_image:

                    image_path = '{}/{}'.format(root_path, elem)
                    dst_image_name = str(counter).zfill(5)
                    dst_path = '{}/{}d.jpg'.format(output_file, dst_image_name)
                    shutil.copy(image_path, dst_path)

                    sys.stdout.write('{}/{}\r'.format(counter, select_num))
                    sys.stdout.flush()
                    counter += 1
예제 #13
0
def trig_check2(trignum, **kwargs):

    savepath = kwargs.get('savepath', False)

    import numpy as np
    import matplotlib.pyplot as plt
    import gen_reader as gr
    import utility as ut

    trigdat = gr.wf_reader('/home/james/anaconda3/data/' + str(date) +
                           '/lv/trig_' + str(trignum) + '.txt')

    # Calculate dt and find the accelerometer level during trigger window
    acc_sig, acc_sig_1 = [], []
    j = 0
    for i in range(np.shape(trigdat)[0]):
        if trigdat[i, 2] == 0:
            j = 0
        if trigdat[i, 2] == 1:
            if j == 0:
                acc_sig.append(np.mean(acc_sig_1))
            acc_sig_1.append(trigdat[i, 1])
            j += 1

    plt.figure('trig2')
    plt.clf()
    plt.plot(acc_sig[1:], 'bo', markersize=3)
    plt.title(
        str(date) + ' run' + str(trignum) +
        ' Average Trigger Signal while Laser Shutter Open')
    plt.xlabel('Trigger Number')
    plt.ylabel('Accelerometer Signal (V)')
    if savepath != False:
        ut.create_dir(savepath)
        plt.savefig(savepath + 'trig_' + str(trignum) + '_acc_sig.png')

    return acc_sig[1:]
예제 #14
0
def create_controller_folder(directory='', o=False):
    """
    [Create/Set Controller Folder] Create a new Controller Folder, if directory not specified,
    {$MAYA_USER_DIR}/{$CONTROLLER_FOLDER} will be set as default. Use o=True flag to open up
    the controller folder in file explorer
        :param directory: (String) A directory to specify, non will create
        :param o: (Boolean) if Open this directory in file explorer
    """
    # Controller folder variable could be altered: use global keyword to grant access
    global CONTROLLER_FOLDER
    if not directory:
        directory = CONTROLLER_FOLDER
    else:
        CONTROLLER_FOLDER = directory
    if util.create_dir(directory):
        print("[CONTROLLER FOLDER] -> Created path: %s" % directory)
    else:
        print("[CONTROLLER FOLDER] -> File Path Exists: %s" % directory)

    # with -o flag on, open up the folder in file explorer
    if o:
        print("[CONTROLLER FOLDER] -> Open=True")
        util.open_folder(directory)
예제 #15
0
def initialize():
    # If no environment is set get out of here
    abort_if_no_environment()

    # Ensure the releases directory exists
    if (not exists(env.releases_path)):
        with cd (env.path):
            run("mkdir releases")

    # Ensure the shared directory exists
    if (not exists(env.shared_path)):
        create_dir(env.path, env.shared_directory_name)
        create_dir(env.path, "%s/%s" % (env.shared_directory_name, env.shared_config_directory_name))
        create_dir(env.path, env.backups_directory_name)
        print green("Application directories set up at %s.\nYou can deploy the application using fab to:%s deploy." % (env.path, env.deploy_to))
        if is_rails_project():
            create_dir(env.path, "%s/%s" % (env.shared_directory_name, env.shared_bundle_directory_name))
            create_dir(env.path, "%s/%s" % (env.shared_directory_name, env.shared_tmp_directory_name))
            create_dir(env.path, "%s/%s" % (env.shared_directory_name, env.shared_logs_directory_name))
            run ("touch %s/%s/%s/production.log" %(env.path, env.shared_directory_name, env.shared_logs_directory_name))
            print yellow("Upload database.yml and other .yml files to %s/%s/%s." % (env.path, env.shared_directory_name, env.shared_config_directory_name))
예제 #16
0
def beam_profile(maindir, dx_in, imsave, **kwargs):

    # Define Keyword Arguments
    z_units = kwargs.get('z_units', 'standard')
    data_units = kwargs.get('data_units', 'standard')
    afters = kwargs.get('after', False)
    param_guess = kwargs.get('p0', 'find')
    param_guess2 = kwargs.get('p0_waist', 'find')
    zvals = kwargs.get('zvals', 'default')
    fitlim = kwargs.get('fitlim', 'full')
    stages = kwargs.get('stage_type', 'auto')

    # Import Modules
    import numpy as np
    import matplotlib.pyplot as plt
    import math
    from scipy.special import erf
    from scipy.optimize import curve_fit
    import pylab
    import os
    import utility as ut
    import gen_reader as gr

    # Create directory for imsave
    ut.create_dir(imsave)

    # Define fit function (erf for low to high power)
    def fit_erf(x, a, x_0, w):
        return (a / 2.) * (1 + erf((np.sqrt(2) * (x - x_0)) / w))

    # Get the files in the directory and remove '.DS_Store' if it exists
    filedirs = os.listdir(maindir)
    filedirs.sort()

    # If all dx are the same
    if len(dx_in) == len(filedirs):
        dx = dx_in
    else:
        dx = np.zeros((len(filedirs), ), dtype=float)
        dx[:] = dx_in

    # Fit the data to get spot size for each z-position
    beam_width = np.zeros((len(filedirs), ), dtype=float)
    weights = np.zeros((len(filedirs), ), dtype=float)
    z = np.zeros((len(filedirs), ), dtype=int)
    after = np.zeros((len(filedirs), ), dtype=int)
    for filedir in filedirs:
        if stages == 'manual':
            if afters == True:
                pos, pows, z[filedirs.index(filedir)], after[filedirs.index(
                    filedir)] = pow_ave(maindir + '/' + filedir,
                                        dx[filedirs.index(filedir)],
                                        data_units,
                                        zvals=zvals)
            if afters == False:
                pos, pows, z[filedirs.index(filedir)] = pow_ave(
                    maindir + '/' + filedir,
                    dx[filedirs.index(filedir)],
                    data_units,
                    zvals=zvals)
        if stages == 'auto':
            z[filedirs.index(filedir)] = np.float(filedir[-9:-4])
            matrix = gr.reader(maindir + filedir, header=False)
            pos, pows = (.166E-3 / 25.) * matrix[:, 0], matrix[:, 1]
        if stages == 'profman':
            xstep, z[filedirs.index(
                filedir)] = filedir[-9:-4], filedir[-29:-24]
            matrix = gr.reader(maindir + filedir, header=False)
            pows = matrix[:, 0]
            pos = 1E-3 * np.arange(0, float(xstep) * len(pows), float(xstep))

        # Normalize and reorder the data for low to high power
        pows_norm = pows / np.amax(pows)
        if pows_norm[0] > pows_norm[-1]:
            pows_norm = np.flipud(pows_norm)

        # Get initial parameter guesses
        if param_guess == 'find':
            param_guess = [1, 0, 0]
            # Guess for w
            bnds = ut.bound_finder(pows_norm, [.1, .9])
            param_guess[2] = pos[bnds[1]] - pos[bnds[0]]
            for i in range(len(pows)):
                if pows_norm[i] <= .5:
                    param_guess[1] = pos[i]
                    continue
                else:
                    if pows_norm[i] - .5 >= .5 - pows_norm[i - 1]:
                        param_guess[1] = pos[i - 1]
                        break
                    else:
                        break

        # Do the fit
        if fitlim == 'full':
            posf = pos
            pows_normf = pows_norm
        if fitlim != 'full':
            posf = pos[fitlim[0]:fitlim[1]]
            pows_normf = pows_norm[fitlim[0]:fitlim[1]]
        param, covar = curve_fit(fit_erf, posf, pows_normf, p0=param_guess)
        beam_width[filedirs.index(filedir)] = param[2]
        weights[filedirs.index(filedir)] = 1 / np.sqrt(covar[2, 2])

        # Plot Fit
        x = np.linspace(0, pos[-1], 100)
        fit = fit_erf(x, param[0], param[1], param[2])
        fig = plt.figure('profile')
        plt.clf()
        ax = fig.add_subplot(111)
        plt.plot(pos, pows_norm, 'bo', label='Data')
        plt.plot(x, fit, 'k--', label='Fit')
        plt.axis([0, 1.1 * np.amax(pos), 0, 1.25])
        plt.xlabel('Razor Blade Position (mm)')
        plt.ylabel('Normalized Laser Power')
        plt.legend()
        bbox_props = dict(boxstyle='square', fc='.9', ec='k', alpha=1.0)
        fig_text = 'Spot Size: ' + repr(round(
            1000. * param[2], 2)) + ' +/- ' + repr(
                round(1000 * np.sqrt(covar[2, 2]), 2)) + ' micron'
        #fig_text='Amplitude: '+repr(round(param[0],2))+'\nOffset: '+repr(round(param[1],2))+' mm'+'\nSpot Size: '+repr(1000*round(param[2]),3)+' micron'
        plt.text(.02,
                 .97,
                 fig_text,
                 fontsize=10,
                 bbox=bbox_props,
                 va='top',
                 ha='left',
                 transform=ax.transAxes)
        if zvals == 'default':
            pylab.savefig(imsave + '/' + repr(z[filedirs.index(filedir)]) +
                          '_fit.png')
        if zvals != 'default':
            pylab.savefig(imsave + '/' + repr(zvals[filedirs.index(filedir)]) +
                          '_fit.png')
        plt.show()

    # Fit the beam widths to find beam waist
    # Define the fit function
    wlength = 572  # nm

    def fit_waist(z, w_0, f):
        z_0 = (math.pi * np.square(w_0)) / (wlength * 1E-6)
        return w_0 * np.sqrt(1 + np.square((z - f) / z_0))

    # Switch to manual z vals
    if zvals != 'default':
        z = np.array(zvals)

    # Convert z-positions to array with 0 = lowest position and units are mm
    if z_units == 'standard':
        conv = 25.4
    if z_units == 'mm':
        conv = 1
    if z_units == 'micron':
        conv = .001
    z = (z - z[0]) * conv

    # Set initial parameters for beam fit
    if param_guess2 == 'find':
        # Get initial parameter guesses
        param_guess2 = []
        slope = (beam_width[1] - beam_width[0]) / (z[1])
        theta = 2 * np.arctan(np.absolute(slope))
        param_guess2.append(2 * (wlength * 1E-6) / (math.pi * theta))
        param_guess2.append(-beam_width[0] / slope)

    # Normalize the weights
    weights_n = weights / np.amax(weights)

    # Do the fit
    param2, covar2 = curve_fit(fit_waist,
                               z,
                               beam_width,
                               p0=param_guess2,
                               sigma=weights_n)

    # Plot the fit and data
    z_cont = np.linspace(0, np.amax(z), 100)
    fit2 = fit_waist(z_cont, param2[0], param2[1])
    fig = plt.figure('Beam Fit')
    plt.clf()
    ax = fig.add_subplot(111)
    plt.plot(z, beam_width, 'bo', label='Data')
    plt.plot(z_cont, fit2, 'k--', label='Fit')
    plt.axis([0, np.amax(z), 0, 1.25 * np.amax(beam_width)])
    plt.xlabel('z (mm)')
    plt.ylabel('Spot Size (mm)')
    plt.legend()
    plt.errorbar(z, beam_width, xerr=None, yerr=1 / weights, fmt=None)
    bbox_props = dict(boxstyle='square', fc='.9', ec='k', alpha=1.0)
    fig_text = 'Beam Waist: ' + repr(round(
        1000 * param2[0], 2)) + ' +/- ' + repr(
            round(1000 * np.sqrt(covar2[0, 0]),
                  2)) + ' micron \nWaist Pos: ' + repr(round(
                      param2[1], 2)) + ' +/- ' + repr(
                          round(np.sqrt(covar2[1, 1]), 2)) + ' mm'
    plt.text(.02,
             .97,
             fig_text,
             fontsize=10,
             bbox=bbox_props,
             va='top',
             ha='left',
             transform=ax.transAxes)
    pylab.savefig(imsave + '/beam_fit.png')
    plt.show()
예제 #17
0
def waist_fit(z, beam_width, weight, **kwargs):

    imsave = kwargs.get('savepath', False)
    disp = kwargs.get('print', False)

    # Import Modules
    import numpy as np
    import matplotlib.pyplot as plt
    import math
    from scipy.special import erf
    from scipy.optimize import curve_fit
    import utility as ut

    # Convert z-positions to array with 0 = lowest position and units are mm
    z = np.array(z)
    z = (z - z[0]) * (25.4 / 1000)

    # Define the fit function

    def fit_waist(z, w_0, f):
        z_0 = (math.pi * np.square(w_0)) / (572 * 1E-6)
        return w_0 * np.sqrt(1 + np.square((z - f) / z_0))

    param_guess = [4E-3, np.mean(z)]

    # Normalize the weights
    weight = weight / np.amax(weight)

    # Do the fit
    param, covar = curve_fit(fit_waist,
                             z,
                             beam_width,
                             p0=param_guess,
                             sigma=weight)

    # Plot the fit and data
    z_cont = np.linspace(0, np.amax(z), 100)
    if flength == 'fit':
        fit = fit_waist(z_cont, param[0], param[1])
    if flength != 'fit':
        fit = fit_waist(z_cont, param[0])
    fig = plt.figure('Beam Fit')
    plt.clf()
    ax = fig.add_subplot(111)
    plt.plot(z, beam_width, 'bo', label='Data')
    plt.plot(z_cont, fit, 'k--', label='Fit')
    plt.axis([-.1, 1.1 * np.amax(z), 0, 1.25 * np.amax(beam_width)])
    plt.xlabel('z (mm)')
    plt.ylabel('Spot Size (mm)')
    plt.legend()
    bbox_props = dict(boxstyle='square', fc='.9', ec='k', alpha=1.0)
    fig_text = 'Beam Waist: ' + ut.rnd(1000 * param[0], 2) + ' +/- ' + ut.rnd(
        1000 * np.sqrt(covar[0, 0]), 2) + ' micron'
    plt.text(.02,
             .97,
             fig_text,
             fontsize=10,
             bbox=bbox_props,
             va='top',
             ha='left',
             transform=ax.transAxes)
    if imsave != False:
        ut.create_dir(imsave)
        plt.savefig(imsave + '/beam_fit.png')
    if disp == True:
        print('w0: ' + ut.rnd(1000 * param[0], 2) + ' um\nz0: ' +
              ut.rnd((math.pi * np.square(1000 * param[0])) /
                     (572 * 1E-3), 2) + ' um\nf: ' + ut.rnd(param[1], 2) +
              ' mm')
    plt.show()
예제 #18
0
def prof_solo(profnum, z, **kwargs):

    # Define kwargs
    imsave = kwargs.get('savefile', 'none')
    fitrange = kwargs.get('fit_range', 'full')
    xstep = kwargs.get('xstep', 'auto')
    units = kwargs.get('units', 'microns')

    # Import modules
    import numpy as np
    import matplotlib.pyplot as plt
    import math
    from scipy.special import erf
    from scipy.optimize import curve_fit
    import pylab
    import os
    import gen_reader as gr
    import utility as ut

    # Define fit function (erf for low to high power)
    def fit_erf(x, a, x_0, w, offset):
        return (a / 2.) * (1 + erf((np.sqrt(2) * (x - x_0)) / w)) + offset

    # Read in data from file
    if xstep == 'auto':
        matrix = gr.reader('/home/chris/anaconda/data/' + str(date) +
                           '/lv/prof' + str(profnum) + '/prof' + str(profnum) +
                           '_amp25_zpos_micron_' + z + '.txt',
                           header=False)
        pos, pows = (.166E-3 / 25.) * matrix[:, 0], matrix[:, 1]
    if xstep != 'auto':
        matrix = gr.reader('/home/chris/anaconda/data/' + str(date) +
                           '/lv/profman' + str.zfill(profnum, 2) + '/profman' +
                           str.zfill(profnum, 2) + '_z-pos-' + units +
                           str.zfill(z, 5) + '_x-step-' + units +
                           str.zfill(xstep, 5) + '.txt',
                           header=False)
        pows = matrix[:, 0]
        pos = 1E-3 * np.arange(0, float(xstep) * len(pows), float(xstep))
        if units == 'minches':
            pos = pos * 25.4

    # Make position array and power array (normalized low to high power)
    if pows[0] > pows[-1]:
        pows_norm = np.flipud(np.array(pows)) / np.amax(np.array(pows))
    else:
        pows_norm = np.array(pows) / np.amax(np.array(pows))
    # Get initial parameter guesses
    param_guess = [1, 0, 0, 0]
    # Guess for w
    bnds = ut.bound_finder(pows_norm, [.1, .9])
    param_guess[2] = pos[bnds[1]] - pos[bnds[0]]
    # Guess for x_0
    for i in range(len(pows)):
        if pows_norm[i] <= .5:
            param_guess[1] = pos[i]
            continue
        else:
            if pows_norm[i] - .5 >= .5 - pows_norm[i - 1]:
                param_guess[1] = pos[i - 1]
                break
            else:
                break
    # Do the fit
    if fitrange != 'full':
        param, covar = curve_fit(fit_erf,
                                 pos[fitrange[0]:fitrange[1]],
                                 pows_norm[fitrange[0]:fitrange[1]],
                                 p0=param_guess)
    if fitrange == 'full':
        param, covar = curve_fit(fit_erf, pos, pows_norm, p0=param_guess)

    # Plot the fits
    x = np.linspace(0, np.amax(pos), 100)
    fit = fit_erf(x, param[0], param[1], param[2], param[3])
    fig = plt.figure('laser_prof')
    plt.clf()
    ax = fig.add_subplot(111)
    plt.plot(pos, pows_norm, 'bo', label='Data')
    plt.plot(x, fit, 'k--', label='Fit')
    plt.axis([0, 1.1 * np.amax(pos), 0, 1.25])
    plt.xlabel('Razor Blade Position (mm)')
    plt.ylabel('Normalized Laser Power')
    plt.legend()
    bbox_props = dict(boxstyle='square', fc='.9', ec='k', alpha=1.0)
    fig_text = 'Spot Size: ' + ut.rnd(1000 * param[2], 2) + ' +/- ' + ut.rnd(
        1000 * np.sqrt(covar[2, 2]), 2) + ' micron'
    #fig_text='Amplitude: '+repr(round(param[0],2))+'\nOffset: '+repr(round(param[1],2))+' mm'+'\nSpot Size: '+repr(1000*round(param[2]),3)+' micron'
    plt.text(.02,
             .97,
             fig_text,
             fontsize=10,
             bbox=bbox_props,
             va='top',
             ha='left',
             transform=ax.transAxes)
    if imsave != 'none':
        ut.create_dir(imsave)
        plt.savefig(imsave + 'beam_profile_' + str.zfill(z, 5) + '.png')
    plt.show()

    return param[2], np.sqrt(covar[2, 2]), pos, pows_norm
예제 #19
0
 def create_work_dir(self, data_dir):
     work_dir = "{}/{}".format(data_dir, self.host)
     utility.create_dir(work_dir)
예제 #20
0
def fitter1d(func, data, param_0, **kwargs):

    # Define Keyword Arguments
    col = kwargs.get('color', 'Black')
    fitlim = kwargs.get('fitlim', 'full')
    fig = kwargs.get('fig', 'default')
    disp_param = kwargs.get('d_param', False)
    savepath = kwargs.get('savepath', False)
    label = kwargs.get('label', '')
    numpts = kwargs.get('numpts', 5)

    # Import Modules
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    import utility as ut

    # Slice data to get frames/region of interest
    if fitlim != 'full':
        # Find index for upper fit limit
        j = -1
        for i in data[0, :]:
            j = j + 1
            if i < fitlim:
                last_wave = i
            else:
                a = abs(fitlim - last_wave)
                b = abs(i - fitlim)
                if a > b:
                    lim_index = j
                    break
                else:
                    lim_index = j - 1
                    break
        data = data[:, 0:lim_index]

    # Do the fit
    param, sigma = curve_fit(func, data[0, :], data[1, :], p0=param_0)

    # Make a more finely spaced x data for fit plot
    xfit = np.linspace(np.amin(data[0, :]), np.amax(data[0, :]),
                       numpts * np.shape(data)[1])
    # Plot fit and data
    if fig == 'default':
        plt.figure('Fitter')
    else:
        plt.figure(fig)
    plt.clf()
    plt.plot(data[0, :], data[1, :], 'bo', label='Data')
    # Dynamically create a plot command with as many parameters as needed
    plt_str = 'plt.plot(xfit,func(xfit,'
    p_txt = ''
    for i in range(len(param)):
        if i == 0:
            plt_str += 'param[%d]' % i
            if disp_param != False:
                p_txt += disp_param[i] + ': ' + scinot(param[i])
        else:
            plt_str += ',param[%d]' % i
            if disp_param != False:
                p_txt += '\n' + disp_param[i] + ': ' + scinot(param[i])
    plt_str += '),"--",color=col,linewidth=2,label="Model")'
    exec(plt_str)
    if disp_param != False:
        textbox(p_txt, [.75, .8])
    plt.legend()
    if savepath != False:
        ut.create_dir(savepath)
        plt.savefig(savepath + 'fit_' + label + '.png')

    return param