Esempio n. 1
0
    def saverdb(self, parameter_s='', local_ns=None):
        """ Save current system's RV in a file """
        try:
            args = parse_arg_string('saverdb', parameter_s)
        except DocoptExit:
            print saverdb_usage.lstrip()
            return
        except SystemExit:
            return

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return        

        filename = args['<file>']
        system.save(filename)
Esempio n. 2
0
    def demc(self, parameter_s='', local_ns=None):
        """ Run the Differential Evolution MCMC. - stub"""
        from shell_colors import red
        ## take care of arguments
        try:
            args = parse_arg_string('demc', parameter_s)
        except DocoptExit:
            print demc_usage.lstrip()
            return
        except SystemExit:
            return

        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
        print args

        zfile = args.pop('<zipfile>')

        results = core.do_demc(system, zfile=zfile, burnin=0)
        return results
Esempio n. 3
0
    def mod(self, parameter_s='', local_ns=None):
        """ Define the type of model that will be adjusted to the data.
        Type 'mod -h' for more help
        """
        from shell_colors import yellow, blue, red
        args = parse_arg_string('mod', parameter_s)
        if args == 1:  # called without arguments, show how it's done
            msg = yellow('Usage: ') + 'mod [k<n>] [d<n>]\n' + \
                  'Options: k<n>    Number of keplerian signals\n' + \
                  '         d<n>    Degree of polynomial drift'
            clogger.fatal(msg)
            return

        if 'default' in local_ns:
            system = local_ns['default']
            if system.model is None: system.model = {}
            system.model['k'] = k = int(args[0][1])
            system.model['d'] = d = int(args[1][1])
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        # this should be logged?
        print blue('Current model:'), k, 'kep,', d, 'drifts'
Esempio n. 4
0
    def gen(self, parameter_s='', local_ns=None):
        """ Run the genetic algorithm minimization - stub """
        from shell_colors import red

        ## take care of arguments
        try:
            args = parse_arg_string('gen', parameter_s)
        except DocoptExit:
            print de_usage.lstrip()
            return
        except SystemExit:
            return
        
        ngen = int(args.pop('--ngen'))
        npop = int(args.pop('--npop'))


        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.do_genetic(system, npop=npop, ngen=ngen)
        system.do_plot_fit()
Esempio n. 5
0
    def add_noise(self, parameter_s='', local_ns=None):
        try:
            args = parse_arg_string('add_noise', parameter_s)
        except DocoptExit:
            print addnoise_usage.lstrip()
            return
        except SystemExit:
            return

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return 

        # print args
        noise = float(args['<number>'])
        kms = system.error.mean() < 0.01
        if kms:
            system.error = sqrt(system.error**2 + (noise / 1000)**2)
        else:
            system.error = sqrt(system.error**2 + noise**2)
Esempio n. 6
0
    def wf(self, parameter_s='', local_ns=None):
        """ Calculate the spectral window function of the observations. 
        Type 'wf -h' for more help. """

        args = parse_arg_string('wf', parameter_s)
        if args == 1: return
        print args
        
        # use default system or user defined
        try:
            if local_ns.has_key('default') and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
        
        try: 
            system.per
        except AttributeError:
            from shell_colors import green
            clogger.debug('Calculating periodogram to get frequencies')
            stdout_write('Calculating periodogram to get frequencies...')
            system.per = periodograms.gls(system, hifac=5)
            print green(' done')
        
        try: 
            system.wf._plot()
        except AttributeError:
            system.wf = periodograms.SpectralWindow(system.per.freq, system.time)
Esempio n. 7
0
    def to_mps(self, parameter_s='', local_ns=None):
        # Convert data to meters per second, if in km/s
        from shell_colors import blue

        args = parse_arg_string('to_mps', parameter_s)
        # print args

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['SYSTEM']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        if (min(system.error) < 0.01):
            msg = blue('INFO: ') + 'Converting to m/s'
            clogger.info(msg)

            system.vrad = (system.vrad - mean(system.vrad)) * 1e3
            system.error *= 1e3
            system.units = 'm/s'
