(* ::Package:: *)

(* Mathematica initialization file 
Marko Tervi\[ODoubleDot] *)

(* MANIPULATION *)
Simp[x_]:=TimeConstrained[FullSimplify[x,assums],60]
Simp[x_,y_]:=TimeConstrained[FullSimplify[x,Join[{y},assums]],60]
TSimp[x_,y_:{}]:=TraditionalForm[Simp[x,y]]

ReIm[x_]:={Re[x],Im[x]}
PolarReIm[r_,\[Theta]_]:=ReIm[r (Cos[\[Theta]]+I Sin[\[Theta]])]

(* GRAPHING *)
BDashed={Black,Dashed};
BDotted={Black,Dotted};
Dashed6=Dashing[{0.01,0.01}];
Dotted6=Dashing[{0.003,0.01}];
ShortDotted = Dashing[{0.003, 0.004}];
LongDashed = Dashing[{0.02, 0.02}];
ShortDashed = Dashing[{0.005, 0.005}];
UsualText={FontFamily->"Times",FontSize->16};
TimesText[size_]:={FontFamily->"Times",FontSize->size}

MakeLegend[namelist_,stylelist_,toright_:0.25,fontN_:22]:=Module[{n=Length[namelist],ylist,legend},
ylist=Range[1,n];
legend=Table[Text[namelist[[i]],{1+toright,i}],{i,1,n}];
Plot[{ylist},{x,0,1},
Axes->None,
PlotStyle->stylelist,
PlotRange->{{0,2},{0,n+1}},
BaseStyle->{FontSize->fontN},
Epilog->legend]
]

(* not needed from version 5.1 on
Red=RGBColor[1,0,0];
Green=RGBColor[0,1,0];
Blue=RGBColor[0,0,1];
Black=RGBColor[0,0,0]; *)


(* LIST AND MATRIX OPERATIONS *)
Ones[n_]:=Table[1,{n}]
Zeros[n_]:=Table[0,{n}]
Index[n1_,n0_:1]:=Range[n0,n1]

ArgMax[xlist_]:=Ordering[xlist,-1][[1]]  
(* picks the argmax with largest index *)
ArgMaxFirst[ylist_]:=Length[ylist]+1-ArgMax[Reverse[ylist]]
MinList[list_]:=Table[Min[list[[i]]],{i,1,Length[list]}]
MaxList[list_]:=-MinList[-list]

DifList[xlist_]:=Take[xlist,1-Length[xlist]]-Take[xlist,Length[xlist]-1]
SumList[xlist_]:=Table[Sum[xlist[[i]],{i,1,j}],{j,1,Length[xlist]}]
ProductList[xlist_]:=Table[Product[xlist[[i]],{i,1,j}],{j,1,Length[xlist]}]
DerList[xlist_]:=Table[{xlist[[i,1]],DifList[xlist][[i,2]]/DifList[xlist][[i,1]]},{i,1,
      Length[xlist]-1}]

MatrixProductList[list_]:=Module[{temp=list[[1]],n=Length[list],i=1},While[i++<n,temp=temp.list[[i]]];temp]

TrNorm[mat_]:=Sqrt[Tr[ConjugateTranspose[mat].mat]]

(*Sorts the rows of mat by the elements of the n:th column.
Negative n results in the reverse sort *)
SortElement[mat_,n_]:=Sort[mat,(Sign[n]*#1 [[Abs[n]]]>Sign[n]*#2 [[Abs[n]]])&]

(*Returns mat with diagonal elements replaced by zeros*)
NoDiag[mat_]:=If[Length[mat]==Length[mat\[Transpose]],mat-DiagonalMatrix[Diagonal[mat]],Table[If[i!=j,mat[[i,j]],0],{i,1,Length[mat]},{j,1,Length[mat\[Transpose]]}]]

(* MSort sorts rows and columns of mat according to values of sortrow and sortcol respectively.
In the absence of sortcol it assumes that the last observations of sortrow correspond to the possible missing columns in mat  *)
MSort[mat_,sortrow_,sortcol2_:{}]:=Module[{temp,sortcol},
sortcol=If[sortcol2=={},sortrow,sortcol2];
temp=Join[{sortrow},mat];
temp=Drop[SortElement[temp\[Transpose],1]\[Transpose],1];
temp=Join[{sortcol},temp\[Transpose]];
Drop[SortElement[temp\[Transpose],1]\[Transpose],1]\[Transpose]
]

(* PROGRAMMING *)

(* iterate f[{x1_,...,xt_}]  n times starting with initial condition xlist *)
Iterate[f_,xlist_,n_]:=Module[{i=n,t=Length[xlist],xtemp=xlist},
While[i-->0,xtemp=Join[xtemp,{f[Take[xtemp,-t]]}]];
xtemp]
    
DiscreteMax[funk_,xmin_,xmax_,xsteps_]:=Module[{tabx,tfunk},
tabx=Table[{xi,funk[xi]},{xi,xmin,xmax,(xmax-xmin)/xsteps}];
tfunk=Interpolation[tabx];
GlobalTab=tabx;
NMaximize[{tfunk[x],xmin<=x<= xmax},{x},MaxIterations->1000,PrecisionGoal->10,AccuracyGoal->Infinity]
]

(* DATA ANALYSIS *)

DataSummary[xlist_]:={Length[xlist],Mean[xlist],StandardDeviation[xlist],
    Min[xlist],Median[xlist],Max[xlist]}
    
DataSummary2[xlist_]:=
  TableForm[{{"Obs.","Mean","Std.Dev","Min","Med","Max"},DataSummary[xlist]}]

StatStar[p_,levels_:{0.01,0.05,0.1}]:=Piecewise[{{"***",p<= levels[[1]]},{"**",p<=levels[[2]]},{"*",p<= levels[[3]]}},""]
 
(* Calculates Pinski-Narin ifluence weights for matrix mat, assuming irreducibility *) 
PinskiNarin[mat_,n_:256]:=100*(Ones[Length[mat]]/Length[mat]).MatrixPower[N[mat/Total[mat\[Transpose]]],n]

Herfindahl[list_,digits_:8]:=Round[(10^digits)*Total[(list/Total[list])^2]]/(10.^digits)


(* Create a random permutation of the set {1,2,...,n} *)
RandomPermutation[n_Integer]:=Module[{temp=Range[1,n],result,ti},
result={ti=RandomChoice[temp]};
temp=Complement[temp,{ti}];
While[temp!={},
ti=RandomChoice[temp];
result=Join[result,{ti}];
temp=Complement[temp,{ti}]];
result]

(* MISCELLANEOUS *)

ShortDate[] := Module[{mins = Date[][[5]]},
    Print[Date[][[4]], ":", 
      If[Length[mins] == 1, StringJoin["0", ToString[mins]], mins]]
    ]
    
LongDate[]:=
  Print[Date[][[4]],":",Date[][[5]],", ",Date[][[3]],".",Date[][[2]],", ",
    Date[][[1]]]

Beep6[x_:1]:=Play[Sin[2^t],{t,11+x,14+x}]
 
