Exemplo n.º 1
0
 def change_limits(self, ax=None, limits=None):
     if ax is None:
         ax = self.select_subplot()
     ax_settings = self.settings['{0:d}.{1:d}'.format(ax.row, ax.col)]
     if limits is None:
         x_limits = utils.get_input_float('\nPlot limits for ' + \
                                              ax.parameters[0] + \
                                              ' (lower upper)?\n> ', num=2)
     else:
         x_limits = limits[0]
     ax.set_xlim(x_limits)
     ax_settings['x_limits'] = x_limits
     if limits is None:
         if len(ax.parameters) == 2:
             y_limits = utils.get_input_float('\nPlot limits for ' + \
                                                  ax.parameters[1] + \
                                                  ' (lower upper)?\n> ', 
                                              num=2)
         else:
             y_limits = utils.get_input_float('\nPlot limits for ' + \
                                                  'y axis' + \
                                                  ' (lower upper)?\n> ', 
                                              num=2)
     elif len(limits) == 2:
         y_limits = limits[1]
     else:
         y_limits = None
     if y_limits is not None:
         ax.set_ylim(y_limits)
         ax_settings['y_limits'] = y_limits
Exemplo n.º 2
0
 def set_color(self, color=None):
     if color is None:
         color = utils.get_input_float('\nRGB values for main color?\n' + \
                                           '(3 numbers between 0 and 1 ' + \
                                           'separated by spaces)\n> ', 
                                       num=3)
     if not np.all([0.<=x<=1. for x in list(color)]):
         print 'Values must be between 0 and 1.'
         self.set_color()
     self.settings['color'] = tuple(color)
Exemplo n.º 3
0
 def set_color(self, color=None):
     if color is None:
         color = utils.get_input_float('\nRGB values for main color?\n' + \
                                           '(3 numbers between 0 and 1 ' + \
                                           'separated by spaces)\n> ',
                                       num=3)
     if not np.all([0. <= x <= 1. for x in list(color)]):
         print 'Values must be between 0 and 1.'
         self.set_color()
     self.settings['color'] = tuple(color)
Exemplo n.º 4
0
 def define_new_chain(self):
     files = []
     while len(files) == 0:
         for f in raw_input('\nChain file names?\n> ').split():
             new_files = glob.glob(f)
             if len(new_files) == 0:
                 print 'No files matching ' + f + ' found.'
             elif not np.array([os.path.isfile(nf) \
                                for nf in new_files]).all():
                 print 'Some of the files specified are not valid.'
             else:
                 files += new_files
     name = raw_input('Label for chain?\n> ')
     burn_in = utils.get_input_float( \
         'Burn-in fraction or number of samples?\n> ')[0]
     mult_column = utils.get_input_integer( \
         'Multiplicity column? (Enter -1 if none.)\n> ')[0]
     if mult_column < 0:
         mult_column = None
     lnlike_column = utils.get_input_integer( \
         'Log likelihood column? (Enter -1 if none.)\n> ')[0]
     if lnlike_column < 0:
         lnlike_column = None
     first_par_column = utils.get_input_integer( \
         'Column of first chain parameter?\n> ')[0]
     m = Menu(options=['File named as chain label + .paramnames',
                       'A different file',
                       'Header of chain files'],
              exit_str=None,
              header='Where are the chain parameter names?')
     m.get_choice()
     paramname_file = None
     params_in_header = False
     if m.i_choice == 1:
         paramname_file = raw_input('Enter file name:\n> ')
     elif m.i_choice == 2:
         params_in_header = True
     chain_settings = (name, files, burn_in, 
                       mult_column, lnlike_column, first_par_column,
                       paramname_file, params_in_header)
     # check if name is already in history; if so, replace with new
     for chain in list(self.history['chains']):
         if chain[0] == name:
             self.history['chains'].remove(chain)
     self.history['chains'].append([1] + list(chain_settings))
     return chain_settings
    print(
        f"\tInsertion Cost={DEFAULT_INS_COST}, Deletion Cost={DEFAULT_DEL_COST}, Match Cost={DEFAULT_MATCH_COST}, Mismatch Cost={DEFAULT_MISMATCH_COST}"
    )
    use_default = get_input_boolean(
        'Do you want to use the above costs? [Y/N]')

    #%% Costs
    if use_default:
        print("* Using default costs *")
        ins_cost = DEFAULT_INS_COST
        del_cost = DEFAULT_DEL_COST
        match_cost = DEFAULT_MATCH_COST
        mismatch_cost = DEFAULT_MISMATCH_COST
    else:
        print("* Defining own costs *")
        ins_cost = get_input_float('Please type the insertion penalty/cost')
        del_cost = get_input_float('Please type the deletion penalty/cost')
        match_cost = get_input_float('Please type the matching penalty/cost')
        mismatch_cost = get_input_float(
            'Please type the mismatching penalty/cost')

    #%% Algorithm Timing
    start_time = timer()
    V, paths = needleman_wunsch(S1, S2, ins_cost, del_cost, match_cost,
                                mismatch_cost)
    st1, st2, score = reconstruct(S1, S2, V, paths)

    combined = combine(V, paths, PATH_CHARACTERS)

    end_time = timer()
    duration_sec = end_time - start_time
    S1 = input('Type the first string (S1)')
    S2 = input('Type the second string (S2)')
    print("*** Default penalty costs and parameters for f(k) = a + (b * k) ***")
    print(f"\ta={DEFAULT_A}, b={DEFAULT_B}, Match Cost={DEFAULT_MATCH_COST}, Mismatch Cost={DEFAULT_MISMATCH_COST}")
    use_default = get_input_boolean('Do you want to use the above costs? [Y/N]')

    #%% Costs
    if use_default:
        print("* Using default costs *")
        a = DEFAULT_A
        b = DEFAULT_B
        match_cost = DEFAULT_MATCH_COST
        mismatch_cost = DEFAULT_MISMATCH_COST
    else:
        print("* Defining own costs *")
        a = get_input_float('Please type the value for a in f(k) = a + (b * k)')
        b = get_input_float('Please type the value for b in f(k) = a + (b * k)')
        match_cost = get_input_float('Please type the matching penalty/cost')
        mismatch_cost = get_input_float('Please type the mismatching penalty/cost')

    #%% Algorithm Timing
    start_time = timer()
    F, E, G, F_paths, E_paths, G_paths = gotoh(S1, S2, match_cost, mismatch_cost, a, b)
    st1, st2, score = reconstruct(S1, S2, F, E, G, F_paths, E_paths, G_paths)

    combined_F = combine(F, F_paths, PATH_F_CHARACTERS)
    combined_G = combine(G, G_paths, PATH_G_CHARACTERS)
    combined_E = combine(E, E_paths, PATH_E_CHARACTERS)

    end_time = timer()
    duration_sec = end_time - start_time