Esempio n. 8
0
    def do_plot_extras(self, extra):
        """ Plot other observed quantities as a function of time.

        Parameters
        ----------
        extra: string
          One of the quantities available in system.extras
        """
        # import pyqtgraph as pg

        colors = 'bgrcmykw' # lets hope for less than 9 data-sets
        t = self.time

        # handle inexistent field
        if extra not in self.extras._fields:
          from shell_colors import red
          msg = red('ERROR: ') + 'The name "%s" is not available in extras.\n' % extra
          clogger.fatal(msg)
          return

        i = self.extras._fields.index(extra) # index corresponding to this quantity

        plt.figure()
        # p = pg.plot()
        plt.plot(t, self.extras[i], 'o', label=extra)
        
        plt.xlabel('Time [days]')
        plt.ylabel(extra + ' []')
        plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05))
        plt.minorticks_on()
        plt.tight_layout()
        plt.show()
Esempio n. 9
0
    def plot(self, parameter_s='', local_ns=None):
        """ Plot various quantities. 
        Type 'plot -h' for more help """

        try:
            args = parse_arg_string('plot', parameter_s)
        except DocoptExit:
            print plot_usage.lstrip()
            return
        except SystemExit:
            return
        # print args

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        together = False
        if args['--together']:
            together = True
            second_quantity = args['--together']

        # plot the observed radial velocities
        if args['obs']:
            if together: system.do_plot_obs_together(q=second_quantity, save=args['--save'])
            else: system.do_plot_obs(save=args['--save'])

        # plot residuals from fit
        if args['resid']:
            system.do_plot_resid(save=args['--save'])

        # plot other quantities
        extras_available = ['fwhm', 'contrast', 'bis_span', 'noise', 
                          's_mw', 'sig_s', 'rhk', 'sig_rhk', 
                          'sn_CaII', 'sn10', 'sn50', 'sn60']
        extras_mapping = ['fwhm', 'contrast', 'bis', 'noise',
                          's', 's', 'rhk', 'rhk',
                          'sn', 'sn', 'sn', 'sn']
        for i, e in enumerate(extras_available):
            try:
                if args[extras_mapping[i]]:
                    if together: system.do_plot_extras_together(e, save=args['--save'])
                    else: system.do_plot_extras(e, save=args['--save'])
                    return
            except KeyError:
                pass
Esempio n. 10
0
    def __init__(self, *filenames, **kwargs):

        assert len(filenames)>=1, "Need at least one file to read"
        # don't repeat files
        filenames = unique(filenames)

        # verbose?
        try:
          verbose = kwargs.pop('verbose')
        except KeyError:
          verbose = False
          
        # skip header lines? (no by default)
        try:
          skip = kwargs.pop('skip')
        except KeyError:
          skip = 0

        # in which format are the files? (drs35 by default)
        try:
          format = kwargs.pop('format').lower()
        except (KeyError, AttributeError): # this way we also catch the default None
          format = 'drs35'

        # read data
        try:
          t, rv, err, self.provenance, extras = \
               rvIO.read_rv(*filenames, verbose=verbose, skip=skip, format=format)
        except ValueError:
          from shell_colors import red
          msg = red('ERROR: ') + 'If your files have header lines set --skip option.\n'
          clogger.fatal(msg)
          return

        self.time, self.vrad, self.error = (t, rv, err)

        # save the extra quantities as a namedtuple if we read them
        if format == 'drs35': # default
          extras_names = ['fwhm', 'contrast', 'bis_span', 'noise', 
                          's_mw', 'sig_s', 'rhk', 'sig_rhk', 'sn_CaII', 
                          'sn10', 'sn50', 'sn60']
        elif format == 'drs34' or format == 'coralie':
          extras_names = ['fwhm', 'contrast', 'bis_span', 'noise', 'sn10', 'sn50', 'sn60']
        else:
          extras_names = []
        extra = namedtuple('Extra', extras_names, verbose=False)
        self.extras = extra._make(extras)
        self.extras_names = extras_names

        # time, vrad and error can change, 
        # the *_full ones correspond always to the full set
        self.time_full = self.time
        self.vrad_full = self.vrad
        self.error_full = self.error
        # same for extras
        self.extras_full = self.extras
