Esempio n. 1
0
    def gibbs(self, num_itns=250, random_seed=None, optimize_alpha_m=False, optimize_beta=False, slice_sample=False):
        """
        Uses Gibbs sampling to draw multiple samples from the
        posterior distribution over token--component (token--topic)
        assignments given this instance's corpus (i.e., document
        tokens). After drawing each sample, the log evidence for this
        instance's corpus AND current set of token--component (i.e.,
        token--topic) assignments is printed, along with the most
        probable word types according to the current approximation of
        mean of the posterior distribution over phis.

        Keyword arguments:

        num_itns -- number of Gibbs sampling iterations
        random_seed -- seed for the random number generator
        optimize_alpha_m -- whether to optimize alpha and m
        optimize_beta -- whether to optimize beta
        slice_sample -- whether to slice sample alpha and beta
        """

        assert not (slice_sample and (optimize_alpha_m or optimize_beta))

        seed(random_seed)

        print 'Initialization:'

        self.gibbs_iteration(init=True)

        log_e = self.log_evidence_corpus_and_z()

        plt = InteractivePlot('Iteration', 'Log Evidence')
        plt.update_plot(0, log_e)

        print '\nLog evidence: %s' % log_e
        print 'alpha, beta: %s, %s\n' % (self.alpha, self.beta)
        self.print_top_types()

        for itn in xrange(1, num_itns + 1):

            print '\n---\n\nIteration %s:' % itn

            self.gibbs_iteration()

            if slice_sample:
                self.slice_sample()

            if optimize_alpha_m:
                self.optimize_alpha_m()

            if optimize_beta:
                self.optimize_beta()

            log_e = self.log_evidence_corpus_and_z()

            plt.update_plot(itn, log_e)

            print '\nLog evidence: %s' % log_e
            print 'alpha, beta: %s, %s\n' % (self.alpha, self.beta)
            self.print_top_types()
Esempio n. 2
0
def main():
    # start by reading in the file
    try:
        filename = sys.argv[1]
    except IndexError:
        logger.error(
            'Please provide a rotation curve file. Usage: "$ python fithalo.py path/filename.rot"'
        )
        return

    if not os.path.exists(filename):
        logger.error(f'File {filename} does not exist.')
    else:
        # read data file
        galaxy_params, rcdf = read_file(filename)
        # do an initial fit with free M/L & record resulting RCs in data frame
        rcdf, halo_fit_params = initialize_data(rcdf, galaxy_params)
        # plot initial fit
        fig, rc_plots, labels = draw_plot(rcdf, galaxy_params, halo_fit_params)
        ip = InteractivePlot(fig, rc_plots, labels, rcdf, halo_fit_params)
        plt.show(block=False)
        print_menu(galaxy_params['galaxy_name'])
        print_fit_results(halo_fit_params)
        choice = input()
        handle_choice(choice, ip, rcdf, galaxy_params, halo_fit_params)
Esempio n. 3
0
    def gibbs(self, num_itns=25, random_seed=None):
        """
        Uses Gibbs sampling to draw multiple samples from the
        posterior distribution over document--component assignments
        (i.e., document groups) given this instance's corpus (i.e.,
        document tokens). After drawing each sample, the log evidence
        for this instance's corpus AND current set of
        document--component assignments is printed, along with the
        most probable word types according to the current
        approximation of mean of the posterior distribution over phis.

        Keyword arguments:

        num_itns -- number of Gibbs sampling iterations
        random_seed -- seed for the random number generator
        """

        seed(random_seed)

        print 'Initialization:'

        self.gibbs_iteration(init=True)

        log_e = self.log_evidence_corpus_and_z()

        plt = InteractivePlot('Iteration', 'Log Evidence')
        plt.update_plot(0, log_e)

        print '\nLog evidence: %s\n' % log_e
        self.print_top_types()

        for itn in xrange(1, num_itns + 1):

            print '\n---\n\nIteration %s:' % itn

            self.gibbs_iteration()

            log_e = self.log_evidence_corpus_and_z()

            plt.update_plot(itn, log_e)

            print '\nLog evidence: %s\n' % log_e
            self.print_top_types()
