示例#1
0
 def __call__(self, **kwargs):
     """
     This function should perform some sanity checks, but right now it does nothing.
     """
     cf = CommonFunctions(self)
     cf.phycassert(not model.update_freqs_separately, 'update_freqs_separately is no longer allowed')
     cf.phycassert(not model.update_relrates_separately, 'update_freqs_separately is no longer allowed')
示例#2
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes ParamSummarizer object.

        """
        CommonFunctions.__init__(self, opts)
示例#3
0
 def __call__(self, **kwargs):
     cf = CommonFunctions(self)
     cf.phycassert(not self.update_freqs_separately, 'update_freqs_separately is no longer allowed')
     cf.phycassert(not self.update_relrates_separately, 'update_freqs_separately is no longer allowed')
     self.set(**kwargs)
     self.checkModelParameters(cf)
     return self.saveas()
示例#4
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes MCMCImpl object by assigning supplied phycas object
        to a data member variable.

        """
        CommonFunctions.__init__(self, opts)
        self.opts = opts
        self.sitelikef = None
示例#5
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes ScriptGenImpl object.

        """
        CommonFunctions.__init__(self, opts)
        self.script_filename = None
        self.scriptf = None
        self.sampledata_filename = None
        self.samplef = None
示例#6
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes RefDistImpl object.

        """
        CommonFunctions.__init__(self, opts)
        self.skip = None
        self.epsilon = None
        self.rooted = None
        self.refdistf = None
        self.rooted_trees = False
        self.out_refdist_file_name = None
        self.min_sample_size = 1
示例#7
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes the SimulateImpl object by assigning supplied phycas object
        to a data member variable.

        """
        CommonFunctions.__init__(self, opts)
        self.starting_tree_source = None
        self.starting_tree        = None
        #self.ntax                 = None
        self.sim_model_tree       = None
        self.data_matrix          = None
        self.nchar                = opts.nchar
示例#8
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes the LikeImpl object by assigning supplied phycas object
        to a data member variable.

        """
        CommonFunctions.__init__(self, opts)
        self.starting_tree         = None
        self.taxon_labels          = None
        self.data_matrix           = None
        self.ntax                  = None
        self.nchar                 = None
        self.reader                = NexusReader()
        self.npatterns          = []        # Will hold the actual number of patterns for each subset after data file has been read
示例#9
0
    def __call__(self, **kwargs):
        global _fixed_terminal_width

        self.set(**kwargs)
        c = copy.deepcopy(self)
        self.cf = CommonFunctions(c)

        ok = self._openCommandReferenceFile()
        if ok:
            # temporarily fix terminal width to 80 characters
            setFixedTerminalWidth(80)

            # loop through all phycas command classes and write current settings for each to file
            for cmd in PhycasHelp._phycas_cmd_classes:
                if not cmd.hidden():
                    c = cmd()
                    s = c.help.current()
                    command_name_string = self.formatNameString(c.help.cmd_name)
                    asterisks_full = '*'*80
                    self.cmdreff.write('\n\n%s\n%s\n%s\n' % (asterisks_full, command_name_string, asterisks_full))
                    self.cmdreff.write('%s\n' % s)
            self.cf.output('Command reference saved to the file %s' % self.cmdreff_filename)

            # return terminal width to None so that it can adapt to actual terminal width
            setFixedTerminalWidth(None)

            closed_ok = self._closeCommandReferenceFile()
            if not closed_ok:
                self.cf.output('An error was encountered: the command reference file %s could not be closed.' % self.cmdreff_filename)
        else:
            self.cf.output('Sorry, an error was encountered: the command reference file %s could not be created.' % self.cmdreff_filename)