Esempio n. 11
0
def do_correlate(system, vars=(), verbose=False):
	# just to be sure, but this should not pass through docopt in commands.py
	if len(vars) != 2: return

	var1 = vars[0]
	var2 = vars[1]

	# handle inexistent fields
	available = system.extras._fields + ('vrad',)
	if var1 not in available:
		msg = red('ERROR: ') + 'The name "%s" is not available for correlation.\n' % var1
		clogger.fatal(msg)
		return
	if var2 not in available:
		msg = red('ERROR: ') + 'The name "%s" is not available for correlation.\n' % var2
		clogger.fatal(msg)
		return

	if var1 == 'vrad': 
		v1 = system.vrad
	else:
		i = system.extras._fields.index(var1)
		v1 = system.extras[i]

	if var2 == 'vrad': 
		v2 = system.vrad
	else:
		i = system.extras._fields.index(var2)
		v2 = system.extras[i]		

	pr = pearsonr(v1, v2)
	sr = spearmanr(v1, v2)

	if verbose:
		print blue('[Pearson correlation]') + ' r=%f, p-value=%f' % pr
		print blue('[Spearman correlation]') + ' r=%f, p-value=%f' % sr
	# label = 
	figure()
	plot(v1, v2, 'o')
	xlabel(var1)
	ylabel(var2)
	tight_layout()
	show()
Esempio n. 12
0
    def remove_rotation(self, parameter_s='', local_ns=None):
        """ Remove rotation period and harmonics """
        from shell_colors import red
        
        try:
            args = parse_arg_string('rrot', parameter_s)
        except DocoptExit:
            print rrot_usage.lstrip()
            return
        except SystemExit:
            return

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        print args
        prot = args['--prot']
        nrem = int(args['--nrem'])
        fwhm = args['fwhm']
        rhk = args['rhk']

        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
            
        core.do_remove_rotation(system, prot=prot, nrem=nrem, fwhm=fwhm, rhk=rhk)
Esempio n. 13
0
    def nest(self, parameter_s='', local_ns=None):
        """ Start the MultiNest analysis and handle data interaction and IO """
        from shell_colors import red

        if local_ns.has_key('default'):
            system = local_ns['default']
            core.do_multinest(system)
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
Esempio n. 14
0
    def detection_limits(self, parameter_s='', local_ns=None):
        # use default system or user defined
        if 'default' in local_ns:
            system = local_ns['default']
        else:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.do_detection_limits(system)
Esempio n. 15
0
    def dnest(self, parameter_s='', local_ns=None):
        from shell_colors import red

        if local_ns.has_key('default'):
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.do_RJ_DNest3(system)
Esempio n. 16
0
 def genyorbit(self, parameter_s='', local_ns=None):
     """ Run the genetic algorithm minimization - stub """
     from shell_colors import red
     if 'default' in local_ns:
         system = local_ns['default']
     else:
         msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                'name with the -n option'
         clogger.fatal(msg)
         return
         
     write_yorbit_macro(system)
Esempio n. 17
0
 def gen(self, parameter_s='', local_ns=None):
     """ Run the genetic algorithm minimization - stub """
     from shell_colors import red
     if local_ns.has_key('default'):
         system = local_ns['default']
         core.do_genetic(system)
     else:
         msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                'name with the -n option'
         clogger.fatal(msg)
         return
         
     system.do_plot_fit()
Esempio n. 18
0
def do_fit(system, verbose):
	try:
		degree = system.model['d']
	except TypeError:
		msg = red('Error: ') + 'Need to run mod before fit. '
		clogger.error(msg)
		return
	with warnings.catch_warnings(record=True) as w:
		p = polyfit(system.time, system.vrad, degree)
		if len(w):
			msg = yellow('Warning: ') + 'Polyfit may be poorly conditioned. ' \
			      + 'Maybe try a lower degree drift?'
			clogger.info(msg)
	return p
Esempio n. 19
0
    def set_fit(self, parameter_s='', local_ns=None):
        from shell_colors import red
        # args = parse_arg_string('fit', parameter_s)
        # if args == 1: return
        #print args

        # verb = True if args['--verbose'] else False

        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.do_set_fit(system)