Esempio n. 4
0
def handle_choice(choice, ip, rcdf, galaxy_params, halo_fit_params):
    while choice not in ['f', 'r', 'p', 's', 'q']:
        print(f"'{choice}' is not a valid entry. Please try again.")
        choice = input()
    if choice == 'q':
        sys.exit(0)
    while choice != 'q':
        if choice == 'f':  # user input M/L
            ip.disconnect()
            plt.close()
            # calculate V_disk & V_bulge based on user-input M/L
            d_ml, b_ml = ml_prompt(rcdf.V_disk_norm, rcdf.V_bulge_norm)
            rcdf.V_disk_fit = rcdf.V_disk_norm * np.sqrt(d_ml)
            rcdf.V_bulge_fit = rcdf.V_bulge_norm * np.sqrt(b_ml)
            # fit halo with fixed M/L
            vels = [
                rcdf.VROT, rcdf.V_ERR, rcdf.V_gas_scaled, rcdf.V_disk_fit,
                rcdf.V_bulge_fit
            ]
            halo_fit_params = do_fixed_ml_fit(rcdf.RAD, vels)
            halo_fit_params['d_ml'] = d_ml
            halo_fit_params['b_ml'] = b_ml
            print_fit_results(halo_fit_params)
            # update rotation curves (minus stellar ones which were calculated above)
            rcdf = calculate_rotation_curves(rcdf, halo_fit_params)
            # update plot
            fig, rc_plots, labels = draw_plot(galaxy_params, rcdf,
                                              halo_fit_params)
            ip = InteractivePlot(fig, rc_plots, labels, rcdf, halo_fit_params)
            plt.show(block=False)
            choice = input()
        elif choice == 'r':  # fit halo & M/L
            ip.disconnect()
            plt.close()
            # fit halo & M/L
            vels = [
                rcdf.VROT, rcdf.V_ERR, rcdf.V_gas_scaled, rcdf.V_disk_norm,
                rcdf.V_bulge_norm
            ]
            halo_fit_params = do_fit(rcdf.RAD, vels)
            print_fit_results(halo_fit_params)
            # update rotation curves
            rcdf = calculate_rotation_curves(rcdf, halo_fit_params)
            # update plot
            fig, rc_plots, labels, = draw_plot(galaxy_params, rcdf,
                                               halo_fit_params)
            ip = InteractivePlot(fig, rc_plots, labels, rcdf, halo_fit_params)
            plt.show(block=False)
            choice = input()
        elif choice == 'p':
            figfile = input('Enter figure file name: ')
            plt.savefig(figfile)
            choice = input()
        elif choice == 's':  # save results to file
            write_results(ip, halo_fit_params, galaxy_params['galaxy_name'])
            choice = input()
        else:
            return
Esempio n. 5
0
    def gibbs(self, num_itns=250, random_seed=None):
        """
        Uses Gibbs sampling to draw multiple samples from the
        posterior distribution over token--component (token--topic)
        assignments given this instance's corpus (i.e., document
        tokens). After drawing each sample, the log evidence for this
        instance's corpus AND current set of token--component (i.e.,
        token--topic) assignments is printed, along with the most
        probable word types according to the current approximation of
        mean of the posterior distribution over phis.

        Keyword arguments:

        num_itns -- number of Gibbs sampling iterations
        random_seed -- seed for the random number generator
        """

        seed(random_seed)

        print 'Initialization:'

        self.gibbs_iteration(init=True)

        log_e = self.log_evidence_corpus_and_z()

        plt = InteractivePlot('Iteration', 'Log Evidence')
        plt.update_plot(0, log_e)

        print '\nLog evidence: %s' % log_e
        print 'alpha, beta: %s, %s\n' % (self.alpha, self.beta)
        self.print_top_types()

        for itn in xrange(1, num_itns + 1):

            print '\n---\n\nIteration %s:' % itn

            self.gibbs_iteration()
            self.slice_sample()

            log_e = self.log_evidence_corpus_and_z()

            plt.update_plot(itn, log_e)

            print '\nLog evidence: %s' % log_e
            print 'alpha, beta: %s, %s\n' % (self.alpha, self.beta)
            self.print_top_types()
