def print_poly(P, dim, name): """ Prints a MIMO polynomial model. Parameters ---------- P : ndarray Polynomial model to be displayed. dim : array_like Number of outputs (ny) and inputs (nu) in this order, that is, [ny, nu]. name : string Name displayed for the polynomial model. Returns ------- """ s = poly_to_str(P) rows, cols = dim[0], dim[1] index = 0 for row in range(rows): for col in range(cols): if rows == 1 and cols == 1: # Prints SISO subcase display(Math(r'' + name + '(q^{-1}) = ' + s[index])) else: # Prints general MIMO case poly_index = "{" + str(row + 1) + str(col + 1) + "}" display( Math(r'' + name + "_" + poly_index + '(q^{-1}) = ' + s[index])) index = index + 1
def fit_plot(temp, prof, verbose=True, preroll=True): if isinstance(temp, SinglePulse): sptemp = temp else: sptemp = SinglePulse(temp, windowsize=256) rollval = sptemp.getNbin() / 2 - np.argmax(sptemp.data) if isinstance(prof, SinglePulse): spprof = prof else: spprof = SinglePulse(prof, mpw=sptemp.mpw) if preroll: sptemp.shiftit(rollval, save=True) spprof.shiftit(rollval, save=True) tauccf, tauhat, bhat, sigma_tau, sigma_b, snr, rho = spprof.fitPulse( sptemp.data) if verbose: display(Math(r'\hat{\tau} = %0.1f \pm %0.1f' % (tauhat, sigma_tau))) display(Math(r'\hat{b} = %0.1f \pm %0.1f' % (bhat, sigma_b))) if preroll: sptemp.shiftit(-1 * rollval, save=True) spprof.shiftit(-1 * rollval, save=True) rotatedtemp = sptemp.shiftit(tauhat) figure(figsize=(10, 8)) subplot(211) plot(prof.data, 'k') plot(bhat * rotatedtemp, 'r', lw=2) xlim(0, len(prof.data)) ylabel("Profile") subplot(212) plot(prof.data - bhat * rotatedtemp, 'k') xlim(0, len(prof.data)) xlabel("Phase Bins") ylabel("Difference Profile") return tauhat, bhat
def exer_mult_step(expression): import re import sympy as sym from sympy import init_printing init_printing() from IPython.display import display, Math, Latex a, b, c, x, y, z = sym.symbols("a b c x y z") expression = str(expression) evexpr = sym.expand(eval(expression)) print 'Expand the following expression step by step:' display(Math(str(expression).replace('**', '^').replace('*', ''))) print 'Multiply ALL the monomials:' factor = re.split('\)\s*\*\s*\(', str(expression)) refactor = [ re.split('\(|\)', factor[i])[1 - i] for i in range(len(factor)) ] terms = [ re.split(':', re.sub('\s*(\+|\-)\s*', r':\1', refactor[i])) for i in range(len(refactor)) ] expandednr = '' for i in range(len(terms[0])): #nci='' if terms[0][i]: nci = terms[0][i] terms[0][i] = r'{\color{red}{%s}}' % terms[0][i] for j in range(len(terms[1])): #ncj='' if terms[1][j]: ncj = terms[1][j] terms[1][j] = r'\color{red}{%s}' % terms[1][j] l = jointerms(terms) display(Math(l.replace('**', '^').replace('*', ''))) terms[1][j] = ncj newterm = raw_input() if re.search('^-', newterm): newterm = newterm else: newterm = '+' + newterm expandednr = expandednr + newterm expandednr = re.sub('^\+', '', expandednr) terms[0][i] = nci print 'Reduce the expression:' display(Math(expandednr.replace('**', '^').replace('*', ''))) result = raw_input() if evexpr == eval(result): print "Good job!, final result:" return eval(result) else: print('WRONG!!!\nRight result:') return sym.expand(expression)
def getMagneticFieldHarmonics(self): E1, E2, H1, H2 = self.getFields() a_y = Matrix([[0, 1, 0]]) n = Symbol(self.n_str) vars_fourier = [self.Ex1, self.Ey1, self.Ez1, self.sigma_d, self.sigma_o] H1 = d1_putSums(H1, vars_fourier, self.z, self.harmonic) vars_fourier = [self.Ex1, self.Ey1, self.Ez1, self.sigma_d, self.sigma_o] H2 = d1_putSums(H2, vars_fourier, self.z, self.harmonic) if self.vbose: display(Math('H_1 = ' + latex(H1.T))) display(Math('H_2 = ' + latex(H2.T))) H1 = Matrix([[H1[i].doit() for i in range(H1.cols)]]) H2 = Matrix([[H2[i].doit() for i in range(H2.cols)]]) H1 = d1_applyConvolutions(H1, self.z, self.harmonic) H2 = d1_applyConvolutions(H2, self.z, self.harmonic) if self.vbose: display(Math('H_1 = ' + latex(H1.T))) display(Math('H_2 = ' + latex(H2.T))) H1 = Matrix([[d1_applyOrthogonalities(H1[i], self.z, self.harmonic)\ for i in range(H1.cols)]]) H2 = Matrix([[d1_applyOrthogonalities(H2[i], self.z, self.harmonic)\ for i in range(H2.cols)]]) if self.vbose: display(Math('\\tilde{H}_1 = ' + latex(H1.T))) display(Math('\\tilde{H}_2 = ' + latex(H2.T))) H1 = Matrix([[simplify(symExp_replaceFunction(H1[i], self.Ey1_tilde, self.Ey1_rep)\ /exp(-I*self.k*self.z-self.alpha*self.y)) for i in range(H1.cols)]]) H2 = Matrix([[simplify(symExp_replaceFunction(H2[i], self.Ey1_tilde, self.Ey1_rep)\ /exp(-I*self.k*self.z+self.alpha*self.y)) for i in range(H2.cols)]]) if self.vbose: display(Math('\\tilde{H}_1 = ' + latex(H1.T))) display(Math('\\tilde{H}_2 = ' + latex(H2.T))) return [H1, H2]
def __init__(self, expression, dictionary=None): if dictionary is None: dictionary = inspect.stack()[1][0].f_globals latex = '' for x in expression.split(): if x in dictionary: if isinstance(dictionary[x], np.ndarray): latex += ' ' + self.ndarray_to_latex(dictionary[x]) else: latex += ' ' + self.number_to_latex(dictionary[x]) else: latex += ' ' + str(x) from IPython.display import Math self.display = Math(latex)
def getFields(self): E1 = Matrix([[self.Ex1, self.Ey1, self.Ez1]])\ *exp(-I*self.k*self.z-self.alpha*self.y) # upper region E2 = Matrix([[self.Ex1, -self.Ey1, self.Ez1]])\ *exp(-I*self.k*self.z+self.alpha*self.y) # upper region if self.vbose: display(Math('E_1 = ' + latex(E1))) display(Math('E_2 = ' + latex(E2))) H1 = -1/(I*self.omega*self.mu)*curl_r(E1) H2 = -1/(I*self.omega*self.mu)*curl_r(E2) if self.vbose: display(Math('H_1 = ' + latex(H1))) display(Math('H_2 = ' + latex(H2))) return [E1, E2, H1, H2]
def forma_geral_solucao(hessiana, solucao): markdown(f'## Solução: {solucao}') markdown('### Hessiana') hessiana = simplify(hessiana.subs(solucao)) display(hessiana) markdown('### Sistema Linear ') x1, x2 = var('x1 x2', real=True) x1l, x2l = var("x'_1 x'_2", real=True) matrizx1lx2l = Matrix([[x1l], [x2l]]) matrizx1x2 = Matrix([[x1], [x2]]) math(f'{latexc(matrizx1lx2l)}={latexc(hessiana)}{latexc(matrizx1x2)}') math(f'{latexc(matrizx1lx2l)}={latexc(hessiana*matrizx1x2)}') markdown('### Solução geral: ') t = var(f't', real=True) e = var(f'e', real=True) l = var(f'\lambda', real=True) matriz00 = Matrix([[0], [0]]) matrizLambda = Matrix([[l, 0], [0, l]]) partes = [] for i, (autovalor, multiplicity, matriz) in enumerate(simplify(hessiana).eigenvects()): ci = var(f'c{i+1}', real=True) partes.append([ci, matriz[0], e**(autovalor * t)]) markdown(f""" * **Multiplicidade**: {multiplicity} * **Autovalor:** {autovalor} * **Autovetor** """) display( Math( f'{latexc(matrizLambda-hessiana)}{latexc(matrizx1x2)}={latexc(matriz00)}' )) display( Math( f'{latexc((matrizLambda-hessiana).subs({l: autovalor}))}{latexc(matrizx1x2)}={latexc(matriz00)}' )) display(Math(f'{latexc(matrizx1x2)}={latexc(matriz[0])}')) #Eq(x1x2, partes[0] + partes[1]) markdown('**General solution to this linear system**') parte1 = ''.join([latexc(it) for it in partes[0]]) parte2 = ''.join([latexc(it) for it in partes[1]]) math(f'{latexc(matrizx1x2)}={parte1}+{parte2}')
def to_latex(self, jupyter_display=False, outer=False): cont = "-" + self.inverse.to_latex() if cont and jupyter_display: display(Math(cont)) display(Markdown("<details><pre>$" + cont + "$</pre></details>")) else: return cont
def display_evaluation(self, lookup: Callable, intermediates: Iterable[Intermediate]): line_latex = [ self.get_evaluation_latex() # r"0.4 \times {0.2}^2 + {0.8}^2 + 0.6 \times {0.3}^2 + {0.7}^2", ] start = r"""\begin{align} """ end = r""" \end{align} """ current_expr = self._rs for inter in intermediates: if inter is Intermediate.EXPAND_OUTER_SUM and isinstance( current_expr, SumOverFiniteSet): current_expr = current_expr.expand() line_latex.append(Displayable._to_latex(current_expr)) if inter is Intermediate.SUBSTITUTE_ALL: current_expr: Displayable current_expr = current_expr._substituted(lookup) line_latex.append( Displayable._to_latex(current_expr, numerify_descendents=True)) if inter is Intermediate.GET_RESULT: line_latex.append(str(round(current_expr._try_get_value(), 3))) # noinspection PyTypeChecker i_display(Math(start + "\\\\ \n &= ".join(line_latex) + end))
def dist_interact(P, S, d_0, n=50): # Interactively plot the unconditional distribution of X_n where {X_n, n >= 0} is a DTMC xlabels = list(map(str, S)) p = bplt.figure(x_range=xlabels) # Create a Bokeh figure source = ColumnDataSource(data=dict(x=xlabels, top=d_0)) # Start with d_0 glyph = VBar(x="x", top="top", bottom=0, width=0.8, fill_color='blue') # Specify a vertical bar plot labels = LabelSet(x='x', y='top', text='top', text_align='center', source=source) # Label each bar with the value p.add_glyph(source, glyph) p.add_layout(labels) p.yaxis.axis_label = 'd_n' p.y_range = Range1d(0, 1) handle = None def update(n): # Function for updating the data and pushing to the figure handle source.data['top'] = np.round( np.dot(d_0, np.linalg.matrix_power(P, n)), 4) if handle is not None: push_notebook(handle=handle) display(Math(r'$d_0 = ' + pmatrix([d_0], frac=True) + '$')) # Display initial distribution # Interactive slider and plot widgets.interact(update, n=widgets.IntSlider(value=0, min=0, max=n, description='n')) handle = show(p, notebook_handle=True)
def show_var(name, value, units=None, *, boxed=False, fmt='#.3g'): """Show the value of a variable using LaTeX. Parameters ---------- name : str The name (in LaTeX format) of the variable. value The value of the variable to show. units : str, optional The units of the variable. (default: None) Keyword-only parameters ----------------------- boxed : bool, optional If True, draw a box around the entire expression. (default: False) fmt : str, optional Format string used to display `value`. (default: '#.3g') """ if units is None: units = '' else: units = r'~\mathrm{%s}' % units eqn = f'{name} = {value:{fmt}}{units}' if boxed: eqn = r'\boxed{%s}' % eqn display(Math(eqn))
def pretty_print_lti(this_lti): num_str_aux = build_poly_str(this_lti.num) den_str_aux = build_poly_str(this_lti.den) display(Math(r'\frac{' + num_str_aux + '}{' + den_str_aux + '}'))
def to_latex(self, jupyter_display=False, outer=False): cont = r"\text{ln}(" + self.argument.to_latex() + ")" if cont and jupyter_display: display(Math(cont)) display(Markdown("<details><pre>$" + cont + "$</pre></details>")) else: return cont
def print_model(self): result = r"E = " result += r"{0:.2f} \cdot 10^{{49}}".format( 10**self.model.intercept.value / 1e49) result += r" \cdot n_0^{{ {0:.2f} }}".format(self.model.slope.value) result += r" \text{ [ergs]}" display(Math(result))
class NumpyToLatex: def __init__(self, expression, dictionary=None): if dictionary is None: dictionary = inspect.stack()[1][0].f_globals latex = '' for x in expression.split(): if x in dictionary: if isinstance(dictionary[x], np.ndarray): latex += ' ' + self.ndarray_to_latex(dictionary[x]) else: latex += ' ' + self.number_to_latex(dictionary[x]) else: latex += ' ' + str(x) from IPython.display import Math self.display = Math(latex) def ndarray_to_latex(self, ndarray): lines = str(ndarray).replace('[', '').replace(']', '').splitlines() x = [r'\begin{bmatrix}'] x += [' ' + ' & '.join(l.split()) + r'\\' for l in lines] x += [r'\end{bmatrix}'] return '\n'.join(x) def number_to_latex(self, number): return "{:.2f}".format(number) def _repr_latex_(self): return self.display._repr_latex_()
def show_res(Eq1, kd='', kreturn=False, kdisp=False): kres = Eq1 if kdisp or kd != '': sR = kd + ' =' display(Math(sR + latex(kres))) if kreturn: return (kres)
def csolveset(Eq, kv, kd='', kdisp=False): kres = solveset(Eq, kv) kres = list(kres) if kdisp or kd != '': sR = kd + ' =' display(Math(sR + latex(kres))) return (kres)
def get_sub2_arg(keq, k1, k2, kd=' ', kdisp=True): sR = kd + ' =' kres = keq.args[k1] kres = kres.args[k2] if kdisp: display(Math(sR + latex(kres))) return (kres)
def internalfluxbox(mvs): out = Output(layout=Layout(height='auto', width=cws[0])) with out: for k, v in mvs.get_InternalFluxesBySymbol().items(): display(Math("F_{" + str(k) + "} = " + latex(v))) return out
def to_latex(self, jupyter_display=False, outer=False): cont = latex_ratio(self.value) if cont and jupyter_display: display(Math(cont)) display(Markdown("<details><pre>$" + cont + "$</pre></details>")) else: return cont
def to_latex(self, jupyter_display=False, outer=False): cont = self.base.to_latex() + "^{" + self.exponent.to_latex() + "}" if cont and jupyter_display: display(Math(cont)) display(Markdown("<details><pre>$" + cont + "$</pre></details>")) else: return cont
def iprint_latex(variable_name: str, variable_value=None, short: bool = False): """Display variables in IPython notebooks using LaTeX markup. Uses `math_object_to_latex`. This function sorts the input ``mobj`` if it is a :class:`~.Set` or a :class:`~.Multiset` to make the output consistent, so be careful with big (multi)sets. (Such large (multi)sets where this is a problem may not be suitable to display in LaTeX anyway.) :param variable_name: The name of the variable to display. :param variable_value: (Optional) The value of the variable. If it is missing, the variable value is fetched from the caller's frame; a variable with the name ``variable_name`` is assumed to exist in this case. :param short: (Optional) When set to ``True``, a short version of the content is generated. Longer parts are abbreviated with ellipses ('...'). Defaults to ``False``. See also `Config.short_atom_len` and `Config.short_set_len`. .. note:: This function imports from ``IPython`` and expects IPython to be installed. This is generally given when running in an IPython notebook. """ from IPython.display import Math, display if variable_value is None: variable_value = _misc.get_variable(variable_name, frames_up=1) variable_latex = math_object_to_latex(variable_value, short=short) variable_name_latex = variable_name.replace('_', r'\_') latex = '{name} = {value}'.format(name=variable_name_latex, value=variable_latex) display(Math(latex))
def latex_print(poly: Polynomial): """ Print a numpy's Polynomial LaTeX(ish)ly. Args: poly (Polynomial): a polynomial to be printed in LaTeX or whatever this is. """ result = '' coeffs = poly.coef[::-1] coeffs_num = len(coeffs) for (p, coeff) in enumerate(coeffs): power = coeffs_num - 1 - p if coeff: sign = '+' if coeff > 0 else '' result += sign result += str(round(coeff, 4)) if power: result += 'x' if power > 1: result += f'^{{{power}}}' result = result.lstrip('+') display(Math(result))
def array_to_latex(array, precision=5, pretext="", display_output=True): """Latex representation of a complex numpy array (with dimension 1 or 2) Args: matrix (ndarray): The array to be converted to latex, must have dimension 1 or 2. precision: (int) For numbers not close to integers, the number of decimal places to round to. pretext: (str) Latex string to be prepended to the latex, intended for labels. display_output: (bool) if True, uses IPython.display to display output, otherwise returns the latex string. Returns: str: Latex representation of the array, wrapped in $$ Raises: ValueError: If array can not be interpreted as a numerical numpy array ValueError: If the dimension of array is not 1 or 2 """ try: array = np.asarray(array) array + 1 # Test array contains numerical data except: raise ValueError( "array_to_latex can only convert numpy arrays containing numerical data, or types that can be converted to such arrays" ) if array.ndim == 1: output = vector_to_latex(array, precision=precision, pretext=pretext) elif array.ndim == 2: output = matrix_to_latex(array, precision=precision, pretext=pretext) else: raise ValueError( "array_to_latex can only convert numpy ndarrays of dimension 1 or 2" ) if display_output: display(Math(output)) else: return (output)
def display_parsing_table(self, raw=False): begin = r"\begin{array}{|" begin += r"|".join(["c"] * (len(self.terminals) + 1)) begin += r"|}" + '\n' end = r"\end{array}" # create the header header = "\t\hline \n" + "\t" + r"\text{terminal}" for terminal in self.terminals: header += "\t&" header += terminal header += r'\\ \hline' + "\n" cells = "" for nonterminal in self.rules.keys(): line = "\t" + nonterminal for terminal in self.terminals: line += " \t&" if terminal in self.parsing_table[nonterminal]: line += self.display_rule( left=nonterminal, rule=self.parsing_table[nonterminal][terminal], new_line=False, array_environment=False) # line += r"\\ \hline" + '\n' line += r"\\ " + '\n' cells += line cells += r"\hline" + "\n" content = begin + header + cells + end display(Math(content)) if raw: syntax = Syntax(content, "latex") Console().print(syntax)
def display_header_pj(in_val: str = None, include_top: bool = True, include_bot: bool = True) -> int: """Display a basic header (fundamentally a set of strings, but the input text is displayed using latex) Keyword Arguments: in_val {str} -- A string to display using display (default: {None}) Returns: int -- status """ status = 0 try: if in_val is None: sp.pprint(_header_element_) else: if include_top: sp.pprint(_header_element_) status, full_sentence = _display_l_(in_val, _jup_math_eq_delim_) display(Math(full_sentence)) if include_bot: sp.pprint(_header_element_) return None except: status = 1 return status
def transmon_print_all_params(Lj_nH, Cs_fF): """ Linear harmonic oscillator approximation of transmon. Convinince func """ # Parameters - duplicates with transmon_get_all_params Ej, Ec = Convert.Ej_from_Lj(Lj_nH, 'nH', 'MHz'), Convert.Ec_from_Cs( Cs_fF, 'fF', 'MHz') # MHz Lj_H, Cs_F = Convert.Lj_from_Ej(Ej, 'MHz', 'H'), Convert.Cs_from_Ec( Ec, 'MHz', 'F') # SI units Phi_ZPF, Q_ZPF = Convert.ZPF_from_LC(Lj_H, Cs_F) Omega_MHz = sqrt(1. / (Lj_H * Cs_F)) * 1E-6 # MHz # Print text = r""" \begin{align} L_J &=%.1f \mathrm{\ nH} & C_\Sigma &=%.1f \mathrm{\ fF} \\ E_J &=%.2f \mathrm{\ GHz} & E_C &=%.0f \mathrm{\ MHz} \\ \omega_0 &=2\pi\times %.2f \mathrm{\ GHz} & Z_0 &= %.0f \mathrm{\ \Omega} \\ \phi_\mathrm{ZPF} &= %.2f \ \ \phi_0 & n_\mathrm{ZPF} &=%.2f \ \ (2e) \\ \end{align} """ % (Lj_H * 1E9, Cs_F * 1E15, Ej / 1E3, Ec, Omega_MHz / (2 * pi) * 1E-3, sqrt(Lj_H / Cs_F), Phi_ZPF / fluxQ, Q_ZPF / (2 * e_el)) from IPython.display import display, Math display(Math(text)) return text
def display(*M, names=None): s = "" if (names is None): names = ["" for i in range(len(M)) ] for i, m in enumerate(M): s+= LA.M(m, name=names[i], call_display=False, showdim=False); display(Math(s))
def display_j(in_list: list = None) -> int: """This is a top level routine which displays output in Jupyter using mathjax NOTE: This is currently only tested with Google Colaboratory Keyword Arguments: in_list {list} -- The list of stuff to display (default: {None}) Returns: int -- discription of the status """ status = 0 try: assert in_list is not None except: status = 1 print("The in_list must not be None.") return status #Main body of work try: #Obtain the latex status, full_sentence = _display_l_(in_list, _jup_math_eq_delim_) #Use display(Math) to output the latex of the sympy expression to the output of a compute cell display(Math(full_sentence)) return None except Exception as e: status = 2 print("Something went amiss with the mathjax process. Details: {}". format(e)) return status return status
def test_image(img): obj = Model('test', cnn_pretrain_path='working_on_best_model/model/rweights.h5', batch_size=1, image=img) print img obj.predict_hand() import numpy as np import re from IPython.display import display, Math, Latex, Image imgs = np.load('working_on_best_model/model/pred_imgs_hw.npy') preds = np.load('working_on_best_model/model/pred_latex_hw.npy') properties = np.load( '/home/abhitrip/Downloads/website/working_on_best_model/model/properties.npy' ).tolist() displayPreds = lambda Y: display(Math(Y.split('#END')[0])) idx_to_chars = lambda Y: ' '.join( map(lambda x: properties['idx_to_char'][x], Y)) #displayIdxs = lambda Y: display(Math(''.join(map(lambda x: properties['idx_to_char'][x],Y)))) preds_chars = idx_to_chars(preds[0, 1:]).replace('$', '') output = preds_chars.split('#END')[0] return output