Esempio n. 20
0
    def clean(self, parameter_s='', local_ns=None):
        """ 
        Deconvolves the LS periodogram from the window function 
        using the CLEAN algorithm (Roberts et al. 1985)
        """
        # use default system or user defined
        try:
            if 'default' in local_ns:
                system = local_ns['default']
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.do_clean(system)
Esempio n. 21
0
    def correlate(self, parameter_s='', local_ns=None):
        from shell_colors import red
        args = parse_arg_string('correlate', parameter_s)
        if args == 1: return
        print args

        verb = True if args['--verbose'] else False

        if local_ns.has_key('default'):
            system = local_ns['default']
            var1 = args['<var1>']
            var2 = args['<var2>']
            result = core.do_correlate(system, vars=(var1, var2), verbose=verb)
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
Esempio n. 22
0
    def rotation(self, parameter_s='', local_ns=None):
        """ Calculate rotation period from activity-rotation relation"""
        args = parse_arg_string('rotation', parameter_s)
        # print args

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['SYSTEM']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        core.get_rotation_period(system)
Esempio n. 23
0
    def lowpass(self, parameter_s='', local_ns=None):
        from shell_colors import blue
        # try:
        #     args = parse_arg_string('add_noise', parameter_s)
        # except DocoptExit:
        #     print addnoise_usage.lstrip()
        #     return
        # except SystemExit:
        #     return

        # use default system or user defined
        try:
            system = local_ns['default']
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return 

        core.do_lowpass_filter(system) 
Esempio n. 24
0
    def fit(self, parameter_s='', local_ns=None):
        from shell_colors import red
        args = parse_arg_string('fit', parameter_s)
        if args == 1: return
        print args

        verb = True if args['--verbose'] else False

        if local_ns.has_key('default'):
            system = local_ns['default']
            result = core.do_fit(system, verb)
            if result is not None:
                system.model['drift'] = result
                if verb: print 'Coeff:', result
                system.do_plot_drift()
            else:
                return
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
Esempio n. 25
0
    def correlate(self, parameter_s='', local_ns=None):
        from shell_colors import red
        args = parse_arg_string('correlate', parameter_s)
        if args == 1: return
        #print args

        verb = args['--verbose']
        rem = args['--remove']
        chunks = args['--chunks']

        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        var1 = args['<var1>']
        var2 = args['<var2>']

        result = core.do_correlate(system, vars=(var1, var2), verbose=verb, remove=rem, chunks=chunks)
Esempio n. 26
0
    def dawfab(self, parameter_s='', local_ns=None):
        """ Run the Dawson Fabrycky algorithm to search for aliases.
        Type 'dawfab -h' for more help. """

        args = parse_arg_string('dawfab', parameter_s)
        if args == 1: return
        #print args
        
        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            from shell_colors import red
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
        
        core.do_Dawson_Fabrycky(system)
        return
Esempio n. 27
0
    def per(self, parameter_s='', local_ns=None):
        """ Calculate periodograms of various quantities. 
        Type 'per -h' for more help. """

        from shell_colors import red
        try:
            args = parse_arg_string('per', parameter_s)
        except DocoptExit:
            print per_usage.lstrip()
            return
        except SystemExit:
            return
        # print args
        
        if args['--describe']:
            print periodograms.help_text
            return

        # use default system or user defined
        try:
            if 'default' in local_ns and not args['-n']:
                system = local_ns['default']
            else:
                system_name = args['-n']
                system = local_ns[system_name]
        except KeyError:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return
        
        # verb = True if args['--verbose'] else False
        hf = float(args.pop('--hifac'))
        of = float(args.pop('--ofac'))
        fap = args['--fap']
        bfap = args['--bfap']
        showplot = not args['--noplot']

        # which periodogram should be calculated?
        per_fcn = None
        if args['--hoef']:
            per_fcn = periodograms.hoeffding
            name = 'Hoeffding'
        elif args['--bgls']:
            per_fcn = periodograms.bgls
            name = 'Bayesian Generalized Lomb-Scargle'
        elif args['--bayes']: 
            per_fcn = periodograms.bls
            name = 'Bayesian Lomb-Scargle'
        elif args['--ls']: 
            per_fcn = periodograms.ls_PressRybicki
            name = 'Lomb Scargle'
        elif args['--multiband']:
            per_fcn = periodograms.MultiBandGLS
            name = 'Multiband Lomb-Scargle'
            tempmask = system.time > 57170
            if (~tempmask).all():
                msg = red('ERROR: ') + 'All observations are before 57170. Multiband periodogram is not appropriate'
                clogger.fatal(msg)
                return
        elif args['--gls']: 
            per_fcn = periodograms.gls
            name ='Generalized Lomb-Scargle'
        # this is the default if user did not specify arguments
        else: 
            per_fcn = periodograms.gls
            name ='Generalized Lomb-Scargle'

        if args['obs']: # periodogram of the observed RVs
            try: 
                # are we forced to recalculate it?
                if args['--force']: raise AttributeError
                # it was calculated already?
                system.per
                # the same periodogram?
                if system.per.name != name:
                    raise AttributeError
                # system.per._output(verbose=verb)  # not ready
                if showplot:
                    system.per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])
            except AttributeError:
                system.per = per_fcn(system, hifac=hf, ofac=of)
                # system.per._output(verbose=verb)  # not ready
                if showplot:
                    system.per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])

        if args['bis']: # periodogram of the CCF's Bisector Inverse Slope
            system.bis_per = per_fcn(system, hifac=hf, ofac=of, quantity='bis')
            if showplot:
                system.bis_per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])

        if args['fwhm']: # periodogram of the CCF's fwhm
            system.fwhm_per = per_fcn(system, hifac=hf, ofac=of, quantity='fwhm')
            if showplot:
                system.fwhm_per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])

        if args['rhk']: # periodogram of rhk
            system.rhk_per = per_fcn(system, hifac=hf, ofac=of, quantity='rhk')
            if showplot:
                system.rhk_per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])

        if args['contrast']: # periodogram of contrast
            system.contrast_per = per_fcn(system, hifac=hf, ofac=of, quantity='contrast')
            if showplot:
                system.contrast_per._plot(doFAP=fap, dobFAP=bfap, save=args['--save'])

        if args['resid']: # periodogram of the residuals of the current fit
            system.resid_per = per_fcn(system, hifac=hf, ofac=of, quantity='resid')
            if showplot:
                system.resid_per._plot(doFAP=fap, dobFAP=bfap)