Exemplo n.º 7
0
    def define_new_likelihood(self, pdf):
        # if chain exists, choose some parameters from there
        # can also add new parameters
        name = raw_input('Label for likelihood?\n> ')
        m = Menu(options=['Flat', 'Gaussian', 
                          'SNe (Gaussian with analytic marginalization)',
                          'Inverse Gaussian'], 
                 exit_str=None,
                 header='Choose the form of the likelihood:')
        m.get_choice()
        form = m.choice
        if form[:3] == 'SNe':
            form = 'SNe'
        lk_dict = {'form': form}
        priors = []
        if form != 'SNe':
            parameters = pdf.choose_parameters(allow_extra_parameters=True)
            pdf.add_parameters(parameters)
            lk_dict['parameters'] = parameters

        if form == 'Flat':
            for p in parameters:
                if len(pdf.settings['parameters'][p]) != 2:
                    new_prior = utils.get_input_float( \
                        'Enter lower and upper limits of the prior on ' + \
                            p + ':\n> ', num=2)
                    priors.append(sorted(new_prior))
                else:
                    priors.append(pdf.settings['parameters'][p])

        elif form in ['Gaussian', 'Inverse Gaussian']:
            means = utils.get_input_float('Enter mean values:\n> ',
                                          num=len(parameters))
            variances = utils.get_input_float('Enter variances:\n> ',
                                              num=len(parameters))
            for i, p in enumerate(parameters):
                if len(pdf.settings['parameters'][p]) != 2:
                    priors.append([means[i] - 5.*np.sqrt(variances[i]),
                                   means[i] + 5.*np.sqrt(variances[i])])
                else:
                    priors.append(pdf.settings['parameters'][p])
            covariance = np.diag(variances)
            for i, j in itertools.combinations(range(len(parameters)), 2):
                covariance[i, j] = utils.get_input_float( \
                    'Cov(' + parameters[i] + ', ' + parameters[j] + ')?\n> ')[0]
                covariance[j, i] = covariance[i, j]
            lk_dict['means'] = means
            lk_dict['covariance'] = covariance.tolist()

        elif form == 'SNe':
            sn_z_mu_file = raw_input('Name of file with mean SN distance ' + \
                                         'modulus vs. z?\n> ')
            sn_z, sn_mu = np.loadtxt(sn_z_mu_file, unpack=True)
            lk_dict['means'] = list(sn_mu)
            sn_cov_file = raw_input('Name of file with SN covariance ' + \
                                        'matrix?\n> ')
            sn_cov = np.loadtxt(sn_cov_file)
            lk_dict['covariance'] = sn_cov.tolist()
            sn_parameters = []
            for i, z in enumerate(sn_z):
                p_sn_z = 'mu_SN_z' + str(z)
                sn_parameters.append(p_sn_z)
                priors.append([sn_mu[i] - 5.*np.sqrt(sn_cov[i,i]),
                               sn_mu[i] + 5.*np.sqrt(sn_cov[i,i])])
            pdf.add_parameters(sn_parameters)
            lk_dict['parameters'] = sn_parameters


        lk_dict['priors'] = priors
        new_lk = (name, 1, lk_dict)

        # check if name is already in history; if so, replace with new
        for lk in list(self.history['likelihoods']):
            if lk[0] == name:
                self.history['likelihoods'].remove(lk)
        self.history['likelihoods'].append(list(new_lk))
        return new_lk