예제 #1
0
def display_equation(idx, symObj):
    if (isinstance(idx, str)):
        eqn = '\\[' + idx + ' = ' + latex(symObj) + '\\]'
        display_latex(eqn, raw=True)
    else:
        eqn = '\\[' + latex(idx) + ' = ' + latex(symObj) + '\\]'
        display_latex(eqn, raw=True)
    return
예제 #2
0
def pprint_matrix(data, digits=3):
    """Print a numpy array as a latex matrix."""
    header = (r"\begin{{pmatrix}}" r"{d}\end{{pmatrix}}")
    d = data.__str__()[1:-1]
    d = d.replace(']', '')
    d = d.replace('\n', r'\\')
    d = re.sub(r' *\[ *', '', d)
    d = re.sub(r' +', ' & ', d)
    display.display_latex(display.Latex(header.format(d=d)))
예제 #3
0
def pprint_matrix(data, digits=3):
    """Print a numpy array as a latex matrix."""
    header = r"\begin{{pmatrix}}" r"{d}\end{{pmatrix}}"
    d = data.__str__()[1:-1]
    d = d.replace("]", "")
    d = d.replace("\n", r"\\")
    d = re.sub(r" *\[ *", "", d)
    d = re.sub(r" +", " & ", d)
    display.display_latex(display.Latex(header.format(d=d)))
예제 #4
0
def pprint_matrix(data, digits=3):
    """Print a numpy array as a latex matrix."""
    header = (r"\begin{{pmatrix}}"
              r"{d}\end{{pmatrix}}")
    d=data.__str__()[1:-1]
    d = d.replace(']', '')
    d = d.replace('\n', r'\\')
    d = re.sub(r' *\[ *', '', d)
    d = re.sub(r' +', ' & ', d)
    display.display_latex(display.Latex(header.format(d=d)))
예제 #5
0
    def callback(r,m):
        from IPython.display import display_latex

        print "appy rule: %s" % r

        lt = pc.latex(r.search.subs(m,evaluate=False)),\
             pc.latex(r.replacement.subs(m,evaluate=False)),\
             r"\;\text{ if }\;%s" % pc.latex(r.condition.subs(m,evaluate=False)) if r.condition is not None else ''

        display_latex(r"$$%s \rightarrow %s%s$$" % lt,raw=True)
예제 #6
0
    def callback(r,m):
        from IPython.display import display_latex
        import sys

        print("appy rule: %s" % r)

        lt = pc.latex(r.search.subs(m,evaluate=False)),\
             pc.latex(r.replacement.subs(m,evaluate=False)),\
             r"\;\text{ if }\;%s" % pc.latex(r.condition.subs(m,evaluate=False)) if r.condition is not None else ''

        display_latex(r"$$%s \rightarrow %s%s$$" % lt,raw=True)
        sys.stdout.flush()
def print_equation(theta):
    """Displays a LaTeX equation for the polynomial with
    coefficients `theta`, where theta[-1] is the lowest
    order coefficient (the constant) and theta[0] is the
    highest order coefficient.
    
    Parameters
    ----------
    theta : numpy array with shape (k+1,)
        The coefficients of the polynomial, ordered from
        highest-order to lowest-order.
    
    """
    display_latex("$${}$$".format(format_equation(theta)), raw=True)
예제 #8
0
def print_equation(theta):
    """Displays a LaTeX equation for the polynomial with
    coefficients `theta`, where theta[-1] is the lowest
    order coefficient (the constant) and theta[0] is the
    highest order coefficient.
    
    Parameters
    ----------
    theta : numpy array with shape (k+1,)
        The coefficients of the polynomial, ordered from
        highest-order to lowest-order.
    
    """
    display_latex("$${}$$".format(format_equation(theta)), raw=True)
    