Esempio n. 28
0
def do_genetic(system, just_gen=False):
	""" Carry out the fit using a genetic algorithm and if 
	just_gen=False try to improve it with a run of the LM algorithm """
	try:
		degree = system.model['d']
		keplerians = system.model['k']
	except TypeError:
		msg = red('Error: ') + 'Need to run mod before gen. '
		clogger.error(msg)
		return

	maxP = system.per.get_peaks(output_period=True)[1]
	size_maxP = 10**(len(str(int(maxP)))-1)
	system.fit = {}

	msg = blue('INFO: ') + 'Initializing genetic algorithm...'
	clogger.info(msg)
	msg = blue('    : ') + 'Model is: %d keplerians + %d drift' % (keplerians, degree)
	clogger.info(msg)

	vel = zeros_like(system.time)

	def chi2_1(individual):
		""" Fitness function for 1 planet model """
		P, K, ecc, omega, T0, gam = individual 
		get_rvn(system.time, P, K, ecc, omega, T0, gam, vel)
		chi2 = sum(((system.vrad - vel)/system.error)**2)
		#print chi2
		return chi2,

	def chi2_n(individual):
		""" Fitness function for N planet model """
		P, K, ecc, omega, T0, gam = [individual[i::6] for i in range(6)]
		#print ecc
		get_rvn(system.time, P, K, ecc, omega, T0, gam[0], vel)
		#print 'out of get_rvn'
		chi2 = sum(((system.vrad - vel)/system.error)**2)
		#print chi2
		return chi2,

	## create the required types -- the fitness and the individual.
	creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) # minimization of a single objective
	creator.create("Individual", list, fitness=creator.FitnessMin) 

	## create parameters by sampling from their priors
	def P_prior():
		return random.uniform(5, 1000)
		# return random.gauss(maxP, size_maxP)
	def K_prior():
		return random.uniform(0, 150)
	def ecc_prior():
		return random.uniform(0, 0.9)
	def om_prior():
		return random.uniform(0, 360)
	def t0_prior():
		return random.uniform(2350000, 2550000)
	def gamma_prior():
		return random.uniform(-100, 100)
	priors = [P_prior, K_prior, ecc_prior, om_prior, t0_prior, gamma_prior]

	toolbox = base.Toolbox()
	toolbox.register("individual", tools.initCycle, creator.Individual, priors, n=keplerians)
	toolbox.register("population", tools.initRepeat, list, toolbox.individual)

	def mutPrior(individual, indpb):
		for i, fcn in enumerate(zip(individual, priors)):
			if random.random() < indpb:			
				individual[i] = fcn[1]()
		return individual,

	toolbox.register("evaluate", chi2_n)
	toolbox.register("mate", tools.cxTwoPoints)
	toolbox.register("mutate", mutPrior, indpb=0.10)
	toolbox.register("select", tools.selTournament, tournsize=3)

	npop = 500
	ngen = 150
	npar = 5*keplerians+1
	## build the population
	pop = toolbox.population(n=npop)
	## helper functions
	hof = tools.HallOfFame(1)
	stats = tools.Statistics(lambda ind: ind.fitness.values)
	stats.register("avg", nanmean)
	# stats.register("std", nanstd)
	stats.register("min", np.nanmin)
	# stats.register("max", np.nanmax)
	# stats.register("total", sigma3)
	stats.register("red", lambda v: min(v)/(len(system.time)-npar) )

	msg = blue('INFO: ') + 'Created population with N=%d. Going to evolve for %d generations...' % (npop,ngen)
	clogger.info(msg)

	## run the genetic algorithm
	algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=ngen, stats=stats, halloffame=hof, verbose=True)
	
	## output results information
	msg = yellow('RESULT: ') + 'Best individual is'
	clogger.info(msg)
	## loop over planets
	print("%3s %12s %10s %10s %10s %15s %9s" % \
		('', 'P[days]', 'K[km/s]', 'e', unichr(0x3c9).encode('utf-8')+'[deg]', 'T0[days]', 'gam') )
	for i, planet in enumerate(list(ascii_lowercase)[:keplerians]):
		P, K, ecc, omega, T0, gam = [hof[0][j::6] for j in range(6)]
		print("%3s %12.1f %10.2f %10.2f %10.2f %15.2f %9.2f" % (planet, P[i], K[i], ecc[i], omega[i], T0[i], gam[i]) )
	
	msg = yellow('RESULT: ') + 'Best fitness value: %s\n' % (hof[0].fitness)
	clogger.info(msg)

	if just_gen: 
		# save fit in the system and return, no need for LM
		system.fit['params'] = hof[0]
		system.fit['chi2'] = hof[0].fitness/(len(system.time)-npar)
		return

	msg = blue('INFO: ') + 'Calling LM to improve result...'
	clogger.info(msg)	

	## call levenberg markardt fit
	lm = do_lm(system, [hof[0][j::6] for j in range(6)])
	lm_par = lm[0]
	
	## loop over planets
	msg = yellow('RESULT: ') + 'Best fit is'
	clogger.info(msg)
	print("%3s %12s %10s %10s %10s %15s %9s" % \
		('', 'P[days]', 'K[km/s]', 'e', unichr(0x3c9).encode('utf-8')+'[deg]', 'T0[days]', 'gam') )
	for i, planet in enumerate(list(ascii_lowercase)[:keplerians]):
		P, K, ecc, omega, T0, gam = [lm_par[j::6] for j in range(6)]
		print("%3s %12.1f %10.2f %10.2f %10.2f %15.2f %9.2f" % (planet, P[i], K[i], ecc[i], omega[i], T0[i], gam[i]) )

	chi2 = chi2_n(lm_par)[0]
	msg = yellow('RESULT: ') + 'Best fitness value: %f, %f' % (chi2, chi2/(len(system.time)-npar))
	clogger.info(msg)

	# save fit in the system
	system.fit['params'] = lm_par
	system.fit['chi2'] = chi2

	# #  print p.minFitness, p.maxFitness, p.avgFitness, p.sumFitness
	# print 'Genetic:', p.bestFitIndividual, p.bestFitIndividual.fitness
	# lm = do_lm(system, p.bestFitIndividual.genes)
	# lm_par = lm[0]
	# print 'LM:', lm_par

	# # get best solution curve
	# new_time = system.get_time_to_plot()
	# vel = zeros_like(new_time)

	# P, K, ecc, omega, t0 = p.bestFitIndividual.genes
	# get_rv(new_time, P, K, ecc, omega, t0, vel)
	# # plot RV with time
	# plot(system.time, system.vrad, 'o')
	# plot(new_time, vel, '-')

	# P, K, ecc, omega, t0 = lm_par
	# get_rv(new_time, P, K, ecc, omega, t0, vel)
	# plot(new_time, vel, 'r-')
	# show()

	return
