Exemple #1
0
    def draw(self, to_file):
        # Tegn spørgsmålet
        text = r'Example of equation: $\displaystyle %s $' % latex(self.func)

        fig = plt.figure(figsize=plotting.QUESTION_FIGSIZE)
        fig.text(x=.05,
                 y=.9,
                 s=r'Example text 1',
                 color=plotting.COLOR_BLACK,
                 fontsize=plotting.TEXT_LARGE)
        fig.text(x=.5,
                 y=.5,
                 s=text,
                 color=plotting.COLOR_BLACK,
                 fontsize=plotting.TEXT_LARGE,
                 horizontalalignment='center')
        fig.text(x=.05,
                 y=.25,
                 s=r'Example text 2',
                 color=plotting.COLOR_BLACK,
                 fontsize=plotting.TEXT_LARGE,
                 horizontalalignment='left',
                 verticalalignment='center')
        fig.text(x=.05,
                 y=.13,
                 s=r'Example text 3',
                 color=plotting.COLOR_BLACK,
                 fontsize=plotting.TEXT_LARGE,
                 horizontalalignment='left',
                 verticalalignment='center')
        fig.savefig(to_file, dpi=plotting.DPI)
        plt.close()
Exemple #2
0
    def draw(self, to_file):
        # Create figure
        if DANISH:
            text1 = r'Integralet $\displaystyle\int f(x)dx$, hvor $f$ er en funktion, ser efter '\
                r'substitutionen $\displaystyle {}={}$ således ud:'\
                r'$$\int {} du$$'\
                r'Hvad er $\displaystyle\int f(x)dx$?'.format(u,latex(self.substitution),latex(self.integrant))
        else:
            pass

        fig = plt.figure(figsize=plotting.QUESTION_FIGSIZE)


        text = r'\begin{{minipage}}{{550px}}' \
               r'{0} \\' \
               r'\end{{minipage}}'.format(text1)

        fig.text(x=.05,
                 y=.87,
                 s=text,
                 color=plotting.COLOR_BLACK,
                 horizontalalignment='left',
                 verticalalignment='top',
                 fontsize=plotting.TEXT_LARGE)

        fig.savefig(to_file, dpi=plotting.DPI)
        plt.close()
Exemple #3
0
 def draw(self, to_file):
     # Tegn spørgsmålet
     text = r'Example of equation: $\displaystyle %s $' % latex(self.func)
     
     fig = plt.figure(figsize=plotting.QUESTION_FIGSIZE)
     fig.text(x=.05,
              y=.9,
              s=r'Example text 1',
              color=plotting.COLOR_BLACK,
              fontsize=plotting.TEXT_LARGE)
     fig.text(x=.5,
              y=.5,
              s=text,
              color=plotting.COLOR_BLACK,
              fontsize=plotting.TEXT_LARGE,
              horizontalalignment='center')
     fig.text(x=.05,
              y=.25,
              s=r'Example text 2',
              color=plotting.COLOR_BLACK,
              fontsize=plotting.TEXT_LARGE,
              horizontalalignment='left',
              verticalalignment='center')
     fig.text(x=.05,
              y=.13,
              s=r'Example text 3',
              color=plotting.COLOR_BLACK,
              fontsize=plotting.TEXT_LARGE,
              horizontalalignment='left',
              verticalalignment='center')
     fig.savefig(to_file, dpi=plotting.DPI)
     plt.close()
Exemple #4
0
    def draw(self, to_file):
        # Create figure
        if DANISH:
            text1 = r'$\displaystyle {0}$'.format(latex(self.value))
        else:
            pass

        fig = plt.figure(figsize=plotting.ANSWER_FIGSIZE)
        fig.text(x=.5,
                 y=.45,
                 s=text1,
                 color=plotting.COLOR_BLACK,
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontsize=plotting.TEXT_LARGE)

        fig.savefig(to_file, dpi=plotting.DPI)
        plt.close()