예제 #9
0
    def report_use_latex(self):
        """使用LaTex格式化报告
        """
        try:
            from IPython.display import display_latex, Math
            from sympy import init_printing
            init_printing()
        except ModuleNotFoundError:
            return self.__str__()

        for k, v in self.stats_result.items():
            if k not in self.report_filters:
                print(k)
                if isinstance(v, np.ndarray):
                    display_latex(Math(latex(Matrix(v))))
                else:
                    print(v)
                print()
        return "repr"
예제 #10
0
def concat_latex(exprs: typing.List[sympy.Expr],
                 labels: typing.List[str] = None,
                 label_names: typing.List[str] = None,
                 display=False):
    latex_exprs = [
        unwrap_latex(full_simplify(e)._repr_latex_()) for e in exprs
    ]
    if labels is not None and label_names is not None:
        label_strs = [
            '({})'.format(', '.join(
                '{}={:d}'.format(name, value)
                for name, value in zip(label_names, label)))
            for label in labels
        ]
    else:
        label_strs = len(exprs) * ['']
    combined = '\\begin{{split}} {} \\end{{split}}'.format(' \\\\ '.join(
        '{} &: {}'.format(label, expr)
        for label, expr in zip(label_strs, latex_exprs)))
    tex = wrap_latex(combined)

    if display:
        _display.display_latex(tex, raw=True)
    return tex