Esempio n. 6
0
#!/usr/bin/env python3
''' Present an interactive function explorer with slider widgets.
Scrub the sliders to change the properties of the ``linear function``
Use the ``bokeh serve`` command to run the example by executing:

    bokeh serve iplot_linear.py

at your command prompt. Then navigate to the URL

    http://localhost:5006/iplot_linear

in your browser.
'''

from interactive_plot import InteractivePlot


def linear_function(args, x):
    return args[1] + args[0] * x


sliders_spec = [('slope ', 'a', 0, 8, 1), ('shift ', 'b', 0, 5, 0)]
title = 'f(x) = a * x + b'
InteractivePlot(title, 0, 6, 'red', linear_function, sliders_spec)
Esempio n. 7
0
#!/usr/bin/env python3

from mexhat import mexhat_np
''' Present an interactive function explorer with slider widgets.
Scrub the sliders to change the properties of the ``mexican hat function``
Use the ``bokeh serve`` command to run the example by executing:

    bokeh serve iplot_mexhat.py

at your command prompt. Then navigate to the URL

    http://localhost:5006/iplot_mexhat

in your browser.
'''

from interactive_plot import InteractivePlot
'''Computes Mexican hat shape using numpy, see
http://en.wikipedia.org/wiki/Mexican_hat_wavelet'''


def mexhat(args, t):
    sigma = args[0]
    return mexhat_np(sigma, t)


sliders_spec = [('sigma ', 'sigma', 0.8, 3, 1)]
title = 'mexican hat function for varying sigma'
InteractivePlot(title, -7, 7, 'red', mexhat, sliders_spec)
Esempio n. 8
0
Use the ``bokeh serve`` command to run the example by executing:

    bokeh serve iplot_normal.py

at your command prompt. Then navigate to the URL

    http://localhost:5006/iplot_normal

in your browser.
'''

from interactive_plot import InteractivePlot
from normal_pdf import normalProbabilityDensity

def normal_func(args,x):
  assert len(args) == 2
  mean = args[0]
  stddev = args[1]
  return normalProbabilityDensity(mean,stddev,x)

x_min = -3
x_max = 3
stddev_min = 0.5
stddev_max = 1.5
default_mean = x_min + (x_max - x_min)/2
default_stddev = stddev_min + (stddev_max - stddev_min)/2
sliders_spec = [('','mean',x_min+1,x_max-1,default_mean),
                ('','stddev',stddev_min,stddev_max,default_stddev)]
title = 'normal_pdf(x)'
InteractivePlot(title,x_min,x_max,'blue',normal_func,sliders_spec)
#!/usr/bin/env python3

''' Present an interactive function explorer with slider widgets.
Scrub the sliders to change the properties of the plotted function
Use the ``bokeh serve`` command to run the example by executing:

    bokeh serve iplot_quadratic.py

at your command prompt. Then navigate to the URL

    http://localhost:5006/iplot_quadratic

in your browser.
'''

from interactive_plot import InteractivePlot

def quadratic_function(args,x):
  return args[0] * x * x + args[1] * x + args[2]

sliders_spec = [('','a',0,4,1),('','b',0,16,1),('','c',0,64,1)]
title = 'f(x) = a * x^{2} + b * x + c'
InteractivePlot(title,0,6,'blue',quadratic_function,sliders_spec)