Exemple #5
0
 def draw(self, to_file):        
     text = latex(random.randrange(1,4)*self.var)
     if random.choice([0,1])==0:
         some_matrix = Matrix([[1,2,3],[4,Integer(3)/Integer(4),6],[-7,a,9]])
         text = latex_matrix(some_matrix)
         if random.choice([0,1])==0:
             text = latex_matrix(some_matrix, equation_system=True)
     
     fig = plt.figure(figsize=plotting.ANSWER_FIGSIZE)
     fig.text(x=.5,
              y=.5,
              s=r'$%s$' % text,
              color=plotting.COLOR_BLACK,
              fontsize=plotting.TEXT_LARGE,
              horizontalalignment='center',
              verticalalignment='center')
     fig.savefig(to_file, dpi=plotting.DPI)
     plt.close()
Exemple #6
0
    def draw(self, to_file):
        text = latex(random.randrange(1, 4) * self.var)
        if random.choice([0, 1]) == 0:
            some_matrix = Matrix([[1, 2, 3], [4, Integer(3) / Integer(4), 6],
                                  [-7, a, 9]])
            text = latex_matrix(some_matrix)
            if random.choice([0, 1]) == 0:
                text = latex_matrix(some_matrix, equation_system=True)

        fig = plt.figure(figsize=plotting.ANSWER_FIGSIZE)
        fig.text(x=.5,
                 y=.5,
                 s=r'$%s$' % text,
                 color=plotting.COLOR_BLACK,
                 fontsize=plotting.TEXT_LARGE,
                 horizontalalignment='center',
                 verticalalignment='center')
        fig.savefig(to_file, dpi=plotting.DPI)
        plt.close()
