Quiet@Remove["Global`*"];
$HistoryLength=2;
SetDirectory[NotebookDirectory[]];
proms=ToString/@{Qout,T2,Pmechout,Qin,T4};

m1=1.5;
T1=400;
c1=1000;
c2=c1;
Tout=35.;
Δout=10.;
ClearAll[vydej1];
vydej1[{kS_,m2_}]:=Module[{rceSpolecne,T2,T3,T4,Pmechout,Qout,Δ1,Δ2,ηTD=0.6,ηCarnot,Qin,rceLin,rceLog,dospoc,proms,sol},
Δ1=T1-T4;
Δ2=T2-T3;
T3=Tout+Δout;
ηCarnot=1-((Tout+273)/(T4+273.));
rceSpolecne={Qin==m1*c1*(T1-T2),
Qin==m2*c2*(T4-T3),
Qin==Pmechout+Qout,
Pmechout==ηCarnot*ηTD*Qin

};
rceLin=Union[rceSpolecne,{Qin==kS*((Δ1+Δ2)/2)}];
rceLog=Union[rceSpolecne,{Qin==kS*((Δ1-Δ2)/(Log[((Δ1)/(Δ2))]))}];
dospoc=Solve[rceLin][[1]];
proms=First/@dospoc;
sol=Chop[Quiet@FindRoot[rceLog,Thread[{proms,(proms/.dospoc)}]]];
(*{Qout,T2,Pmechout,Qin,T4}*)
proms/.sol
];

ClearAll[vydej2];
vydej2[{{kS_,m2_},{Aa_,Ab_},{cPmech_,cQout_}}]:=Module[{Qout,T2,Pmechout,Qin,T4,CF},
{Qout,T2,Pmechout,Qin,T4}=vydej1[{kS,m2}];
CF=Pmechout*cPmech+Qout*cQout-(Aa+Ab*kS)
];

ClearAll[vydej3];
Aa=50;
Ab=2;
cPmech=1.5;
cQout=0.1;
vydej3[{kS_?NumberQ,m2_?NumberQ}]:=vydej2[{{kS,m2},{Aa,Ab},{cPmech,cQout}}];
vys=Quiet@FindMaximum[vydej3[{kS,m2}],{kS,1300},{m2,1}];
myR:=0.01Round[100#]&;
vysledek={Qout,T2,Pmechout,Qin,T4}=vydej1[{kS,m2}/.vys[[2]]];
(ToString[ #]<>"="&/@proms)[[#]]<>(ToString/@(myR/@vysledek))[[#]]&/@Range[Length[proms]];
%*{"W","°C","W","W","°C"}
vys

vydej3[{1000,0.1}]

<<geneticoperators.m
<<genetic-new.m

VektorPromennych={{kS,1000,20000,24},{m2,0.1,2,24}};

Fitness[{kS_,m2_}]:=-Re[vydej3[{kS,m2}]];

pocetJedincu=80;
pravdepodobnostMutace=0.01;
pravdepodobnostKrizeni=0.85;
pouzitGrayCode=True;
pouzitRuletu=True;
debugMode=False;
Populace=Inicializace[pocetJedincu];

Quiet@OptimalizacniSmycka[40]

(* lze pouzit funkce NMinimize ktera ma stejnou metodu*)

NMinimize[{-Re[vydej3[{kS,m2}]],2>m2>0.1,20000>kS>1000},{kS,m2},Method->"DifferentialEvolution"]

(*numericka derivace:*)

ΔkS=1;
Δm2=0.001;
derPodlekS[{kS_,m2_}]:=((Fitness[{kS+ΔkS,m2}]-Fitness[{kS-ΔkS,m2}])/(2*ΔkS));
derPodlem2[{kS_,m2_}]:=((Fitness[{kS,m2+Δm2}]-Fitness[{kS,m2-Δm2}])/(2*Δm2));
grad[{kS_,m2_}]:={derPodlekS[{kS,m2}],derPodlem2[{kS,m2}]};
grad[{5000.,5}]