'''
Created on 01-Apr-2021
@author: rishi_priyansh
'''

import random
import inspect
import traceback
from sympy import (symbols, Symbol)

from xv.km.util import latex_fraction, latex_atom
from .....helper import BaseHelper

from xv.km.managers import BaseManager
from xv.km.kelements import KProblemTemplate
        
class PolarizationManager(BaseManager):
    '''
    PolarizationManager
    Example:
        ke = PolarizationManager()
        ke.getRandomProblem()
        ke.getRandomProblem(problem_type = 0)
        ...
        
        ke.printProblem()
        ke.printAnswer()
        ke.printSolution()
        
        ke.printProblemTypes()
        
    '''    
    _OPR_TYPE_COUNT = 10
    
    def __new__(cls, *args, **kwargs):
        instance = super(PolarizationManager, cls).__new__(cls, *args, **kwargs)
        for base_class in PolarizationManager.__bases__:
            base_class.__init__(instance, *args, **kwargs)
        return instance
    
    def __init__(self, *args, **kwargs):
        pass



    def _init_problem_types(self, *args, **kwargs):
        self._append_problem_types([
            '_problem_5_157',
            '_problem_5_158',
            '_problem_5_159',
            '_problem_5_160',
            '_problem_5_161',            
            '_problem_5_162',            
            '_problem_5_163',
            '_problem_5_164',
            ])     
        pass

    
    def _problem_5_157(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.157. A plane monochromatic wave of natural light with intensity $I_0$ falls normally on a screen composed of two touching Polaroid
        half-planes. The principal direction of one Polaroid is parallel,
        and of the other perpendicular, to the boundary between them.
        What kind of diffraction pattern is formed behind the screen? What
        is the intensity of light behind the screen at the points of the plane
        perpendicular to the screen and passing through the boundary
        between the Polaroids? 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.157 Natural light can be considered to be an incoherent mixture of two plane polarized light of intensity $I_{{0}} / 2$ with mutually perpendicular planes of vibration. The screen cbnsisting of the two polaroid half-planes acts as an opaque half-screen for one or the other of these light waves. The resulting diffraction pattern has the alterations in intensity (in the illuminated region) characteristic of a straight edge on both sides of the boundary.

        At the boundary the intensity due to either component is
        $$
        \frac{{\left(I_{{0}} / 2\right)}}{{4}}
        $$

        and the total intensity is $\frac{{I_{{0}}}}{{4}}$. (Recall that when light of intensity $I_{{0}}$ is incident on a straight edge, the illuminance in front of the edge is $I_{{0}} / 4$ )

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    def _problem_5_158(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.158. A plane monochromatic wave of natural light with intensity $I_0$, falls normally on an opaque screen with round hole corresponding to the first Fresnel zone for the observation point P. Find
        the intensity of light at the point P after the hole was covered with
        two identical Polaroids whose principal directions are mutually
        perpendicular and the boundary between them passes
        (a) along the diameter of the hole;
        (b) along the circumference of the circle limiting the first half
        of the Fresnel zone. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.158 '(a) Assume first that there is no polaroid and the amplitude due to the entire hole which extends over the first Fresnel zone is $A_{{1}}$
        Then, we know, as usual, $I_{{0}}=\frac{{A_{{1}}^{{2}}}}{{4}}$,
        When the polaroid is introduced as shown above, each half transmits only the corresponding polarized light. If the full hole were covered by one polaroid the amplitude transmitted will be $\left(A_{{1}} / \sqrt{{2}}\right)$.

        Therefore the amplitude transmitted in the present case will be $\frac{{A_{{1}}}}{{2 \sqrt{{2}}}}$ through either half. Since these transmitted waves are polarized in mutually perpendicular planes, the total intensity will be
        $$
        \left(\frac{{A_{{1}}}}{{2 \sqrt{{2}}}}\right)^{{2}}+\left(\frac{{A_{{1}}}}{{2 \sqrt{{2}}}}\right)^{{2}}=\frac{{A_{{1}}^{{2}}}}{{4}}=I_{{0}}
        $$

        (b) We interpret the problem to mean that the two polaroid pieces are separated along the circumference of the circle limiting the first half of the Fresnel zone. (This however is inconsistent with the polaroids being identical in shape; however no other interpretation makes sense.)
        From (5.103) and the previous problems we see that the amplitudes of the waves transmitted through the two parts is
        $$
        \frac{{A_{{1}}}}{{2 \sqrt{{2}}}}(1+i) \text {{ and }} \frac{{A_{{1}}}}{{2 \sqrt{{2}}}}(1-i)
        $$
        and the intensity is
        $$
        \begin{{gathered}}
        \left|\frac{{A_{{1}}^{{2}}}}{{2 \sqrt{{2}}}}(1+i)\right|^{{2}}+\left|\frac{{A_{{1}}}}{{2 \sqrt{{2}}}}(1-i)\right|^{{2}} \\
        =\frac{{A_{{1}}^{{2}}}}{{2}}=2 I_{{0}}
        \end{{gathered}}
        $$

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    def _problem_5_159(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.159. A beam of plane-polarized light falls on a polarizer which
        rotates about the axis of the ray with angular velocity $\omega$ = 21 rad/s.
        Find the energy of light passing through the polarizer per one revolution
        if the flux of energy of the, incident ray is equal to $\Phi_0$ = 4.0 mW.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.159 When the polarizer rotates with angular velocity $\omega$ its instantaneous principal direction makes angle $\omega t$ from a reference direction which we choose to be along the direction of vibration of the plane polarized incident light. The transmitted flux at this instant is
        $$
        \Phi_{{0}} \cos ^{{2}} \omega t
        $$
        and the total energy passing through the polarizer per revolution is
        $$
        \begin{{gathered}}
        &\int_{{0}}^{{T}} \Phi_{{0}} \cos ^{{2}} \omega t d t, \quad T=2 \pi / \omega \\
        &=\Phi_{{0}} \frac{{\pi}}{{\omega}}=0.6 \mathrm{{~m}} \mathrm{{~J}}
        \end{{gathered}}
        $$
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_5_160(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.70. Two coherent plane light waves propagating with a divergence 
        angle $\psi$ << 1 fall almost normally on a screen. The amplitudes
        of the waves are equal. Demonstrate that the distance between the
        neighbouring maxima on the screen is equal to $\Delta x = \lambda / \psi$, where $\lambda$
        is the wavelength.
        
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.70 We can think of the two coherent plane waves as emitted from two coherent point sources very far away. Then
        $$
        \begin{{gathered}}
        \Delta x=\frac{{l \lambda}}{{d}}=\frac{{\lambda}}{{d / l}} \\
        \end{{gathered}}
        $$
        But
        $$
        \begin{{gathered}}
        \frac{{d}}{{l}}=\psi(\text {{ if }} \psi<1) \\
        \end{{gathered}}
        $$
        so
        $$
        \begin{{gathered}}
        \Delta x=\frac{{\lambda}}{{\psi}}
        \end{{gathered}}
        $$
        
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    def _problem_5_161(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.71. Figure 5.14 illustrates the interference experiment with
        Fresnel mirrors. The angle between the mirrors is a = 12', the
        distances from the mirrors' intersection line to the narrow slit S
        and the screen Sc are equal to r = 10.0 cm and b = 130 cm respectively. The wavelength of light is $\lambda$ = 0.55 p.m. Find:
        (a) the width of a fringe on the screen and the number of possible
        maxima;
        (b) the shift of the interference pattern on the screen when the
        slit is displaced by $\delta l$ = 1.0 mm along the arc of radius r with
        centre at the point 0;
        (c) at what maximum width $\delta_{{max}}$ of the slit the interference fringes
        on the screen are still observed sufficiently sharp. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        $5.71$ (a) Here $S^{{\prime}} S^{{\prime \prime}}=d=2 r \alpha$
        Then $\Delta x=\frac{{(b+r) \lambda}}{{2 \alpha}}$
        Putting $b=1.3$ metre,$r= 0.1$ metre
        $\lambda=0.55 \mu \mathrm{{m}}, \alpha=12^{{\prime}}=\frac{{1}}{{5 \times 57}}$ radian
        we get $\Delta x=1.1 \mathrm{{~mm}}$
        Number of possible maxima $=\frac{{2 b \alpha}}{{\Delta x}}+1 \sim 8.3+1 \approx 9$
        $(2 b) \alpha$ is the length of the spot on the screen which gets light after reflection from both mirror. We add 1 above to take account of the fact that in a distance $\Delta x$ there are two maxima).
        
        (b) When the silt moves by $\delta l$ along the arc of radius $r$ the incident ray on the mirror rotates by $\frac{{\delta l}}{{r}} ;$ this is the also the rotation of the reflected ray. There is then a shift of the fringe of magnitude.
        $$
        b \frac{{\delta l}}{{r}}=13 \mathrm{{~mm}}
        $$
        (c) If the width of the slit is $\delta$ then we can imagine the slit to consist of two narrow slits with separation $\delta$. The fringe pattern due to the wide slit is the superposition of the pattern due to these two narrow slits. The full pattern will not be sharp at all if the pattern due to the two narrow slits are $\frac{{1}}{{2}} \Delta x$ apart because then the maxima due to one will fill the minima due to the other. Thus we demand that
        $$
        \frac{{b\delta_{{\max }}}}{{r}} = \frac{{1}}{{2}}\Delta x = \frac{{\left( b + r \right)}}{{4 r \alpha}}
        $$
        or
        $$
        \delta_{{\max }}=\left(1+\frac{{r}}{{b}}\right) \frac{{\lambda}}{{4 \alpha}}=42 \mu \mathrm{{m}}
        $$

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
       
    def _problem_5_162(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.64 Demonstrate that when two harmonic oscillations are added,
        the time-averaged energy of the resultant oscillation is equal to
        the sum of the energies of the constituent oscillations, if both of
        them
        (a) have the same direction and are incoherent, and all the values
        of the phase difference between the oscillations are equally probable;
        (b) are mutually perpendicular, have the same frequency and
        an arbitrary phase difference. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        $5.64$ (a) In this case the net vibration is given by
        $$
        x=a_{{1}} \cos \omega t+a_{{2}} \cos (\omega t+\delta)
        $$
        where $\delta$ is the phase difference between the two vibrations which varies rapidly and randomly in the interval $(0,2 \pi)$. (This is what is meant by incoherence.)
        Then
        $$
        x=\left(a_{{1}}+a_{{2}} \cos \delta\right) \cos \omega t+a_{{2}} \sin \delta \sin \omega t
        $$
        The total energy will be taken to be proportional to the time average of the square of the displacement.
        Thus
        $$
        E=<\left(a_{{1}}+a_{{2}} \cos \delta\right)^{{2}}+a_{{2}}^{{2}} \sin ^{{2}} \delta>=a_{{1}}^{{2}}+a_{{2}}^{{2}}
        $$
        as $\langle\cos \delta\rangle=0$ and we have put $\left\langle\cos ^{{2}} \omega t\right\rangle=\left\langle\sin ^{{2}} \omega t\right\rangle=\frac{{1}}{{2}}$ and has been absorbed in the overall constant of proportionality.
        
        In the same units the energies of the two oscillations are $a_{{1}}^{{2}}$ and $a_{{2}}^{{2}}$ respectively so the proposition is proved.
        (b) Here $\quad \vec{{r}}=a_{{1}} \cos \omega t \hat{{i}}+a_{{2}} \cos (\omega t+\delta) \hat{{j}}$
        and the mean square displacement is $\alpha a_{{1}}^{{2}}+a_{{2}}^{{2}}$
        if $\delta$ is fixed but arbitrary. Then as in (a) we see that $E=E_{{1}}+E_{{2}}$.

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    def _problem_5_163(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.65 By means of plotting find the amplitude of the oscillation
        resulting from the addition of the following three oscillations of the
        same direction: 
        $$
        \xi_{{1}}=a \cos \omega t, \quad \xi_{{2}}=2 a \sin \omega t, \quad \xi_{{3}}=1.5 a \cos (\omega t+\pi / 3)
        $$

        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.65 It is easier to do it analytically.
        $$
        \begin{{gathered}}
        \xi_{{1}}=a \cos \omega t, \xi_{{2}}=2 a \sin \omega t \\
        \xi_{{3}}=\frac{{3}}{{2}} a\left(\cos \frac{{\pi}}{{3}} \cos \omega t-\sin \frac{{\pi}}{{3}} \sin \omega t\right)
        \end{{gathered}}
        $$
        Resultant vibration is
        $$
        \xi=\frac{{7 a}}{{4}} \cos \omega t+a\left(2-\frac{{3 \sqrt{{3}}}}{{4}}\right) \sin \omega t
        $$
        This has an amplitude $=\frac{{a}}{{4}} \sqrt{{49+(8-3 \sqrt{{3}})^{{2}}}}=1 \cdot 89 a$
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    def _problem_5_164(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.66. A certain oscillation results from the addition of coherent
        oscillations of the same direction $\xi_k = a cos [\omega t (k - 1) \varphi]$,
        where k is the number of the oscillation (k = 1, 2, . . N), $\varphi$ is
        the phase difference between the kth and (k - 1)th oscillations.
        Find the amplitude of the resultant oscillation.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.66 We use the method of complex amplitudes. Then the amplitudes are
        $$
        A_{{1}}=a, A_{{2}}=a e^{{i \varphi}}, \ldots A_{{N}}=a e^{{i(N-1) \varphi}}
        $$
        and the resultant complex amplitude is
        $$
        \begin{{aligned}}
        A &=A_{{1}}+A_{{2}}+\ldots+A_{{N}}=a\left(1+e^{{i \varphi}}+e^{{2 i \varphi}}+\ldots+e^{{i(N-1) \varphi}}\right) \\
        &=a \frac{{1-e^{{i N \varphi}}}}{{1-e^{{i \varphi}}}}
        \end{{aligned}}
        $$
        The corresponding ordinary amplitude is
        $$
        \begin{{aligned}}
        |A| &=a\left|\frac{{1-e^{{i N \varphi}}}}{{1-e^{{i \varphi}}}}\right|=a\left[\frac{{1-e^{{i N \varphi}}}}{{1-e^{{i \varphi}}}} \times \frac{{1-e^{{-i N \varphi}}}}{{1-e^{{-i \varphi}}}}\right]^{{1 / 2}} \\
        &=a\left[\frac{{2-2 \cos N \varphi}}{{2-2 \cos \varphi}}\right]^{{1 / 2}}=a \frac{{\sin \frac{{N \varphi}}{{2}}}}{{\sin \frac{{\varphi}}{{2}}}}
        \end{{aligned}}
        $$
        
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
   
