'''
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 InterferenceManager(BaseManager):
    '''
    InterferenceManager
    Example:
        ke = InterferenceManager()
        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(InterferenceManager, cls).__new__(cls, *args, **kwargs)
        for base_class in InterferenceManager.__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_64',
            '_problem_5_65',
            '_problem_5_66',
            '_problem_5_67',
            '_problem_5_68',            
            '_problem_5_69',            
            '_problem_5_70',
            '_problem_5_71',
            ])       
        pass
            
    def _problem_5_64(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_65(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_66(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
    
    def _problem_5_67(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.67 A system illustrated in Fig. 5.12 consists of two coherent
        point sources 1 and 2 located in a certain plane so that their dipole
        moments are oriented at right angles to that plane. The sources are
        separated by a distance d, the radiation wavelength
        is equal to $\lambda$. Taking into account that the oscillations of source 2 lag in phase behind the oscillations
        of source 1 by $\varphi (\varphi < \pi)$, find:
        (a) the angles $\theta$ at which the radiation intensity
        is maximum;
        (b) the conditions under which the radiation intensity in the direction $\theta = \pi$ is maximum and in the 2
        opposite direction, minimum
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.67 (a) With dipole moment $\perp^{{r}}$ to plane there is no variation with $\theta$ of individual radiation amplitude. Then the intensity variation is due to interference only.

        In the direction given by angle 9 the phase difference is
        $\frac{{2 \pi}}{{\lambda}}(d \cos \theta)+\varphi=2 k \pi \quad$ for maxima
        Thus
        $$
        \begin{{aligned}}
        d \cos \theta &=\left(k-\frac{{\varphi}}{{2 \pi}}\right) \lambda \\
        k &=0, \pm 1, \pm 2, \ldots
        \end{{aligned}}
        $$
        We have added $\varphi$ to $\frac{{2 \pi}}{{\lambda}} d \cos \theta$ because the extra path that the wave from 2 has to travel in going to $P$ (as compared to 1$)$ makes it lag more than it already is (due to $\varphi$ ).
        
        (b) Maximum for $\theta=\pi$ gives $-d=\left(k-\frac{{\varphi}}{{2 \pi}}\right) \lambda$
        Minimum for $\theta=0$ gives $d=\left(k^{{\prime}}-\frac{{\varphi}}{{2 \pi}}+\frac{{1}}{{2}}\right) \lambda$
        Adding we get $\quad\left(k+k^{{\prime}}-\frac{{\varphi}}{{\pi}}+\frac{{1}}{{2}}\right) \lambda=0$
        This can be true only if $\quad k^{{\prime}}=-k, \varphi=\frac{{\pi}}{{2}}$
        since $0<\varphi<\pi$
        Then
        Here
        $$
        \begin{{gathered}}
        -d=\left(k-\frac{{1}}{{4}}\right) \lambda \\
        k=0,-1,-2,-3, \ldots
        \end{{gathered}}
        $$
        (Otherwise R.H.S. will become +ve ).
        Putting $k=-\bar{{k}}, \bar{{k}}=0,+1,+2,+3, \ldots$
        $$
        d=\left(k+\frac{{1}}{{4}}\right) \lambda
        $$

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

        problem_s = fr"""
        5.68. A stationary radiating system consists of a
        linear chain of parallel oscillators separated by a distance d, with the oscillation, phase varying linearly along the
        chain. Find the time dependence of the phase difference $\Delta \varphi$ between
        the neighbouring oscillators at which the principal radiation maximum of the system will be "scanning" the surroundings with the
        constant angular velocity $\varphi$
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.68 If $\Delta \varphi$ is the phase difference between neighbouring radiators then for a maximum in the direction $\theta$ we must have
        $$
        \frac{{2 \pi}}{{\lambda}} d \cos \theta+\Delta \varphi=2 \pi k
        $$
        For scanning $\theta=\omega t+\beta$
        Thus
        $$
        \frac{{d}}{{\lambda}} \cos (\omega t+\beta)+\frac{{\Delta \varphi}}{{2 \pi}}=k
        $$
        or
        $$
        \Delta \varphi=2 \pi\left[k-\frac{{d}}{{\lambda}} \cos (\omega t+\beta)\right]
        $$
        To get the answer of the book, put $\beta = \alpha-\pi / 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_69(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        5.69. In Lloyd's mirror experiment (Fig. 5.13) a light wave emitted
        directly by the source S (narrow slit) interferes with the wave 
        reflected from a mirror M. As a result, an interference fringe pattern is 
        
        formed on the screen Sc. The source and the mirror are separated by
        a distance 1 = 100 cm. At a certain position of the source the fringe
        width on the screen was equal to $\Delta x$= 0.25 mm, and after the source
        was moved away from the mirror plane by $\Delta h$ = 0.60 mm, the
        fringe width decreased $\eta$ = 1.5 times. Find the wavelength of light.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        5.69 From the general formula
        we find that
        $$
        \begin{{gathered}}
        \Delta x=\frac{{l \lambda}}{{d}} \\
        \frac{{\Delta x}}{{\eta}}=\frac{{l \lambda}}{{d+2 \Delta h}}
        \end{{gathered}}
        $$
        since $d$ increases tod $+2 \Delta h$ when the source is moved away from the mirror plane by $\Delta h$. Thus
        $$
        \eta d=d+2 \Delta h \quad \text {{ or }} \quad d=2 \Delta h /(\eta-1)
        $$
        Finally
        $$
        \lambda=\frac{{2 \Delta h \Delta x}}{{(\eta-1) l}}=0.6 \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_70(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_71(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
    