Exemple #7
0
def physical_quantity_latex(
        value,
        displaystyle=True,
        display_unity_factor=False,
        units=(),
        substitute_derived_units=True,
):
    value = sp.sympify(value)
    # Seperate numeric factor from variables and units
    factor_numeric = value.subs({symbol: 1 for symbol in value.free_symbols})
    factor_symbolic = value / factor_numeric
    # Use both numeric and symbolic factor?
    use_numeric = True
    use_symbolic = True
    if factor_symbolic == 1 or factor_symbolic == sp.nan:
        use_symbolic = False
    if factor_numeric == 1 and use_symbolic:
        # Keep redundant factor of 1?
        if not display_unity_factor:
            use_numeric = False
    elif factor_numeric == -1 and use_symbolic:
        # Move factor of -1 onto symbolic part?
        if not display_unity_factor:
            factor_symbolic *= -1
            use_numeric = False
    # Latexify numeric factor
    factor_numeric_latex = latex(factor_numeric) if use_numeric else ''
    # Latexify symbolic factor (use roman units)
    if use_symbolic:
        # Substitute units for derived units
        if substitute_derived_units:
            for bases, derived in derived_units.items():
                factor_symbolic_updated = factor_symbolic.subs(bases, derived)
                if factor_symbolic_updated != factor_symbolic:
                    factor_symbolic = factor_symbolic_updated
                    if str(derived) not in units:
                        units += (str(derived), )
        # Latexify
        factor_symbolic_latex = latex(
            factor_symbolic.subs({
                sp.Symbol(unit, positive=True): 'latex' + unit
                for unit in units
            }))
        factor_symbolic_latex_backup = factor_symbolic_latex
        interunit_space = r'\mkern+2mu'
        for unit in units:
            factor_symbolic_latex = factor_symbolic_latex.replace(
                'latex' + unit,
                r'{}\mathrm{{{}}}'.format(interunit_space, unit))
        if factor_symbolic_latex.startswith(interunit_space):
            factor_symbolic_latex = factor_symbolic_latex[len(interunit_space
                                                              ):]
    else:
        factor_symbolic_latex = ''
    # Construct LaTeX string
    s = r'{displaystyle} {numeric} {space} {symbolic}'.format(
        displaystyle=(r'\displaystyle' if displaystyle else r'\textstyle'),
        numeric=factor_numeric_latex,
        space=('\,' if r'\mathrm' in factor_symbolic_latex else ''),
        symbolic=factor_symbolic_latex,
    )
    return s
 def draw(self,
          ax=None,
          subs={},
          color='k',
          colorsegments=None,
          xboundary=(-10, +10),
          yboundary=(-10, +10),
          zboundary=(-10, +10),
          headplacement=0.8,
          axes_order='xyz',
          ring={},
          **kwargs):
     """The variables xboundary an yboundary defines a bounding
     rectangle for the "infinite" wires.
     The headplacement defines the placement of the arrowhead and
     should be between 0 and 1.
     Colorsegments is a sequence of (float, color) pairs,
     where the floats should be between 0 and 1. This is used to
     draw the wire in different colors.
     If supplied, ring should be a dict with the keys 'r', 'x', 'y'
     and 'z'. A ring with the specified radius will be placed at the
     specified position, rotated so that the wire penetrates it.
     This can be used to show wher the wire passes through a grid.
     """
     if ax is None:
         ax = plt.gca()
     if colorsegments is None:
         colorsegments = [(1, color)]
     plot3D = False
     if '3D' in ax.__class__.__name__:
         plot3D = True
     # Symbolic --> numeric
     point = np.array(
         [float(sp.sympify(el).subs(subs)) for el in self.point.pos])
     direction = np.array([float(el) for el in self.direction])
     # If direction is exactly horizontal/vertical,
     # perturb it slightly (this avoids division by zero later).
     eps = np.finfo('double').eps
     for i, el in enumerate(direction):
         if abs(el) < 10 * eps:
             direction[i] = 10 * eps
     # Find "boundary points" of infinite wire
     boundary_points = [None, None]
     for dim, boundary in enumerate((xboundary, yboundary, zboundary)):
         if not plot3D and dim == 2:
             break
         tmin = (boundary[0] - point[dim]) / direction[dim]
         tmax = (boundary[1] - point[dim]) / direction[dim]
         candidate_start_point = point + tmin * direction
         candidate_end_point = point + tmax * direction
         if (abs(tmin / tmax) < 1e+6 and xboundary[0] - 10 * eps <=
                 candidate_start_point[0] <= xboundary[1] + 10 * eps
                 and yboundary[0] - 10 * eps <= candidate_start_point[1] <=
                 yboundary[1] + 10 * eps and zboundary[0] - 10 * eps <=
                 candidate_start_point[1] <= zboundary[1] + 10 * eps):
             # Accept start point
             boundary_points[0] = candidate_start_point
             Tmin = tmin
         if (abs(tmax / tmin) < 1e+6 and xboundary[0] - 10 * eps <=
                 candidate_end_point[0] <= xboundary[1] + 10 * eps
                 and yboundary[0] - 10 * eps <= candidate_end_point[1] <=
                 yboundary[1] + 10 * eps and zboundary[0] - 10 * eps <=
                 candidate_end_point[1] <= zboundary[1] + 10 * eps):
             # Accept end point
             boundary_points[1] = candidate_end_point
             Tmax = tmax
     L = abs(Tmax - Tmin)
     # Plot line
     xend = boundary_points[0][0]
     yend = boundary_points[0][1]
     zend = boundary_points[0][2]
     arrowheadcolor_backward = None
     data = []
     for t, c in colorsegments:
         xstart = xend
         ystart = yend
         zstart = zend
         xend = boundary_points[0][0] + t * (boundary_points[1][0] -
                                             boundary_points[0][0])
         yend = boundary_points[0][1] + t * (boundary_points[1][1] -
                                             boundary_points[0][1])
         zend = boundary_points[0][2] + t * (boundary_points[1][2] -
                                             boundary_points[0][2])
         data.append((
             (xstart, xend),
             (ystart, yend),
             (zstart, zend),
         ))
         if headplacement <= t:
             arrowheadcolor_forward = c
         if headplacement >= t and arrowheadcolor_backward is None:
             arrowheadcolor_backward = c
     if not plot3D:
         # 2D
         for d, (t, c) in zip(data, colorsegments):
             ax.plot(d[0], d[1], '-', color=c, linewidth=2, **kwargs)
     else:
         # 3D
         for d, (t, c) in zip(data, colorsegments):
             ax.plot(d[axes_order.index('x')],
                     d[axes_order.index('y')],
                     d[axes_order.index('z')],
                     '-',
                     color=c,
                     linewidth=2,
                     clip_on=False,
                     **kwargs)
         # Ring showing grid penetration.
         # See the accepted answer at http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
         if ring:
             N = 50
             theta = np.linspace(0, 2 * np.pi, N)
             x = ring['r'] * np.cos(theta)
             y = ring['r'] * np.sin(theta)
             z = np.zeros(N)
             a = np.array((0, 0, 1))
             b = direction
             v = np.cross(a, b)
             s = float(norm(v))
             c = np.dot(a, b)
             M = np.array((
                 (0, -v[2], v[1]),
                 (v[2], 0, -v[0]),
                 (-v[1], v[0], 0),
             ))
             R = np.eye(3) + M + np.dot(M, M) / (1 + c + eps)
             data = np.dot(R, np.array((x, y, z)))
             data[0] += ring['x']
             data[1] += ring['y']
             data[2] += ring['z']
             ax.plot(
                 data[axes_order.index('x')],
                 data[axes_order.index('y')],
                 data[axes_order.index('z')],
                 color=color,
                 linewidth=1,
             )
     # Make sure that the current flows from boundary_points[0] to boundary_points[1]
     arrowheadcolor = arrowheadcolor_forward
     if np.dot(boundary_points[1] - boundary_points[0], direction) < 0:
         boundary_points[0], boundary_points[1] = boundary_points[
             1], boundary_points[0]
         arrowheadcolor = arrowheadcolor_backward
     # Plot arrow head
     arrow_to = boundary_points[0] + headplacement * L * direction
     arrow_from = arrow_to - 1e-6 * (arrow_to - boundary_points[0])
     if not plot3D:
         ax.add_patch(
             patches.FancyArrowPatch(
                 arrow_from[:2],
                 arrow_to[:2],
                 color=arrowheadcolor,
                 linewidth=2,
                 arrowstyle='-|>',
                 mutation_scale=20,
                 clip_on=False,
             ))
     else:
         data = (
             (arrow_from[0], arrow_to[0]),
             (arrow_from[1], arrow_to[1]),
             (arrow_from[2], arrow_to[2]),
         )
         ax.add_artist(
             draw.Arrow3D(
                 data[axes_order.index('x')],
                 data[axes_order.index('y')],
                 data[axes_order.index('z')],
                 color=arrowheadcolor,
                 linewidth=2,
                 arrowstyle='-|>',
                 mutation_scale=20,
                 clip_on=False,
             ))
     # Current label
     offset_fac_parallel = 0.024
     offset_fac_perpendicular = 0.024
     offset_parallel = (headplacement + offset_fac_parallel) * L * direction
     offset_perpendicular = offset_fac_perpendicular * L * np.array(
         (direction[1], -direction[0], 0))
     if abs(direction[0]) < abs(direction[1]):
         # More of less vertical line.
         # Align to the right.
         horizontalalignment = 'right'
         if direction[1] < 0:
             # Direction downward. Shift label further down.
             offset_parallel[1] -= 0.05 * L
         # Offset to the left
         fac = 2.0
         offset_perpendicular[0] = -fac * abs(offset_perpendicular[0])
     else:
         # More of less horizontal line
         if direction[0] < 0:
             # Direction to the left. Align to the right.
             horizontalalignment = 'right'
             #
             offset_parallel[0] -= 0.015 * L
         else:
             # Direction to the right. Align to the left.
             horizontalalignment = 'left'
             #
             offset_parallel[0] += 0.015 * L
         # Offset upwards
         offset_perpendicular[1] = +abs(offset_perpendicular[1])
     label_pos = boundary_points[0] + offset_parallel + offset_perpendicular
     if not plot3D:
         ax.text(
             label_pos[0],
             label_pos[1],
             '${}$'.format(latex(self.magnitude)),
             fontsize=plotting.TEXT_SMALL,
             horizontalalignment=horizontalalignment,
         )
     else:
         data = label_pos
         ax.text(
             data[axes_order.index('x')],
             data[axes_order.index('y')],
             data[axes_order.index('z')],
             '${}$'.format(latex(self.magnitude)),
             fontsize=plotting.TEXT_SMALL,
             horizontalalignment=horizontalalignment,
         )