예제 #11
0
    def ovb_minimal_reporting(self, format = 'html', digits = 3, display = True):
        """
        ovb_minimal_reporting returns the LaTeX/HTML code for a table summarizing the sensemakr object.

        This function takes as input a sensemakr object, the digit to round number, one of the format type "latex" or "html",
        and a boolean whether to display the output or not. The default is round 3 digits, 'html' format and display the table.

        Parameters
        ----------
        format : string
            Either "latex" or "html" (Default value = 'html').
        display : boolean
            Default is True, to display the table.
        digits : int
            Rounding digit for the table (Default value = 3).

        Returns
        -------
        string
            LaTex/HTML code for creating the table summarizing the sensemakr object.

        Examples
        ---------
        >>> # Load example dataset:
        >>> import sensemakr as smkr
        >>> darfur = smkr.load_darfur()
        >>> # Fit a statsmodels OLSResults object ("fitted_model"):
        >>> import statsmodels.formula.api as smf
        >>> model = smf.ols(formula='peacefactor ~ directlyharmed + age + farmer_dar + herder_dar + pastvoted + hhsize_darfur + female + village', data=darfur)
        >>> fitted_model = model.fit()
        >>> # Runs sensemakr for sensitivity analysis
        >>> sensitivity = smkr.Sensemakr(model=fitted_model, treatment = "directlyharmed", q=1.0, alpha=0.05, reduce=True)
        >>> # Gets HTML code and table
        >>> result=sensitivity.ovb_minimal_reporting() # doctest: +SKIP
        >>> # Prints raw html code
        >>> print(result) # doctest: +SKIP
        """
        if(format=='latex'):
            result='\\begin{table}[!h] \n\\centering \n\\begin{tabular}{lrrrrrr} \n'+\
            "\\multicolumn{7}{c}{Outcome: \\textit{"+str(self.model.model.endog_names)+"}} \\\\\n"+\
            "\\hline \\hline \nTreatment: & Est. & S.E. & t-value & $R^2_{Y \\sim D |{\\bf X}}$"+\
            " & $RV_{q ="+str(self.q)+"}$"+ "& $RV_{q = "+str(self.q)+ ", \\alpha = "+str(self.alpha)+ "}$ " + " \\\\ \n"+ "\\hline \n"+\
            "\\textit{"+str(self.treatment)+ "} &"+str(round(self.sensitivity_stats['estimate'], digits))+ " & "+\
              str(round(self.sensitivity_stats['se'], digits))+ " & "+\
              str(round(self.sensitivity_stats['t_statistic'], digits))+" & "+\
              str(round(self.sensitivity_stats['r2yd_x']*100, digits-2))+ "\\% & "+\
              str(round(self.sensitivity_stats['rv_q']*100, digits-2))+ "\\% & "+\
              str(round(self.sensitivity_stats['rv_qa']*100, digits-2))+ "\\% \\\\ \n"+\
            "\\hline \n" + "df = "+str(self.sensitivity_stats['dof'])+ " & & "+"\\multicolumn{5}{r}{ "+( "}\n"+\
            "\\end{tabular}\n"+\
            "\\end{table}" if (self.bounds is None) else "\\small"+\
            "\\textit{Bound ("+str(self.bounds['bound_label'][0])+ ")}: "+\
            "$R^2_{Y\\sim Z| {\\bf X}, D}$ = "+\
            str(round(self.bounds['r2yz_dx'][0]*100, digits-2))+\
            "\\%, $R^2_{D\\sim Z| {\\bf X} }$ = "+\
            str(round(self.bounds['r2dz_x'][0]*100, digits-2))+\
            "\\%""}\\\\\n"+\
            "\\end{tabular}\n"+\
            "\\end{table}")

            if(display==True):
                from IPython.display import display_latex
                display_latex(result, raw=True)
            return result

        if(format=='html'):
            result="<table style='align:center'>\n"+"<thead>\n"+\
            "<tr>\n"+\
            '\t<th style="text-align:left;border-bottom: 1px solid transparent;border-top: 1px solid black"> </th>\n'+\
            '\t<th colspan = 6 style="text-align:center;border-bottom: 1px solid black;border-top: 1px solid black"> Outcome: '+\
            str(self.model.model.endog_names)+'</th>\n'+\
            "</tr>\n"+\
            "<tr>\n"+\
            '\t<th style="text-align:left;border-top: 1px solid black"> Treatment </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black"> Est. </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black"> S.E. </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black"> t-value </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black"> R<sup>2</sup><sub>Y~D|X</sub> </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black">  RV<sub>q = '+\
            str(self.q)+ '</sub> </th>\n'+\
            '\t<th style="text-align:right;border-top: 1px solid black"> RV<sub>q = '+\
            str(self.q)+ ", &alpha; = "+\
            str(self.alpha)+ "</sub> </th>\n"+\
            "</tr>\n"+\
            "</thead>\n"+\
            "<tbody>\n <tr>\n"+\
            '\t<td style="text-align:left; border-bottom: 1px solid black"><i>'+\
            str(self.treatment)+ "</i></td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['estimate'], digits))+ " </td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['se'], digits))+ " </td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['t_statistic'], digits-2))+" </td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['r2yd_x']*100, digits-2))+ "% </td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['rv_q']*100, digits-2))+ "% </td>\n"+\
            '\t<td style="text-align:right;border-bottom: 1px solid black">'+\
            str(round(self.sensitivity_stats['rv_qa']*100, digits-2))+"% </td>\n"+\
            "</tr>\n</tbody>\n"+\
            ('<tr>\n'+\
            "<td colspan = 7 style='text-align:right;border-top: 1px solid black;border-bottom: 1px solid transparent;font-size:11px'>"+\
            "Note: df = "+str(self.sensitivity_stats['dof'])+\
            "</td>\n"+\
            "</tr>\n"+\
            "</table>" if (self.bounds is None) else "<tr>\n"+\
            "<td colspan = 7 style='text-align:right;border-top: 1px solid black;border-bottom: 1px solid transparent;font-size:11px'>"+\
            "Note: df = "+ str(self.sensitivity_stats['dof'])+ "; "+\
            "Bound ( "+str(self.bounds['bound_label'][0])+ " ):  "+\
            "R<sup>2</sup><sub>Y~Z|X,D</sub> =  "+\
            str(round(self.bounds['r2yz_dx'][0]*100, digits-2))+\
            "%, R<sup>2</sup><sub>D~Z|X</sub> ="+\
            str(round(self.bounds['r2dz_x'][0]*100, digits-2))+\
            "%"+\
            "</td>\n"+\
            "</tr>\n"+\
            "</table>")

            if(display==True):
                from IPython.display import display_html
                display_html(result, raw=True)

            return result