(*ESEMPI DI CONVOLUZIONE MODULAZIONE E NON LINEARITA' ISTANTANEA - GABRIEL HINE - 30/11/18*)
Clear["Global`*"]
(*Funzione per graficare una funzione contenente delta di dirac NON TOCCARE*)
ArrowsDeltaFunction[eqn_,x_]:=Module[{xsubs,listDeltas,coefDeltas,locationDeltas},xsubs=(x/.Cases[eqn,DiracDelta[a__]:>Solve[a==0,x],Infinity]);locationDeltas=Flatten[xsubs];Arrow[Table[{{locationDeltas[[i]],0},{locationDeltas[[i]],( N[Integrate[eqn,{x,locationDeltas[[i]]-10^-18,locationDeltas[[i]]+10^-18}]])/. x->locationDeltas[[i]]}},{i,1,Length[locationDeltas]}]]]

(* definizioni NON TOCCARE*)
δ[x_] := DiracDelta[x];
Rect[x_,W_]:= UnitBox[x/W];
Tri  [x_,W_]:= UnitTriangle[x/W];

(*Segnale di ingresso *)
x= (Cos[2 π t]+2 Sin[8 π t]+I);
(*Filtro*)
H= Rect[f,4]+Tri[f-1,1]+Tri[f+1,1];

(*Trasormata di Fourier*)
(*Convenzione adottata nel corso di Teoria di Segnali ->{0, -2 Pi}*)
X=FourierTransform[x,t,f,FourierParameters->{0, -2 Pi}];

(*Plot*)
ReX=ComplexExpand[Re[X]];
ImX=ComplexExpand[Im[X]];
Plot[{ReX,ImX},{f,-5,5},PlotStyle->{Red,Blue},PlotRange->3,AxesLabel->{"f","X(f)"},Filling->Axis,PlotLegends->LineLegend[{Red,Blue},{"Real part","Imag part"}],Epilog->{Thick,Red,ArrowsDeltaFunction[Evaluate[ReX],f],Blue,ArrowsDeltaFunction[Evaluate[ImX],f]}]

ReH=ComplexExpand[Re[H]];
ImH=ComplexExpand[Im[H]];
Plot[{ReH,ImH},{f,-5,5},PlotStyle->{Red,Blue},PlotRange->3,AxesLabel->{"f","H(f)"},Filling->Axis,PlotLegends->LineLegend[{Red,Blue},{"Real part","Imag part"}]]

(*Filtraggio*)
Y = X *  H 
(*Plot*)
ReY=ComplexExpand[Re[Y]];
ImY=ComplexExpand[Im[Y]];
Plot[{ReY,ImY},{f,-5,5},PlotStyle->{Red,Blue},PlotRange->3,AxesLabel->{"f","Y(f)"},Filling -> Axis, PlotLegends->LineLegend[{Red,Blue},{"Real part","Imag part"}],
Epilog->{Thick,Red,ArrowsDeltaFunction[ReY,f],Blue,ArrowsDeltaFunction[ImY,f]}]

(* Modulazione - Convoluzione in frequenza *)
Z = Evaluate[Convolve[Y,H,f,ff]]/.ff-> f
(*Plot*)
ReZ=ComplexExpand[Re[Z]];
ImZ=ComplexExpand[Im[Z]];
Plot[{Evaluate[ReZ],Evaluate[ImZ]},{f,-5,5},PlotStyle->{Red,Blue},PlotRange->5,AxesLabel->{"f","Z(f)"},PlotLegends->LineLegend[{Red,Blue},{"Real part","Imag part"}],Filling->Axis]

(*Anti-trasformata di Fourier*)
z = InverseFourierTransform[Z,f,t,FourierParameters->{0, -2 Pi}]
(*Plot*)
Rez=ComplexExpand[Re[z]];
Imz=ComplexExpand[Im[z]];
Plot[{Evaluate[Rez],Evaluate[Imz]},{t,-5,5},PlotStyle->{Red,Blue},PlotRange->{-5,12},AxesLabel->{"t","z(t)"},PlotLegends->LineLegend[{Red,Blue},{"Real part","Imag part"}],Filling->Axis]

(*Non Linearità*)
nl= (UnitStep[xx] -UnitStep[-xx] )
(*Plot*)
Plot[{nl},{xx,-10,10},PlotRange->Automatic,AxesLabel->{"x","nl(x)"},Filling->Axis]

(*Applicazione non linearità (applicata solo alla parte reale) *)
w = nl/.{xx-> Rez};
(*Plot*)
Plot[Evaluate[w],{t,-5,5},PlotStyle->Red,PlotRange->{-5,12},AxesLabel->{"t","w(t)"},Filling->Axis]