Esempio n. 29
0
    def nest(self, parameter_s='', local_ns=None):
        """ Start the MultiNest analysis and handle data interaction and IO """
        from shell_colors import red

        try:
            args = parse_arg_string('nest', parameter_s)
        except DocoptExit:
            print nest_usage.lstrip()
            return
        except SystemExit:
            return
        # print args

        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return

        user = args['-u']
        resume = args['-r']
        verbose = args['-v']
        gp = args['--gp']
        jitter = args['--jitter']
        if gp and jitter:
            msg = red('ERROR: ') + '--gp and --jitter are incompatible'
            clogger.fatal(msg)
            return
        doplot = not args['--noplot']
        saveplot = args['--saveplot']
        dofeedback = args['--feed']
        doMAPfeedback = args['--MAPfeed']
        maxp = int(args['--maxp'])
        restart = args['--restart']
        nml_path = args['--nml']

        startp = args['--startp']
        if startp is not None:
            startp = [int(i) for i in startp.split(',')]
        else:
            startp = []

        try: 
            ncpu = int(args['--ncpu'])
        except TypeError:
            ncpu = None

        train_quantity = args['--train'] if bool(args['--train']) else None
        skip_train_mcmc = args['--skip-mcmc']
        lin_quantity = args['--lin'] if bool(args['--lin']) else None

        if bool(args['--train']) and not system.is_in_extras(train_quantity):
            msg = red('ERROR: ') + 'The name "%s" is not available in extras.\n' % train_quantity
            clogger.fatal(msg)
            return

        core.do_multinest(system, user, gp, jitter, maxp=maxp,
                          resume=resume, ncpu=ncpu, verbose=verbose,
                          training=train_quantity, skip_train_mcmc=skip_train_mcmc, lin=lin_quantity, 
                          doplot=doplot, saveplot=saveplot, feed=dofeedback, MAPfeed=doMAPfeedback,
                          restart=restart, nml=nml_path, startp=startp)