示例#10
0
    def __init__(self, opts):
        # ---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Initializes TreeSummarizer object by assigning supplied phycas object
        to a data member variable.

        """
        CommonFunctions.__init__(self, opts)
        self.r = self._getLot()
        eld = self.edgelen_dist
        self._current = 0
        self.trees = []
        if eld is None:
            if self.distribution.lower() != "yule":
                raise ValueError("edgelen_dist must be set if the tree simulator's distribution is not Yule")
            if self.speciation_rate is None:
                raise ValueError(
                    "edgelen_dist or the speciation_rate must be set to generate trees from the Yule process"
                )
        else:
            eld.setLot(self.r)
        self.stdout.debugging("Generating %s" % str(self))
示例#11
0
 def __init__(self):
     CommonFunctions.__init__(self, None)
     self.pdf_splits_to_plot = None
     # Variables associated with PDF tree drawing (used in pdftree() function)
     # The 14 standard fonts guaranteed to be available in all PDF consumer applications:
     #   Times-Roman      Helvetica             Courier             Symbol
     #   Times-Bold       Helvetica-Bold        Courier-Bold        ZapfDingbats
     #   Times-Italic     Helvetica-Oblique     Courier-Oblique
     #   Times-BoldItalic Helvetica-BoldOblique Courier-BoldOblique
     self.pdf_filename                 = 'trees.pdf'    # Set to desired name of pdf file to create
     self.pdf_edge_support_file        = None           # File containing PAUP* output with table of support values; if specified, the support values will be shown on trees plotted
     self.pdf_tip_label_font           = 'Times-Italic' # Font used for tip node names; should be one of the 14 standard fonts listed above
     self.pdf_tip_label_height         = 12             # Height in points of tip node name font
     self.pdf_plot_label_font          = 'Helvetica'    # Font used for plot axis labels; should be one of the 14 standard fonts listed above
     self.pdf_plot_label_height        = 12             # Height in points of plot axis label font
     self.pdf_title_font               = 'Helvetica'    # Font used for scalebar text; should be one of the 14 standard fonts listed above
     self.pdf_title_height             = 14             # Height in points of scalebar text font
     self.pdf_scalebar_position        = 'bottom'       # Valid values are 'top', 'bottom' or None
     self.pdf_scalebar_label_font      = 'Helvetica'    # Font used for scalebar text; should be one of the 14 standard fonts listed above
     self.pdf_scalebar_label_height    = 10             # Height in points of scalebar text font
     self.pdf_support_label_font       = 'Times-Roman'  # Font used for edge support values; should be one of the 14 standard fonts listed above
     self.pdf_support_label_height     = 8              # Height in points of edge support font
     self.pdf_support_as_percent       = True           # If True, support values will be shown as percentages (e.g. 93.1) rather than proportions (e.g. 0.931)
     self.pdf_support_decimals         = 1              # The number of decimal places shown in support values (e.g. to get 93.7, specify 1; to round up to 94, specify 0)
     self.pdf_ladderize                = 'right'        # Valid values are 'right', 'left' or None
     self.pdf_page_width               = 8.5            # Page width in inches
     self.pdf_page_height              = 11.0           # Page length in inches
     self.pdf_line_width               = 1.0            # Width of lines representing edges in the tree
     self.pdf_left_margin              = 1.0            # Left margin in inches (1 inch = 72 points)
     self.pdf_right_margin             = 1.0            # Right margin in inches (1 inch = 72 points)
     self.pdf_top_margin               = 1.0            # Top margin in inches (1 inch = 72 points)
     self.pdf_bottom_margin            = 1.0            # Bottom margin in inches (1 inch = 72 points)
     self.keep_xy_proportional         = True           # If True, vertical dimension of each tree in a collection will be kept proportional to its horizontal dimension
     self.keep_tip_labels_proportional = True           # If True, tip label height will be kept commensurate with size of tree for each tree in a printed collection (smaller trees will have smaller tip labels)
     self.pdf_treefile                 = None           # Set to tree file name if you want to make one pdf file with each tree from tree file on a separate page
     self.pdf_newick                   = None           # Set to the tree description to print if only want to save one tree to a pdf file
     self.pdf_outgroup_taxon           = None           # Set to taxon name of tip serving as the outgroup for display rooting purposes (note: at this time outgroup can consist of just one taxon)
示例#12
0
class Commands(PhycasCommand):
    def __init__(self):
        o = PhycasCommandOutputOptions()
        o.__dict__["_help_order"] = ["filename"]

        t = TextOutputSpec(prefix='phycas-command-reference', suffix=".txt", help_str="The document generated by this command.")
        o.__dict__["filename"] = t

        PhycasCommand.__init__(self, None, "commands", "Saves command reference to filename specified (phycas-command-reference.txt by default)", o)

        self.__dict__["cmdreff"] = None
        self.__dict__["cmdreff_filename"] = None
        self.__dict__["cf"] = None

    def hidden():
        """
        Overrides the PhycasCommand.hidden method to keep CmdRef's name from being displayed
        in the list of classes displayed when users type help. Delete this function, or
        change its return value to False, when it is ready to be advertised.
        """
        return False

    hidden = staticmethod(hidden)

    def checkSanity(self):
        """
        Place asserts in this function that should be checked before anything substantive
        is done during a call of a CmdRef object.
        """
        pass

    def _openCommandReferenceFile(self):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Opens the output file.

        """
        self.cf.phycassert(self.cmdreff is None, 'Attempt made to open command reference file, but it is already open!')
        self.cmdreff_filename = self.cf.opts.out.filename._getFilename()
        try:
            self.cmdreff = self.cf.opts.out.filename.open(self.cf.stdout)
        except:
            print '*** Attempt to open command reference file (%s) failed.' % self.cmdreff_filename

        status = (self.cmdreff is not None) and (self.cmdreff)
        return status

    def _closeCommandReferenceFile(self):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Closes the output file.

        """
        self.cf.phycassert(self.cmdreff is not None, 'Attempt made to close command reference file, but it is not open!')
        self.cmdreff.close()
        status = self.cmdreff.closed
        self.cmdreff = None
        return status

    def formatNameString(self, command_name):
        nasterisks_total = 80 - len(command_name) - 2
        asterisks_before = '*'*(nasterisks_total//2)
        asterisks_after = '*'*(nasterisks_total//2)
        if nasterisks_total % 2 == 1:
            asterisks_after += '*'
        return asterisks_before+' '+command_name+' '+asterisks_after

    def __call__(self, **kwargs):
        global _fixed_terminal_width

        self.set(**kwargs)
        c = copy.deepcopy(self)
        self.cf = CommonFunctions(c)

        ok = self._openCommandReferenceFile()
        if ok:
            # temporarily fix terminal width to 80 characters
            setFixedTerminalWidth(80)

            # loop through all phycas command classes and write current settings for each to file
            for cmd in PhycasHelp._phycas_cmd_classes:
                if not cmd.hidden():
                    c = cmd()
                    s = c.help.current()
                    command_name_string = self.formatNameString(c.help.cmd_name)
                    asterisks_full = '*'*80
                    self.cmdreff.write('\n\n%s\n%s\n%s\n' % (asterisks_full, command_name_string, asterisks_full))
                    self.cmdreff.write('%s\n' % s)
            self.cf.output('Command reference saved to the file %s' % self.cmdreff_filename)

            # return terminal width to None so that it can adapt to actual terminal width
            setFixedTerminalWidth(None)

            closed_ok = self._closeCommandReferenceFile()
            if not closed_ok:
                self.cf.output('An error was encountered: the command reference file %s could not be closed.' % self.cmdreff_filename)
        else:
            self.cf.output('Sorry, an error was encountered: the command reference file %s could not be created.' % self.cmdreff_filename)
示例#13
0
文件: SS.py 项目: Linhua-Sun/phycas
 def checkSanity(self):
     """
     Place asserts in this function that should be checked before anything substantive
     is done during a call of a SS object.
     """
     cf = CommonFunctions(self)
     if self.refdist_is_prior and self.refdistfile is not None:
         cf.phycassert(False, 'cannot specify ss.refdist_is_prior = True and also specify a reference distribution using ss.refdistfile')
     if not self.refdist_is_prior and self.refdistfile is None:
         cf.phycassert(False, 'ss.refdist_is_prior is False but you have not specified a reference distribution (i.e. ss.refdistfile is None)')
     cf.phycassert(mcmc.ncycles > 0, 'mcmc.ncycles cannot be less than 1 for the stepping-stone method')
     cf.phycassert(mcmc.allow_polytomies == False or self.ti == True, "mcmc.allow_polytomies must be False to use the generalized stepping-stone method (we're working on relaxing this requirement)")
     #if not self.override_fixed_topology_restriction:
     #    cf.phycassert(mcmc.fix_topology == True, "mcmc.fix_topology must be True to use the stepping-stone method (we're working on relaxing this requirement)")
     models = partition.getModels()
     if len(models) > 0:
         m = models[0]
     else:
         m = model
     if m.edgelen_hyperprior:
         cf.warning("the generalized stepping-stone method has only been tested on models in which model.edgelen_hyperprior = None (proceed at your own risk)")
示例#14
0
    def __init__(self, opts):
        #---+----|----+----|----+----|----+----|----+----|----+----|----+----|
        """
        Gathers information relevant to Gelfand-Ghosh calculations from the
        parent GG object.

        """
        CommonFunctions.__init__(self, opts)

        self.nsamples                   = 0
        self.last_error                 = None

        self.bincountsf                 = None  # filename used for bin counts file
        self.postpredf                  = None  # filename used for post pred. files

        self.starting_tree_source       = None
        self.gg_bin_patterns            = opts.gg_bin_patterns
        self.gg_num_bins                = opts.gg_num_bins
        self.pfile                      = None
        self.tfile                      = None
        self.model                      = None
        self.model_type                 = None
        self.data_matrix                = None
        self.likelihood                 = None
        self.ntax                       = 0
        self.nchar                      = 0
        self.npatterns                  = 0
        self.params                     = None
        self.trees                      = None
        self.is_invariable_sites_model  = False
        self.is_discrete_gamma_model    = False

        self.num_edgelen_hyperparams    = 0

        self.stored_trees               = None  # list of trees built from tree definitions in the trees file
        self.taxon_labels               = None  # list of taxon labels from the data matrix
        self.param_file_lines           = None  # list of lines from the params file (header lines excluded)
        self.param_headers              = None  # list of parameter headers from the param file (self.param_names is a subset of this list)
        self.tree_objects               = None  # dictionary in which keys are unique tree identifiers, and values are tree objects
        self.parameters                 = None  # dictionary in which keys are unique tree identifiers, and values are lists
                                                #   e.g. self.parameters[tree_id][j] = {'rAG': -4.2432, 'freqC': -2.3243, ...}
                                                #   where tree_id is a list of split representations uniquely identifying a particular tree
                                                #   and j is the index of the (j+1)th sample pertaining to that tree. The keys in the
                                                #   dictionary (e.g. 'rAG') are parameter names and the values are transformed parameter values
        self.edge_lengths               = None  # dictionary in which keys are unique tree identifiers, and values are lists
                                                #   e.g. self.edge_lengths[tree_id][j] = {'-**-**--': -1.2345, '-*****--':-2.14225, ...}
                                                #   where tree_id is a list of split representations uniquely identifying a particular tree
                                                #   and j is the index of the (j+1)th sample from that tree. The keys in the dictionary (e.g. '-**-**--')
                                                #   are string representations of splits and the values are log-transformed edge lengths
        self.sample_size                = None  # self.sample_size[tid] is the sample size (after skip samples have been removed) for tree tid
        self.log_like                   = None  # list of log likelihood values gleaned from the params file
        self.log_prior                  = None  # list of log prior values gleaned from the params file
        self.log_posterior              = None  # list of log posterior values gleaned from the params file


        # initialize quantities used in Gelfand-Ghosh calculations
        self.gg_simdata             = likelihood.SimData()     # temporary container used to hold nascent posterior predictive simulation results until they have been analyzed
        self.gg_y                   = likelihood.SimData()     # observed dataset
        self.gg_mu                  = likelihood.SimData()     # mean of all posterior predictive datasets

        self.minbins                = None
        self.gg_binned_simdata      = None   # if self.gg_bin_patterns is True, this vector of floats is used to summarize the counts in self.gg_simdata
        self.gg_binned_y            = None   # if self.gg_bin_patterns is True, this vector of floats is used instead of self.gg_y
        if self.gg_num_bins == 7:
            self.minbins                = True
            self.gg_binned_mu           = [0.0]*7
        elif self.gg_num_bins == 15:
            self.minbins                = False
            self.gg_binned_mu           = [0.0]*15
        else:
            assert False, 'gg_num_bins must be set to either 7 or 15 (%d was specified in this case)' % self.gg_num_bins

        self.gg_a                   = []            # vector of compromise actions (one for each k in kvalues)
        self.gg_npatterns           = []            # vector containing the number of patterns in each posterior predictive dataset
        self.gg_t                   = []            # vector of t values computed from posterior predictive datasets
        self.gg_t_y                 = 0.0           # t for original dataset
        self.gg_t_mean              = 0.0           # mean of t over all posterior predictive datasets
        self.gg_t_mu                = 0.0           # t of mean over all posterior predictive datasets
        self.gg_t_a                 = []            # vector of t values computed from compromise action (one for each k in kvalues)
        self.gg_Pm                  = 0.0           # penalty component (same for all k)
        self.gg_Gm                  = []            # vector of goodness-of-fit components (one for each k in kvalues)
        self.gg_Dm                  = []            # vector of overall measures (one for each k in kvalues)
        self.gg_num_post_pred_reps  = 0.0           # counts total number of posterior predictive simulations performed
        self.gg_total               = 0