This repository was archived by the owner on Feb 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimization.cc
More file actions
2797 lines (2726 loc) · 105 KB
/
optimization.cc
File metadata and controls
2797 lines (2726 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* optimization.cc
*
* Copyright 2017 Luka Marohnić
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* __________________________________________________________________________
* |Example of using 'extrema', 'minimize' and 'maximize' functions to solve|
* |the set of exercises found in: |
* |https://math.feld.cvut.cz/habala/teaching/veci-ma2/ema2r3.pdf |
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 1) Input:
* extrema(2x^3+9x*y^2+15x^2+27y^2,[x,y])
* Result: we get local minimum at origin, local maximum at (-5,0)
* and (-3,2),(-3,-2) as saddle points.
*
* 2) Input:
* extrema(x^3-2x^2+y^2+z^2-2x*y+x*z-y*z+3z,[x,y,z])
* Result: the given function has local minimum at (2,1,-2).
*
* 3) Input:
* minimize(x^2+2y^2,x^2-2x+2y^2+4y=0,[x,y]);
* maximize(x^2+2y^2,x^2-2x+2y^2+4y=0,[x,y])
* Result: the minimal value of x^2+2y^2 is 0 and the maximal is 12.
*
* 4) We need to minimize f(x,y,z)=x^2+(y+3)^2+(z-2)^2 for points (x,y,z)
* lying in plane x+y-z=1. Since the feasible area is not bounded, we're
* using the function 'extrema' because obviously the function has single
* local minimum.
* Input:
* extrema(x^2+(y+3)^2+(z-2)^2,x+y-z=1,[x,y,z])
* Result: the point closest to P in x+y-z=1 is (2,-1,0), and the distance
* is equal to sqrt(f(2,-1,0))=2*sqrt(3).
*
* 5) We're using the same method as in exercise 4.
* Input:
* extrema((x-1)^2+(y-2)^2+(z+1)^2,[x+y+z=1,2x-y+z=3],[x,y,z])
* Result: the closest point is (2,0,-1) and the corresponding distance
* equals to sqrt(5).
*
* 6) First we need to determine the feasible area. Plot its bounds with:
* implicitplot(x^2+(y+1)^2-4,x,y);line(y=-1);line(y=x+1)
* Now we see that the feasible area is given by set of inequalities:
* cond:=[x^2+(y+1)^2<=4,y>=-1,y<=x+1]
* Draw this area with:
* plotinequation(cond,[x,y],xstep=0.05,ystep=0.05)
* Now calculate global minimum and maximum of f(x,y)=x^2+4y^2 on that area:
* f(x,y):=x^2+4y^2;
* minimize(f(x,y),cond,[x,y]);maximize(f(x,y),cond,[x,y])
* Result: the minimum is 0 and the maximum is 8.
*
* 7) Input:
* minimize(x^2+y^2-6x+6y,x^2+y^2<=4,[x,y]);
* maximize(x^2+y^2-6x+6y,x^2+y^2<=4,[x,y])
* Result: the minimum is 4-12*sqrt(2) and the maximum is 4+12*sqrt(2).
*
* 8) Input:
* extrema(y,y^2+2x*y=2x-4x^2,[x,y])
* Result: we obtain (1/2,-1) as local minimum and (1/6,1/3) as local
* maximum of f(x,y)=y. Therefore, the maximal value is y(1/2)=-1
* and the maximal value is y(1/6)=1/3.
*
* The above set of exercises could be turned into an example Xcas worksheet.
*/
#include "giacPCH.h"
#include "giac.h"
#include "optimization.h"
#include "signalprocessing.h"
#include <sstream>
#include <bitset>
using namespace std;
#ifndef NO_NAMESPACE_GIAC
namespace giac {
#endif // ndef NO_NAMESPACE_GIAC
#define GOLDEN_RATIO 1.61803398875
typedef unsigned long ulong;
gen make_idnt(const char* name,int index=-1,bool intern=true) {
stringstream ss;
if (intern)
ss << " ";
ss << string(name);
if (index>=0)
ss << index;
return identificateur(ss.str().c_str());
}
/*
* Return true iff the expression 'e' is constant with respect to
* variables in 'vars'.
*/
bool is_constant_wrt_vars(const gen &e,vecteur &vars,GIAC_CONTEXT) {
for (const_iterateur it=vars.begin();it!=vars.end();++it) {
if (!is_constant_wrt(e,*it,contextptr))
return false;
}
return true;
}
/*
* Return true iff the expression 'e' is rational with respect to
* variables in 'vars'.
*/
bool is_rational_wrt_vars(const gen &e,const vecteur &vars,GIAC_CONTEXT) {
for (const_iterateur it=vars.begin();it!=vars.end();++it) {
vecteur l(rlvarx(e,*it));
if (l.size()>1)
return false;
}
return true;
}
/*
* Solves a system of equations.
* This function is based on _solve but handles cases where a variable
* is found inside trigonometric, hyperbolic or exponential functions.
*/
vecteur solve2(const vecteur &e_orig,const vecteur &vars_orig,GIAC_CONTEXT) {
int m=e_orig.size(),n=vars_orig.size(),i=0;
for (;i<m;++i) {
if (!is_rational_wrt_vars(e_orig[i],vars_orig,contextptr))
break;
}
if (n==1 || i==m)
return *_solve(makesequence(e_orig,vars_orig),contextptr)._VECTptr;
vecteur e(*halftan(_texpand(hyp2exp(e_orig,contextptr),contextptr),contextptr)._VECTptr);
vecteur lv(*exact(lvar(_evalf(lvar(e),contextptr)),contextptr)._VECTptr);
vecteur deps(n),depvars(n,gen(0));
vecteur vars(vars_orig);
const_iterateur it=lv.begin();
for (;it!=lv.end();++it) {
i=0;
for (;i<n;++i) {
if (is_undef(vars[i]))
continue;
if (*it==(deps[i]=vars[i]) ||
*it==(deps[i]=exp(vars[i],contextptr)) ||
is_zero(_simplify(*it-(deps[i]=tan(vars[i]/gen(2),contextptr)),contextptr))) {
vars[i]=undef;
depvars[i]=make_idnt("depvar",i);
break;
}
}
if (i==n)
break;
}
if (it!=lv.end() || find(depvars.begin(),depvars.end(),gen(0))!=depvars.end())
return *_solve(makesequence(e_orig,vars_orig),contextptr)._VECTptr;
vecteur e_subs(subst(e,deps,depvars,false,contextptr));
vecteur sol(*_solve(makesequence(e_subs,depvars),contextptr)._VECTptr);
vecteur ret;
for (const_iterateur it=sol.begin();it!=sol.end();++it) {
vecteur r(n);
i=0;
for (;i<n;++i) {
gen c(it->_VECTptr->at(i));
if (deps[i].type==_IDNT)
r[i]=c;
else if (deps[i].is_symb_of_sommet(at_exp) && is_strictly_positive(c,contextptr))
r[i]=_ratnormal(ln(c,contextptr),contextptr);
else if (deps[i].is_symb_of_sommet(at_tan))
r[i]=_ratnormal(2*atan(c,contextptr),contextptr);
else
break;
}
if (i==n)
ret.push_back(r);
}
return ret;
}
/*
* Traverse the tree of symbolic expression 'e' and collect all points of
* transition in piecewise subexpressions, no matter of the inequality sign.
* Nested piecewise expressions are not supported.
*/
void find_spikes(const gen &e,vecteur &cv,GIAC_CONTEXT) {
if (e.type!=_SYMB)
return;
gen &f=e._SYMBptr->feuille;
if (f.type==_VECT) {
for (const_iterateur it=f._VECTptr->begin();it!=f._VECTptr->end();++it) {
if (e.is_symb_of_sommet(at_piecewise) || e.is_symb_of_sommet(at_when)) {
if (it->is_symb_of_sommet(at_equal) ||
it->is_symb_of_sommet(at_different) ||
it->is_symb_of_sommet(at_inferieur_egal) ||
it->is_symb_of_sommet(at_superieur_egal) ||
it->is_symb_of_sommet(at_inferieur_strict) ||
it->is_symb_of_sommet(at_superieur_strict)) {
vecteur &w=*it->_SYMBptr->feuille._VECTptr;
cv.push_back(w[0].type==_IDNT?w[1]:w[0]);
}
}
else find_spikes(*it,cv,contextptr);
}
}
else find_spikes(f,cv,contextptr);
}
bool next_binary_perm(vector<bool> &perm,int to_end=0) {
if (to_end==int(perm.size()))
return false;
int end=int(perm.size())-1-to_end;
perm[end]=!perm[end];
return perm[end]?true:next_binary_perm(perm,to_end+1);
}
vecteur make_temp_vars(const vecteur &vars,const vecteur &ineq,GIAC_CONTEXT) {
gen t,xmin,xmax;
vecteur tmpvars;
int index=0;
for (const_iterateur it=vars.begin();it!=vars.end();++it) {
xmin=undef;
xmax=undef;
for (const_iterateur jt=ineq.begin();jt!=ineq.end();++jt) {
if (jt->is_symb_of_sommet(at_superieur_egal) &&
jt->_SYMBptr->feuille._VECTptr->front()==*it &&
(t=jt->_SYMBptr->feuille._VECTptr->back()).evalf(1,contextptr).type==_DOUBLE_)
xmin=t;
if (jt->is_symb_of_sommet(at_inferieur_egal) &&
jt->_SYMBptr->feuille._VECTptr->front()==*it &&
(t=jt->_SYMBptr->feuille._VECTptr->back()).evalf(1,contextptr).type==_DOUBLE_)
xmax=t;
}
gen v=make_idnt("var",index++);
if (!is_undef(xmax) && !is_undef(xmin))
assume_t_in_ab(v,xmin,xmax,false,false,contextptr);
else if (!is_undef(xmin))
giac_assume(symb_superieur_egal(v,xmin),contextptr);
else if (!is_undef(xmax))
giac_assume(symb_inferieur_egal(v,xmax),contextptr);
tmpvars.push_back(v);
}
return tmpvars;
}
/*
* Determine critical points of function f under constraints g<=0 and h=0 using
* Karush-Kuhn-Tucker conditions.
*/
vecteur solve_kkt(gen &f,vecteur &g,vecteur &h,vecteur &vars_orig,GIAC_CONTEXT) {
int n=vars_orig.size(),m=g.size(),l=h.size();
vecteur vars(vars_orig),gr_f(*_grad(makesequence(f,vars_orig),contextptr)._VECTptr),mug;
matrice gr_g,gr_h;
vars.resize(n+m+l);
for (int i=0;i<m;++i) {
vars[n+i]=make_idnt("mu",n+i);
giac_assume(symb_superieur_strict(vars[n+i],gen(0)),contextptr);
gr_g.push_back(*_grad(makesequence(g[i],vars_orig),contextptr)._VECTptr);
}
for (int i=0;i<l;++i) {
vars[n+m+i]=make_idnt("lambda",n+m+i);
gr_h.push_back(*_grad(makesequence(h[i],vars_orig),contextptr)._VECTptr);
}
vecteur eqv;
for (int i=0;i<n;++i) {
gen eq(gr_f[i]);
for (int j=0;j<m;++j) {
eq+=vars[n+j]*gr_g[j][i];
}
for (int j=0;j<l;++j) {
eq+=vars[n+m+j]*gr_h[j][i];
}
eqv.push_back(eq);
}
eqv=mergevecteur(eqv,h);
vector<bool> is_mu_zero(m,false);
matrice cv;
do {
vecteur e(eqv);
vecteur v(vars);
for (int i=m-1;i>=0;--i) {
if (is_mu_zero[i]) {
e=subst(e,v[n+i],gen(0),false,contextptr);
v.erase(v.begin()+n+i);
}
else
e.push_back(g[i]);
}
cv=mergevecteur(cv,solve2(e,v,contextptr));
} while(next_binary_perm(is_mu_zero));
vars.resize(n);
for (int i=cv.size()-1;i>=0;--i) {
cv[i]._VECTptr->resize(n);
for (int j=0;j<m;++j) {
if (is_strictly_positive(subst(g[j],vars,cv[i],false,contextptr),contextptr)) {
cv.erase(cv.begin()+i);
break;
}
}
}
return cv;
}
/*
* Determine critical points of an univariate function f(x). Points where it is
* not differentiable are considered critical as well as zeros of the first
* derivative. Also, bounds of the range of x are critical points.
*/
matrice critical_univariate(const gen &f,const gen &x,GIAC_CONTEXT) {
gen df(_derive(makesequence(f,x),contextptr));
matrice cv(*_zeros(makesequence(df,x),contextptr)._VECTptr);
gen den(_denom(df,contextptr));
if (!is_constant_wrt(den,x,contextptr)) {
cv=mergevecteur(cv,*_zeros(makesequence(den,x),contextptr)._VECTptr);
}
find_spikes(f,cv,contextptr); // assuming that f is not differentiable on transitions
for (int i=cv.size()-1;i>=0;--i) {
if (cv[i].is_symb_of_sommet(at_and))
cv.erase(cv.begin()+i);
else
cv[i]=vecteur(1,cv[i]);
}
return cv;
}
/*
* Compute global minimum mn and global maximum mx of function f(vars) under
* conditions g<=0 and h=0. The list of points where global minimum is achieved
* is returned.
*/
vecteur global_extrema(gen &f,vecteur &g,vecteur &h,vecteur &vars,gen &mn,gen &mx,GIAC_CONTEXT) {
int n=vars.size();
matrice cv;
vecteur tmpvars=make_temp_vars(vars,g,contextptr);
gen ff=subst(f,vars,tmpvars,false,contextptr);
if (n==1) {
cv=critical_univariate(ff,tmpvars[0],contextptr);
for (const_iterateur it=g.begin();it!=g.end();++it) {
cv.push_back(makevecteur(it->_SYMBptr->feuille._VECTptr->back()));
}
} else {
vecteur gg=subst(g,vars,tmpvars,false,contextptr);
vecteur hh=subst(h,vars,tmpvars,false,contextptr);
cv=solve_kkt(ff,gg,hh,tmpvars,contextptr);
}
if (cv.empty())
return vecteur(0);
bool min_set=false,max_set=false;
matrice min_locations;
for (const_iterateur it=cv.begin();it!=cv.end();++it) {
gen val=_eval(subst(f,vars,*it,false,contextptr),contextptr);
if (min_set && is_exactly_zero(_ratnormal(val-mn,contextptr))) {
if (find(min_locations.begin(),min_locations.end(),*it)==min_locations.end())
min_locations.push_back(*it);
}
else if (!min_set || is_strictly_greater(mn,val,contextptr)) {
mn=val;
min_set=true;
min_locations=vecteur(1,*it);
}
if (!max_set || is_strictly_greater(val,mx,contextptr)) {
mx=val;
max_set=true;
}
}
if (n==1) {
for (int i=0;i<int(min_locations.size());++i) {
min_locations[i]=min_locations[i][0];
}
}
return min_locations;
}
int parse_varlist(const gen &g,vecteur &vars,vecteur &ineq,vecteur &initial,GIAC_CONTEXT) {
vecteur varlist(g.type==_VECT ? *g._VECTptr : vecteur(1,g));
int n=0;
for (const_iterateur it=varlist.begin();it!=varlist.end();++it) {
if (it->is_symb_of_sommet(at_equal)) {
vecteur &ops=*it->_SYMBptr->feuille._VECTptr;
gen &v=ops.front(), &rh=ops.back();
if (v.type!=_IDNT)
return 0;
vars.push_back(v);
if (rh.is_symb_of_sommet(at_interval)) {
vecteur &range=*rh._SYMBptr->feuille._VECTptr;
if (!is_inf(range.front()))
ineq.push_back(symbolic(at_superieur_egal,makevecteur(v,range.front())));
if (!is_inf(range.back()))
ineq.push_back(symbolic(at_inferieur_egal,makevecteur(v,range.back())));
}
else
initial.push_back(rh);
}
else if (it->type!=_IDNT)
return 0;
else
vars.push_back(*it);
++n;
}
return n;
}
/*
* Function 'minimize' minimizes a multivariate continuous function on a
* closed and bounded region using the method of Lagrange multipliers. The
* feasible region is specified by bounding variables or by adding one or
* more (in)equality constraints.
*
* Usage
* ^^^^^
* minimize(obj,[constr],vars,[opt])
*
* Parameters
* ^^^^^^^^^^
* - obj : objective function to minimize
* - constr (optional) : single equality or inequality constraint or
* a list of constraints, if constraint is given as
* expression it is assumed that it is equal to zero
* - vars : single variable or a list of problem variables, where
* optional bounds of a variable may be set by appending '=a..b'
* - location (optional) : the option keyword 'locus' or 'coordinates' or 'point'
*
* Objective function must be continuous in all points of the feasible region,
* which is assumed to be closed and bounded. If one of these condinitions is
* not met, the final result may be incorrect.
*
* When the fourth argument is specified, point(s) at which the objective
* function attains its minimum value are also returned as a list of vector(s).
* The keywords 'locus', 'coordinates' and 'point' all have the same effect.
* For univariate problems, a vector of numbers (x values) is returned, while
* for multivariate problems it is a vector of vectors, i.e. a matrix.
*
* The function attempts to obtain the critical points in exact form, if the
* parameters of the problem are all exact. It works best for problems in which
* the lagrangian function gradient consists of rational expressions. Points at
* which the function is not differentiable are also considered critical. This
* function also handles univariate piecewise functions.
*
* If no critical points were obtained, the return value is undefined.
*
* Examples
* ^^^^^^^^
* minimize(sin(x),[x=0..4])
* >> sin(4)
* minimize(asin(x),x=-1..1)
* >> -pi/2
* minimize(x^2+cos(x),x=0..3)
* >> 1
* minimize(x^4-x^2,x=-3..3,locus)
* >> -1/4,[-sqrt(2)/2]
* minimize(abs(x),x=-1..1)
* >> 0
* minimize(x-abs(x),x=-1..1)
* >> -2
* minimize(abs(exp(-x^2)-1/2),x=-4..4)
* >> 0
* minimize(piecewise(x<=-2,x+6,x<=1,x^2,3/2-x/2),x=-3..2)
* >> 0
* minimize(x^2-3x+y^2+3y+3,[x=2..4,y=-4..-2],point)
* >> -1,[[2,-2]]
* minimize(2x^2+y^2,x+y=1,[x,y])
* >> 2/3
* minimize(2x^2-y^2+6y,x^2+y^2<=16,[x,y])
* >> -40
* minimize(x*y+9-x^2-y^2,x^2+y^2<=9,[x,y])
* >> -9/2
* minimize(sqrt(x^2+y^2)-z,[x^2+y^2<=16,x+y+z=10],[x,y,z])
* >> -4*sqrt(2)-6
* minimize(x*y*z,x^2+y^2+z^2=1,[x,y,z])
* >> -sqrt(3)/9
* minimize(sin(x)+cos(x),x=0..20,coordinates)
* >> -sqrt(2),[5*pi/4,13*pi/4,21*pi/4]
* minimize((1+x^2+3y+5x-4*x*y)/(1+x^2+y^2),x^2/4+y^2/3=9,[x,y])
* >> -2.44662490691
* minimize(x^2-2x+y^2+1,[x+y<=0,x^2<=4],[x,y],locus)
* >> 1/2,[[1/2,-1/2]]
* minimize(x^2*(y+1)-2y,[y<=2,sqrt(1+x^2)<=y],[x,y])
* >> -4
* minimize(4x^2+y^2-2x-4y+1,4x^2+y^2=1,[x,y])
* >> -sqrt(17)+2
* minimize(cos(x)^2+cos(y)^2,x+y=pi/4,[x,y],locus)
* >> (-sqrt(2)+2)/2,[[5*pi/8,-3*pi/8]]
* minimize(x^2+y^2,x^4+y^4=2,[x,y])
* >> 1.41421356237
* minimize(z*x*exp(y),z^2+x^2+exp(2y)=1,[x,y,z])
* >> -sqrt(3)/9
*/
gen _minimize(const gen &args,GIAC_CONTEXT) {
if (args.type==_STRNG && args.subtype==-1) return args;
if (args.type!=_VECT || args.subtype!=_SEQ__VECT || args._VECTptr->size()>4)
return gentypeerr(contextptr);
vecteur &argv=*args._VECTptr,g,h;
bool location=false;
int nargs=argv.size();
if (argv.back()==at_coordonnees || argv.back()==at_lieu || argv.back()==at_point) {
location=true;
--nargs;
}
if (nargs==3) {
vecteur constr(argv[1].type==_VECT ? *argv[1]._VECTptr : vecteur(1,argv[1]));
for (const_iterateur it=constr.begin();it!=constr.end();++it) {
if ((*it).is_symb_of_sommet(at_equal))
h.push_back(equal2diff(*it));
else if ((*it).is_symb_of_sommet(at_superieur_egal) ||
(*it).is_symb_of_sommet(at_inferieur_egal))
g.push_back(*it);
else
h.push_back(*it);
}
}
vecteur vars,initial;
int n; // number of variables
if ((n=parse_varlist(argv[nargs-1],vars,g,initial,contextptr))==0 || !initial.empty())
return gensizeerr(contextptr);
if (n>1) {
for (int i=0;i<int(g.size());++i) {
gen &gi=g[i];
vecteur &s=*gi._SYMBptr->feuille._VECTptr;
g[i]=gi.is_symb_of_sommet(at_inferieur_egal)?s[0]-s[1]:s[1]-s[0];
}
}
gen &f=argv[0];
gen mn,mx;
vecteur loc(global_extrema(f,g,h,vars,mn,mx,contextptr));
if (loc.empty())
return undef;
if (location)
return makesequence(_simplify(mn,contextptr),_simplify(loc,contextptr));
return _simplify(mn,contextptr);
}
static const char _minimize_s []="minimize";
static define_unary_function_eval (__minimize,&_minimize,_minimize_s);
define_unary_function_ptr5(at_minimize,alias_at_minimize,&__minimize,0,true)
/*
* 'maximize' takes the same arguments as the function 'minimize', but
* maximizes the objective function. See 'minimize' for details.
*
* Examples
* ^^^^^^^^
* maximize(cos(x),x=1..3)
* >> cos(1)
* maximize(piecewise(x<=-2,x+6,x<=1,x^2,3/2-x/2),x=-3..2)
* >> 4
* minimize(x-abs(x),x=-1..1)
* >> 0
* maximize(x^2-3x+y^2+3y+3,[x=2..4,y=-4..-2])
* >> 11
* maximize(x*y*z,x^2+2*y^2+3*z^2<=1,[x,y,z],point)
* >> sqrt(2)/18,[[-sqrt(3)/3,sqrt(6)/6,-1/3],[sqrt(3)/3,-sqrt(6)/6,-1/3],
* [-sqrt(3)/3,-sqrt(6)/6,1/3],[sqrt(3)/3,sqrt(6)/6,1/3]]
* maximize(x^2-x*y+2*y^2,[x=-1..0,y=-1/2..1/2],coordinates)
* >> 2,[[-1,1/2]]
* maximize(x*y,[x+y^2<=2,x>=0,y>=0],[x,y],locus)
* >> 4*sqrt(6)/9,[[4/3,sqrt(6)/3]]
* maximize(y^2-x^2*y,y<=x,[x=0..2,y=0..2])
* >> 4/27
* maximize(2x+y,4x^2+y^2=8,[x,y])
* >> 4
* maximize(x^2*(y+1)-2y,[y<=2,sqrt(1+x^2)<=y],[x,y])
* >> 5
* maximize(4x^2+y^2-2x-4y+1,4x^2+y^2=1,[x,y])
* >> sqrt(17)+2
* maximize(3x+2y,2x^2+3y^2<=3,[x,y])
* >> sqrt(70)/2
* maximize(x*y,[2x+3y<=10,x>=0,y>=0],[x,y])
* >> 25/6
* maximize(x^2+y^2+z^2,[x^2/16+y^2+z^2=1,x+y+z=0],[x,y,z])
* >> 8/3
* assume(a>0);maximize(x^2*y^2*z^2,x^2+y^2+z^2=a^2,[x,y,z])
* >> a^6/27
*/
gen _maximize(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
if (g.type!=_VECT || g.subtype!=_SEQ__VECT || g._VECTptr->size()<2)
return gentypeerr(contextptr);
vecteur gv(*g._VECTptr);
gv[0]=-gv[0];
gen res=_minimize(_feuille(gv,contextptr),contextptr);
if (res.type==_VECT && res._VECTptr->size()>0) {
res._VECTptr->front()=-res._VECTptr->front();
}
else if (res.type!=_VECT)
res=-res;
return res;
}
static const char _maximize_s []="maximize";
static define_unary_function_eval (__maximize,&_maximize,_maximize_s);
define_unary_function_ptr5(at_maximize,alias_at_maximize,&__maximize,0,true)
int ipdiff::sum_ivector(const ivector &v,bool drop_last) {
int res=0;
for (ivector_iter it=v.begin();it!=v.end()-drop_last?1:0;++it) {
res+=*it;
}
return res;
}
/*
* IPDIFF CLASS IMPLEMENTATION
*/
ipdiff::ipdiff(const gen &f_orig,const vecteur &g_orig,const vecteur &vars_orig,GIAC_CONTEXT) {
ctx=contextptr;
f=f_orig;
g=g_orig;
vars=vars_orig;
ord=0;
nconstr=g.size();
nvars=vars.size()-nconstr;
assert(nvars>0);
pdv[ivector(nvars,0)]=f; // make the zeroth order derivative initially available
}
void ipdiff::ipartition(int m,int n,ivectors &c,const ivector &p) {
for (int i=0;i<n;++i) {
if (!p.empty() && p[i]!=0)
continue;
ivector r;
if (p.empty())
r.resize(n,0);
else r=p;
for (int j=0;j<m;++j) {
++r[i];
int s=sum_ivector(r);
if (s==m && find(c.begin(),c.end(),r)==c.end())
c.push_back(r);
else if (s<m)
ipartition(m,n,c,r);
else break;
}
}
}
ipdiff::diffterms ipdiff::derive_diffterms(const diffterms &terms,ivector &sig) {
while (!sig.empty() && sig.back()==0) {
sig.pop_back();
}
if (sig.empty())
return terms;
int k=sig.size()-1,p;
diffterms tv;
ivector u(nvars+1,0);
for (diffterms::const_iterator it=terms.begin();it!=terms.end();++it) {
int c=it->second;
diffterm t(it->first);
const ivector_map &h_orig=it->first.second;
++t.first.at(k);
tv[t]+=c;
--t.first.at(k);
ivector_map h(h_orig);
for (ivector_map::const_iterator jt=h_orig.begin();jt!=h_orig.end();++jt) {
ivector v=jt->first;
if ((p=jt->second)==0)
continue;
if (p==1)
h.erase(h.find(v));
else
--h[v];
++v[k];
++h[v];
t.second=h;
tv[t]+=c*p;
--h[v];
--v[k];
++h[v];
}
t.second=h_orig;
for (int i=0;i<nconstr;++i) {
++t.first.at(nvars+i);
u[k]=1;
u.back()=i;
++t.second[u];
tv[t]+=c;
--t.first.at(nvars+i);
--t.second[u];
u[k]=0;
}
}
--sig.back();
return derive_diffterms(tv,sig);
}
const gen &ipdiff::get_pd(const pd_map &pds,const ivector &sig) const {
try {
return pds.at(sig);
}
catch (out_of_range &e) {
return undef;
}
}
const gen &ipdiff::differentiate(const gen &e,pd_map &pds,const ivector &sig) {
const gen &pd=get_pd(pds,sig);
if (!is_undef(pd))
return pd;
vecteur v(1,e);
bool do_derive=false;
assert(vars.size()<=sig.size());
for (int i=0;i<int(vars.size());++i) {
if (sig[i]>0) {
v=mergevecteur(v,vecteur(sig[i],vars[i]));
do_derive=true;
}
}
if (do_derive)
return pds[sig]=_derive(_feuille(v,ctx),ctx);
return e;
}
void ipdiff::compute_h(const vector<diffterms> &grv,int order) {
if (g.empty())
return;
ivectors hsigv;
matrice A;
vecteur b(g.size()*grv.size(),gen(0));
gen t;
int grv_sz=grv.size();
for (int i=0;i<nconstr;++i) {
for (int j=0;j<grv_sz;++j) {
vecteur eq(g.size()*grv_sz,gen(0));
const diffterms &grvj=grv[j];
for (diffterms::const_iterator it=grvj.begin();it!=grvj.end();++it) {
ivector sig(it->first.first),hsig;
sig.push_back(i);
t=gen(it->second)*differentiate(g[i],pdg,sig);
for (ivector_map::const_iterator ht=it->first.second.begin();ht!=it->first.second.end();++ht) {
if (ht->second==0)
continue;
const ivector &sigh=ht->first;
if (sum_ivector(sigh,true)<order) {
gen h(get_pd(pdh,sigh));
assert(!is_undef(h));
t=t*pow(h,ht->second);
}
else {
assert(ht->second==1);
hsig=sigh;
}
}
if (hsig.empty())
b[grv_sz*i+j]-=t;
else {
int k=0,hsigv_sz=hsigv.size();
for (;k<hsigv_sz;++k) {
if (hsigv[k]==hsig)
break;
}
eq[k]+=t;
if (k==hsigv_sz)
hsigv.push_back(hsig);
}
}
A.push_back(*_ratnormal(eq,ctx)._VECTptr);
}
}
matrice B;
B.push_back(*_ratnormal(b,ctx)._VECTptr);
matrice invA=*_inv(A,ctx)._VECTptr;
vecteur sol(*mtran(mmult(invA,mtran(B))).front()._VECTptr);
for (int i=0;i<int(sol.size());++i) {
pdh[hsigv[i]]=_ratnormal(sol[i],ctx);
}
}
void ipdiff::find_nearest_terms(const ivector &sig,diffterms &match,ivector &excess) {
excess=sig;
int i;
for (map<ivector,diffterms>::const_iterator it=cterms.begin();it!=cterms.end();++it) {
ivector ex(nvars,0);
for (i=0;i<nvars;++i) {
if ((ex[i]=sig[i]-it->first.at(i))<0)
break;
}
if (i<nvars)
continue;
if (sum_ivector(ex)<sum_ivector(excess)) {
excess=ex;
match=it->second;
}
}
}
void ipdiff::raise_order(int order) {
if (g.empty())
return;
ivectors c;
ivector excess,init_f(nvars+nconstr,0);
diffterm init_term;
init_term.first=init_f;
diffterms init_terms;
init_terms[init_term]=1;
vector<diffterms> grv;
for (int k=ord+1;k<=order;++k) {
grv.clear();
c.clear();
ipartition(k,nvars,c);
for (ivectors::const_iterator it=c.begin();it!=c.end();++it) {
diffterms terms=init_terms;
find_nearest_terms(*it,terms,excess);
if (sum_ivector(excess)>0) {
terms=derive_diffterms(terms,excess);
cterms[*it]=terms;
}
grv.push_back(terms);
}
compute_h(grv,k);
}
ord=order;
}
void ipdiff::compute_pd(int order,const ivector &sig) {
gen pd;
ivectors c;
ipartition(order,nvars,c);
for (ivectors::const_iterator ct=c.begin();ct!=c.end();++ct) {
if (!sig.empty() && sig!=*ct)
continue;
if (g.empty()) {
differentiate(f,pdv,sig);
continue;
}
diffterms &terms=cterms[*ct];
pd=gen(0);
for (diffterms::const_iterator it=terms.begin();it!=terms.end();++it) {
ivector sig(it->first.first);
gen t(gen(it->second)*differentiate(f,pdf,sig));
if (!is_zero(t)) {
for (ivector_map::const_iterator jt=it->first.second.begin();jt!=it->first.second.end();++jt) {
if (jt->second==0)
continue;
gen h(get_pd(pdh,jt->first));
assert(!is_undef(h));
t=t*pow(h,jt->second);
}
pd+=t;
}
}
pdv[*ct]=_ratnormal(pd,ctx);
}
}
void ipdiff::gradient(vecteur &res) {
if (nconstr==0)
res=*_grad(makesequence(f,vars),ctx)._VECTptr;
else {
res.resize(nvars);
ivector sig(nvars,0);
if (ord<1) {
raise_order(1);
compute_pd(1);
}
for (int i=0;i<nvars;++i) {
sig[i]=1;
res[i]=derivative(sig);
sig[i]=0;
}
}
}
void ipdiff::hessian(matrice &res) {
if (nconstr==0)
res=*_hessian(makesequence(f,vars),ctx)._VECTptr;
else {
res.clear();
ivector sig(nvars,0);
if (ord<2) {
raise_order(2);
compute_pd(2);
}
for (int i=0;i<nvars;++i) {
vecteur r(nvars);
++sig[i];
for (int j=0;j<nvars;++j) {
++sig[j];
r[j]=derivative(sig);
--sig[j];
}
res.push_back(r);
--sig[i];
}
}
}
const gen &ipdiff::derivative(const ivector &sig) {
if (nconstr==0)
return differentiate(f,pdf,sig);
int k=sum_ivector(sig); // the order of the derivative
if (k>ord) {
raise_order(k);
compute_pd(k,sig);
}
return get_pd(pdv,sig);
}
const gen &ipdiff::derivative(const vecteur &dvars) {
ivector sig(nvars,0);
const_iterateur jt;
for (const_iterateur it=dvars.begin();it!=dvars.end();++it) {
if ((jt=find(vars.begin(),vars.end(),*it))==vars.end())
return undef;
++sig[jt-vars.begin()];
}
return derivative(sig);
}
void ipdiff::partial_derivatives(int order,pd_map &pdmap) {
if (nconstr>0 && ord<order) {
raise_order(order);
compute_pd(order);
}
ivectors c;
ipartition(order,nvars,c);
for (ivectors::const_iterator it=c.begin();it!=c.end();++it) {
pdmap[*it]=derivative(*it);
}
}
gen ipdiff::taylor_term(const vecteur &a,int k) {
assert(k>=0);
if (k==0)
return subst(f,vars,a,false,ctx);
ivectors sigv;
ipartition(k,nvars,sigv);
gen term(0);
if (nconstr>0) while (k>ord) {
raise_order(ord+1);
compute_pd(ord);
}
for (ivectors::const_iterator it=sigv.begin();it!=sigv.end();++it) {
gen pd;
if (g.empty()) {
vecteur args(1,f);
for (int i=0;i<nvars;++i) {
for (int j=0;j<it->at(i);++j) {
args.push_back(vars[i]);
}
}
pd=_derive(_feuille(args,ctx),ctx);
}
else
pd=derivative(*it);
pd=subst(pd,vars,a,false,ctx);
for (int i=0;i<nvars;++i) {
int ki=it->at(i);
if (ki==0)
continue;
pd=pd*pow(vars[i]-a[i],ki)/factorial(ki);
}
term+=pd;
}
return term;
}
gen ipdiff::taylor(const vecteur &a,int order) {
assert(order>=0);
gen T(0);
for (int k=0;k<=order;++k) {
T+=taylor_term(a,k);
}
return T;
}
/*
* END OF IPDIFF CLASS
*/
void vars_arrangements(matrice J,ipdiff::ivectors &arrs,GIAC_CONTEXT) {
int m=J.size(),n=J.front()._VECTptr->size();
assert(n<=32 && m<n);
matrice tJ(mtran(J));
ulong N=std::pow(2,n);
vector<ulong> sets(comb(n,m).val);
int i=0;
for (ulong k=1;k<N;++k) {
bitset<32> b(k);
if (b.count()==(size_t)m)
sets[i++]=k;
}
matrice S;
ipdiff::ivector arr(n);
for (vector<ulong>::const_iterator it=sets.begin();it!=sets.end();++it) {
for (i=0;i<n;++i) arr[i]=i;
N=std::pow(2,n);
for (i=n;i-->0;) {
N/=2;
if ((*it & N)!=0) {
arr.erase(arr.begin()+i);
arr.push_back(i);
}
}
S.clear();