Esempio n. 30
0
    def restrict(self, parameter_s='', local_ns=None):
        """ Select data based on date, SNR or radial velocity accuracy.
        Type 'restrict -h' for more help
        """
        from shell_colors import yellow, blue, red
        args = parse_arg_string('restrict', parameter_s)

        if args == DocoptExit:
            msg = yellow('Warning: ') + "I'm not doing anything. Type restrict -h for help"
            clogger.fatal(msg)
            return

        # use default system or user defined
        if 'default' in local_ns:
            system = local_ns['default']
        else:
            msg = red('ERROR: ') + 'Set a default system or provide a system '+\
                                   'name with the -n option'
            clogger.fatal(msg)
            return


        if args['err']: 
            try:
                maxerr = float(args['<maxerr>'])
            except ValueError:
                msg = red('ERROR: ') + 'maxerr shoud be a number!'
                clogger.fatal(msg)
                return
            core.do_restrict(system, 'error', maxerr)

        if args['sn']: 
            try:
                maxsn = float(args['<maxsn>'])
            except ValueError:
                msg = red('ERROR: ') + 'maxsn shoud be a number!'
                clogger.fatal(msg)
                return
            core.do_restrict(system, 'sn', maxsn)



        if args['jd']:
            try:
                maxjd = int(args['<maxjd>'])
                minjd = int(args['<minjd>'])
            except ValueError:
                msg = red('ERROR: ') + 'minjd and maxjd shoud be integer numbers!'
                clogger.fatal(msg)
                return
            core.do_restrict(system, 'date', minjd, maxjd)

        if args['year']:
            try:
                yr = int(args['<yr>'])
            except ValueError:
                msg = red('ERROR: ') + 'yr shoud be a number!'
                clogger.fatal(msg)
                return
            core.do_restrict(system, 'year', yr)

        if args['years']:
            try:
                yr1 = int(args['<yr1>'])
                yr2 = int(args['<yr2>'])
            except ValueError:
                msg = red('ERROR: ') + 'yr1 and yr2 shoud be numbers!'
                clogger.fatal(msg)
                return
            core.do_restrict(system, 'years', yr1, yr2)

        if args['--gui']:
            core.do_restrict(system, 'gui')

        if args['--index']:
            core.do_restrict(system, 'index', args['--index'], noask=args['--noask'])