-
Notifications
You must be signed in to change notification settings - Fork 2
/
signalprocessing.cc
7837 lines (7625 loc) · 317 KB
/
signalprocessing.cc
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
/*
* signalprocessing.cc
*
* (c) 2018-2019 by 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/>.
*/
#include "giacPCH.h"
#include "giac.h"
#include "signalprocessing.h"
#include "graphtheory.h"
#include "usual.h"
#include "plot.h"
#ifdef HAVE_LIBSAMPLERATE
#include "samplerate.h"
#endif
#ifdef HAVE_LIBAO
#include <ao/ao.h>
#endif
#ifndef HAVE_PNG_H
#undef HAVE_LIBPNG
#endif
#ifdef HAVE_LIBPNG
#include <png.h>
#endif
using namespace std;
#ifndef NO_NAMESPACE_GIAC
namespace giac {
#endif // ndef NO_NAMESPACE_GIAC
#define _SP_BAD_SOUND_DATA gettext("Invalid sound data")
#define _SP_INVALID_RANGE gettext("Invalid range specification")
#define _SP_BAD_WINDOW gettext("Invalid window parameters")
#define MAX_TAILLE 500
#define MAX_FACTORS 10
#define MIDI_NOTE_0 8.17579891564
#define GREY_COLOR 47
double mylog2(double x) {
return std::log(x)/M_LN2;
}
string n2hexstr(char c) {
static const char* digits="0123456789ABCDEF";
std::string hex(2,'0');
for (size_t i=0,j=4;i<2;++i,j-=4)
hex[i]=digits[(c>>j) & 0x0f];
return hex;
}
int nextpow2(int n) {
return 1<<int(std::ceil(mylog2(n)));
}
gen generr(const char* msg) {
string m(msg);
m.append(".");
return gensizeerr(m.c_str());
}
gen generrtype(const char* msg) {
string m(msg);
m.append(".");
return gentypeerr(m.c_str());
}
gen generrdim(const char* msg) {
string m(msg);
m.append(".");
return gendimerr(m.c_str());
}
gen generrarg(int i) {
return generr(string(gettext("Invalid argument")+string(" ")+print_INT_(i)).c_str());
}
void print_error(const char *msg,GIAC_CONTEXT) {
*logptr(contextptr) << gettext("Error") << ": " << gettext(msg) << "\n";
}
void print_warning(const char *msg,GIAC_CONTEXT) {
*logptr(contextptr) << gettext("Warning") << ": " << gettext(msg) << "\n";
}
bool is_whitespace(char c) {
return c==32 || (c>8 && c<14);
}
string trim_left(const string &s) {
string::const_iterator it=s.begin(),itend=s.end();
for (;it!=itend && is_whitespace(*it);++it);
return string(it,itend);
}
string trim_right(const string &s) {
string::const_iterator it=s.end(),itend=s.begin();
bool yes=true;
while (it!=itend && (yes=is_whitespace(*(--it))));
if (it!=itend || !yes) ++it;
return string(itend,it);
}
bool iszero(const gen &g,const gen &t,GIAC_CONTEXT) {
return (is_undef(t) && is_zero(_abs(g,contextptr),contextptr)) ||
(!is_undef(t) && is_strictly_greater(t,_abs(g,contextptr),contextptr));
}
gen _trim(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
bool has_opt=g.type==_VECT && g.subtype==_SEQ__VECT,retpos=false;
if (has_opt && g._VECTptr->size()<2)
return gendimerr(contextptr);
const gen &a=has_opt?g._VECTptr->front():g;
int optstart=has_opt?g._VECTptr->size()-1:0,dir=0;
if (has_opt) {
if (g._VECTptr->at(optstart)==at_index) retpos=(bool)(optstart--);
if (g._VECTptr->at(optstart)==at_left) dir=-(optstart--);
else if (g._VECTptr->at(optstart)==at_right) dir=(optstart--);
}
if (a.type==_STRNG) { // trim a string
if (optstart)
return gensizeerr(contextptr);
string lstr=dir<=0?trim_left(*a._STRNGptr):*a._STRNGptr;
string rstr=dir>=0?trim_right(lstr):lstr;
size_t d=a._STRNGptr->length()-lstr.length(),len=rstr.length();
return retpos?(dir<0?gen(d):(dir>0?gen(len):makesequence(d,len))):string2gen(rstr,false);
}
gen thr;
rgba_image *img=rgba_image::from_gen(a);
if (img!=NULL) { // trim zero pixel margins from an image
if (dir)
return generr(gettext("One-sided trimming is not supported for images"));
if (optstart>1)
return gentoomanyargs(gettext("Too many arguments"),contextptr);
bool inverted=false;
if (optstart==1) {
if (g._VECTptr->at(optstart)!=at_inv)
return gensizeerr(contextptr);
inverted=true;
}
matrice cd=*(inverted?-(*img):*img)[change_subtype(GREY_COLOR,_INT_COLOR)]._VECTptr;
vecteur xw=*_trim(makesequence(_sum(cd,contextptr),at_index),contextptr)._VECTptr;
vecteur yh=*_trim(makesequence(_sum(mtran(cd),contextptr),at_index),contextptr)._VECTptr;
gen ret=makesequence(xw[0],yh[0],xw[1],yh[1]);
return retpos?ret:(*img)(ret,contextptr);
}
audio_clip *clip=audio_clip::from_gen(a);
if (clip!=NULL) { // trim an audio clip
int n=clip->length(),sr=clip->sample_rate(),cs=sr/100;
gen dbs(-30.0);
if (optstart>2)
return gentoomanyargs(gettext("Too many arguments"),contextptr);
if (optstart==2) {
const gen &opt=g._VECTptr->at(optstart);
if (!is_real_number(opt,contextptr) || !is_positive(opt,contextptr))
return generr(gettext("Expected a nonnegative real number"));
cs=_round(sr*to_real_number(opt,contextptr),contextptr).val;
--optstart;
}
if (optstart==1) {
const gen &opt=g._VECTptr->at(optstart);
if (!is_real_number(opt,contextptr) || !is_strictly_positive(-opt,contextptr))
return generr(gettext("Expected a negative real number"));
dbs=to_real_number(opt,contextptr);
}
int N=nextpow2(sr/20);
gen data=_channel_data(_stereo2mono(a,contextptr),contextptr);
if (data.type!=_VECT)
return gensizeerr(gettext("Failed to extract audio data"));
thr=_pow(makesequence(10.0,dbs/gen(10.0)),contextptr);
double alpha=0.05;
int overlap=int(alpha*(N-1)),i;
data._VECTptr->resize(((n-overlap)/(N-overlap)+1)*(N-overlap)+overlap,0);
int nn=data._VECTptr->size(),lb=0,ub=n;
if (dir<=0) {
for (i=0;i<nn-N+1;i+=N-overlap) {
vecteur v=*_tukey_window(makesequence(vecteur(data._VECTptr->begin()+i,data._VECTptr->begin()+i+N),alpha),contextptr)._VECTptr;
vecteur e=*_hilbert(v,contextptr)._VECTptr;
iterateur it=e.begin(),itend=e.end();
for (;it!=itend;++it)
*it=pow(re(*it,contextptr),2)+pow(im(*it,contextptr),2);
v=*_moving_average(makesequence(e,cs),contextptr)._VECTptr;
lb=_trim(makesequence(v,thr,at_left,at_index),contextptr).val;
if (lb<N-cs+1) {
lb+=i;
break;
}
}
if (i>=nn-N+1)
lb=n;
lb=std::min(lb,n);
}
if (dir>=0) {
for (i=nn-N;i>=0;i-=N-overlap) {
vecteur v=*_tukey_window(makesequence(vecteur(data._VECTptr->begin()+i,data._VECTptr->begin()+i+N),alpha),contextptr)._VECTptr;
vecteur e=*_hilbert(v,contextptr)._VECTptr;
iterateur it=e.begin(),itend=e.end();
for (;it!=itend;++it)
*it=pow(re(*it,contextptr),2)+pow(im(*it,contextptr),2);
e=*_moving_average(makesequence(e,cs),contextptr)._VECTptr;
ub=_trim(makesequence(e,thr,at_right,at_index),contextptr).val;
if (ub>0) {
ub+=i;
break;
}
}
if (i<0)
ub=0;
ub=std::max(ub,0);
}
if (!retpos && ub<=lb)
return vecteur(0);
if (dir<0) return retpos?lb:a(lb,contextptr);
if (dir>0) return retpos?ub:a(makesequence(0,ub),contextptr);
gen ret=makesequence(lb,ub);
return retpos?ret:a(ret,contextptr);
}
// trim a real or complex vector
if (a.type!=_VECT)
return gentypeerr(contextptr);
if (optstart>1)
return gentoomanyargs(gettext("Too many arguments"),contextptr);
thr=optstart?g._VECTptr->at(optstart):undef;
if (!is_undef(thr) && (!is_real_number(thr,contextptr) || !is_strictly_positive(thr,contextptr)))
return generr(gettext("Invalid threshold specification"));
const_iterateur it0=a._VECTptr->begin(),it1=it0,itend=a._VECTptr->end(),it2=itend;
try {
if (dir<=0) for (;it1!=itend && iszero(*it1,thr,contextptr);++it1);
if (dir>=0) {
bool yes=true;
while (it2!=it1 && (yes=iszero(*(--it2),thr,contextptr)));
if (it2!=it1 || !yes) ++it2;
}
} catch (const std::runtime_error &err) {
*logptr(contextptr) << err.what() << "\n";
return gensizeerr(contextptr);
}
if (retpos) {
int d=it1-it0,len=it2-it1;
return dir<0?gen(d):(dir>0?gen(len):makesequence(d,len));
}
return vecteur(it1,it2);
}
static const char _trim_s[]="trim";
static define_unary_function_eval (__trim,&_trim,_trim_s);
define_unary_function_ptr5(at_trim,alias_at_trim,&__trim,0,true);
bool is_real_number(const gen &g,GIAC_CONTEXT) {
if (g.type==_INT_ || g.type==_ZINT || g.type==_FLOAT_ || g.type==_DOUBLE_ || g.type==_REAL || g.type==_FRAC)
return true;
return evalf_double(g,1,contextptr).type==_DOUBLE_;
}
bool is_real_vector(const vecteur &v,GIAC_CONTEXT) {
const_iterateur it=v.begin(),itend=v.end();
for (;it!=itend;++it) {
if (!is_real_number(*it,contextptr))
return false;
}
return true;
}
gen to_real_number(const gen &g,GIAC_CONTEXT) {
gen ret=_evalf(g,contextptr);
if (ret.type!=_DOUBLE_)
return evalf_double(ret,1,contextptr);
return ret;
}
bool is_real_interval(const gen &g,gen &a,gen &b,GIAC_CONTEXT) {
if (!g.is_symb_of_sommet(at_interval))
return false;
a=g._SYMBptr->feuille._VECTptr->front();
b=g._SYMBptr->feuille._VECTptr->back();
if (!is_real_number(a,contextptr) || !is_real_number(b,contextptr))
return false;
a=to_real_number(a,contextptr);
b=to_real_number(b,contextptr);
return true;
}
/* Return true iff G has a boolean value. */
bool is_logical(const gen &g) {
return g.is_symb_of_sommet(at_and) || g.is_symb_of_sommet(at_ou) ||
g.is_symb_of_sommet(at_superieur_egal) || g.is_symb_of_sommet(at_inferieur_egal) ||
g.is_symb_of_sommet(at_superieur_strict) || g.is_symb_of_sommet(at_inferieur_strict) ||
g.is_symb_of_sommet(at_same) || g.is_symb_of_sommet(at_equal);
}
/* Set LB and UB to the interval G endpoints.
* The interval endpoints may also be specified as a list. */
bool get_range(const gen &g,gen &lb,gen &ub) {
if (g.is_symb_of_sommet(at_interval)) {
lb=g._SYMBptr->feuille._VECTptr->front();
ub=g._SYMBptr->feuille._VECTptr->back();
} else if (g.type==_VECT && g._VECTptr->size()==2 &&
is_numericv(*g._VECTptr,num_mask_withint | num_mask_withfrac)) {
lb=g._VECTptr->front();
ub=g._VECTptr->back();
} else return false;
return true;
}
/* Return 1 if a<b, -1 if a>=b, and 0 if a and b are not comparable */
int compexpr(const gen &a,const gen &b,GIAC_CONTEXT) {
gen res=_eval(symb_inferieur_strict(a,b),contextptr);
if (res.is_integer() && res.subtype==_INT_BOOLEAN)
return 2*res.val-1;
return 0;
}
void count_func_instances_recursion(const gen &g,const unary_function_ptr *f,int &cnt,bool nested) {
if (g.type==_VECT) {
const_iterateur it=g._VECTptr->begin(),itend=g._VECTptr->end();
for (;it!=itend;++it) count_func_instances_recursion(*it,f,cnt,nested);
return;
}
if (g.is_symb_of_sommet(f)) {
++cnt;
if (!nested) return;
}
if (g.type==_SYMB)
count_func_instances_recursion(g._SYMBptr->feuille,f,cnt,nested);
}
int count_func_instances(const gen &g,const unary_function_ptr *f,bool nested=false) {
int c=0;
count_func_instances_recursion(g,f,c,nested);
return c;
}
bool indomain(const matrice &intervals,const gen &a,GIAC_CONTEXT) {
if (intervals.empty())
return false;
assert(ckmatrix(intervals) && mcols(intervals)==2);
const_iterateur it=intervals.begin(),itend=intervals.end();
for (;it!=itend;++it) {
const vecteur &i=*it->_VECTptr;
if (is_greater(a,i.front(),contextptr) && is_greater(i.back(),a,contextptr))
return true;
}
return false;
}
/* Get the assumptions on identifier G: obtain the domain, feasible interval(s) and excluded points.
* Return true if assumptions are read successfully, else return false. */
bool get_assumptions(const gen &g,int &dom,matrice &intervals,vecteur &excluded,GIAC_CONTEXT) {
if (g.type!=_IDNT)
return false;
dom=-1;
intervals.clear();
excluded.clear();
gen res=_about(g,contextptr);
if (res.type==_IDNT && res==g) {
intervals.push_back(makevecteur(minus_inf,plus_inf));
return true; // no assumptions
}
if (res.type!=_VECT || res.subtype!=_ASSUME__VECT)
return false;
if (res._VECTptr->size()==1) {
if (!res._VECTptr->front().is_integer())
return false;
dom=res._VECTptr->front().val;
return true;
}
if (res._VECTptr->size()!=3)
return false;
if (res._VECTptr->front().is_integer())
dom=res._VECTptr->front().val; // 1 - real, 2 - integer, 4 - complex, 10 - rational
intervals=*res._VECTptr->at(1)._VECTptr;
excluded=*res._VECTptr->at(2)._VECTptr;
return true;
}
/* Set (additional) assumptions on identifier G: must be either inequality
* constraints or bounds in form [L,U]. */
void set_assumptions(const gen &g,const vecteur &cond,const vecteur &excluded,bool additionally,GIAC_CONTEXT) {
if (cond.empty())
return;
vecteur args;
for (const_iterateur it=cond.begin();it!=cond.end();++it) {
if (it->type==_VECT) {
assert(it->_VECTptr->size()==2);
const gen &lb=it->_VECTptr->front(),&ub=it->_VECTptr->back();
gen l=is_inf(lb)?undef:(contains(excluded,lb)?symb_superieur_strict(g,lb):symb_superieur_egal(g,lb));
gen r=is_inf(ub)?undef:(contains(excluded,ub)?symb_inferieur_strict(g,ub):symb_inferieur_egal(g,ub));
if (!is_undef(l) && !is_undef(r))
args.push_back(symb_and(l,r));
else if (!is_undef(l))
args.push_back(l);
else if (!is_undef(r))
args.push_back(r);
} else args.push_back(*it);
}
gen a=symbolic(at_ou,change_subtype(args,_SEQ__VECT));
if (additionally)
giac_additionally(a,contextptr);
else giac_assume(a,contextptr);
}
bool is_simpler(const gen &a,const gen &b) {
return taille(a,MAX_TAILLE)<taille(b,MAX_TAILLE);
}
/* Simplify by applying ratnormal iteratively as far as it goes. */
gen ratsimp(const gen &g,GIAC_CONTEXT) {
gen res(g),smp;
int ta=taille(res,MAX_TAILLE),tb;
while (true) {
smp=ratnormal(res,contextptr);
if ((tb=taille(smp,MAX_TAILLE))>=ta)
break;
res=smp;
ta=tb;
}
return res;
}
gen sign2Heaviside(const gen &g) {
if (g.type==_VECT) {
vecteur res;
res.reserve(g._VECTptr->size());
for (const_iterateur it=g._VECTptr->begin();it!=g._VECTptr->end();++it) {
res.push_back(sign2Heaviside(*it));
}
return gen(res,g.subtype);
}
if (g.is_symb_of_sommet(at_sign))
return 2*symbolic(at_Heaviside,g._SYMBptr->feuille)-1;
if (g.type==_SYMB)
return symbolic(g._SYMBptr->sommet,sign2Heaviside(g._SYMBptr->feuille));
return g;
}
gen Heaviside2sign(const gen &g) {
if (g.type==_VECT) {
vecteur res;
res.reserve(g._VECTptr->size());
for (const_iterateur it=g._VECTptr->begin();it!=g._VECTptr->end();++it) {
res.push_back(Heaviside2sign(*it));
}
return gen(res,g.subtype);
}
if (g.is_symb_of_sommet(at_Heaviside))
return (symbolic(at_sign,g._SYMBptr->feuille)+1)/2;
if (g.type==_SYMB)
return symbolic(g._SYMBptr->sommet,Heaviside2sign(g._SYMBptr->feuille));
return g;
}
/* Convert Re(z) and Im(z) to (z+conj(z))/2 and (z-conj(z))/2, respectively. */
gen reim2conj(const gen &g) {
if (g.type==_VECT) {
vecteur res;
res.reserve(g._VECTptr->size());
const_iterateur it=g._VECTptr->begin(),itend=g._VECTptr->end();
for (;it!=itend;++it) res.push_back(reim2conj(*it));
return gen(res,g.subtype);
}
if (g.is_symb_of_sommet(at_re) || g.is_symb_of_sommet(at_im)) {
gen z=g._SYMBptr->feuille,s=g.is_symb_of_sommet(at_re)?1:-1;
return (z+s*symb_conj(z))/2;
}
if (g.type==_SYMB)
return symbolic(g._SYMBptr->sommet,reim2conj(g._SYMBptr->feuille));
return g;
}
bool is_const_wrt(const gen &g,const gen &x,GIAC_CONTEXT) {
return is_constant_wrt(sign2Heaviside(g),x,contextptr) && !contains(*_lname(g,contextptr)._VECTptr,x);
}
bool is_integer_idnt(const gen &g,GIAC_CONTEXT) {
if (g.type!=_IDNT)
return false;
matrice i;
vecteur e;
int d;
return get_assumptions(g,d,i,e,contextptr) && d==2;
}
/* Test whether G necessarily has an integral value. */
bool is_inZ(const gen &g_orig,GIAC_CONTEXT) {
gen g=ratnormal(g_orig,contextptr);
if (g.is_integer() || is_integer_idnt(g,contextptr))
return true;
if (g.type!=_SYMB || !is_one(_denom(g,contextptr)))
return false;
const gen &ar=g._SYMBptr->feuille;
if (g.is_symb_of_sommet(at_neg))
return is_inZ(ar,contextptr);
gen d;
if (g.is_symb_of_sommet(at_pow) && ar.type==_VECT && (d=ar._VECTptr->back()).is_integer() && d.val>=0)
return is_inZ(ar._VECTptr->front(),contextptr);
if (g.is_symb_of_sommet(at_floor) || g.is_symb_of_sommet(at_ceil) ||
g.is_symb_of_sommet(at_sign) || g.is_symb_of_sommet(at_Heaviside) ||
g.is_symb_of_sommet(at_legendre_symbol) || g.is_symb_of_sommet(at_jacobi_symbol))
return true;
if ((g.is_symb_of_sommet(at_plus) || g.is_symb_of_sommet(at_prod)) && ar.type==_VECT) {
const_iterateur it=ar._VECTptr->begin(),itend=ar._VECTptr->end();
for (;it!=itend;++it) {
if (!is_inZ(*it,contextptr))
return false;
}
return true;
}
return false;
}
/* Does the expression g contain a symbolic subexpression with sommet f?
* set a and rest to the argument of first found f and the multiplier of f(a), respectively. */
bool contains_f(const gen &g,const unary_function_ptr *f,gen &a,gen &rest,GIAC_CONTEXT) {
bool ret=false;
if (g.type!=_SYMB)
return ret;
if (g.is_symb_of_sommet(f)) {
rest=1;
a=g._SYMBptr->feuille;
return true;
}
if (g.is_symb_of_sommet(at_prod)) {
rest=1;
vecteur fac=g._SYMBptr->feuille.type==_VECT?*g._SYMBptr->feuille._VECTptr:vecteur(1,g._SYMBptr->feuille);
const_iterateur it=fac.begin(),itend=fac.end();
for (;it!=itend;++it) {
if (!ret && it->is_symb_of_sommet(f)) {
a=it->_SYMBptr->feuille;
ret=true;
} else rest=*it*rest;
}
} else if (g.is_symb_of_sommet(at_neg)) {
if (contains_f(g._SYMBptr->feuille,f,a,rest,contextptr)) {
rest=-rest;
return true;
}
return false;
}
return ret;
}
/* Find linear transformations of x appearing as arguments to other functions. */
void lintx(const gen &g,const identificateur &x,vecteur <,GIAC_CONTEXT) {
gen a,b;
if (g.type==_VECT) {
const_iterateur it=g._VECTptr->begin(),itend=g._VECTptr->end();
for (;it!=itend;++it) lintx(*it,x,lt,contextptr);
} else if (is_linear_wrt(g,x,a,b,contextptr) && !is_zero(a) && is_zero(im(a,contextptr)) && is_zero(im(b,contextptr)))
lt.push_back(makevecteur(a,b));
else if (g.type==_SYMB)
lintx(g._SYMBptr->feuille,x,lt,contextptr);
}
/* Rewrite a linear combination of instances of f such that the number of f-applications is minimal. */
gen collect_with_func(const gen &g_orig,const unary_function_ptr *f,gen_map *m,gen *rest,GIAC_CONTEXT) {
bool with_m=m!=NULL;
assert(!with_m || rest!=NULL);
gen g=expand(g_orig,contextptr);
vecteur terms;
if (g.is_symb_of_sommet(at_plus))
terms=g._SYMBptr->feuille.type==_VECT?*g._SYMBptr->feuille._VECTptr:vecteur(1,g._SYMBptr->feuille);
else terms=vecteur(1,g);
gen ret=0,a,r;
gen_map ft;
if (with_m) {
*rest=0;
m->clear();
}
gen_map &fterms=with_m?*m:ft;
const_iterateur it=terms.begin(),itend=terms.end();
for (;it!=itend;++it) {
if (contains_f(*it,f,a,r,contextptr))
fterms[a]+=r;
else if (!with_m)
ret+=*it;
else *rest+=*it;
}
gen_map::const_iterator jt=fterms.begin(),jtend=fterms.end();
if (!with_m)
for (;jt!=jtend;++jt) ret+=ratnormal(jt->second,contextptr)*symbolic(f,jt->first);
return with_m?0:ret;
}
gen simplify_floor(const gen &g,GIAC_CONTEXT) {
if (g.type==_VECT) {
vecteur res;
res.reserve(g._VECTptr->size());
const_iterateur it=g._VECTptr->begin(),itend=g._VECTptr->end();
for (;it!=itend;++it) {
res.push_back(simplify_floor(*it,contextptr));
}
return gen(res,g.subtype);
}
if (g.type!=_SYMB)
return g;
const gen &args=g._SYMBptr->feuille;
if (g.is_symb_of_sommet(at_floor)) {
gen e=expand(ratnormal(simplify_floor(args,contextptr),contextptr),contextptr),ar=0,rest=0,num,den;
vecteur terms=e.is_symb_of_sommet(at_plus)?*e._SYMBptr->feuille._VECTptr:vecteur(1,e);
const_iterateur it=terms.begin(),itend=terms.end();
for (;it!=itend;++it) {
if (is_inZ(*it,contextptr))
rest+=*it;
else if (is_real_number(*it,contextptr)) {
gen f=_floor(_abs(*it,contextptr),contextptr),s=_sign(*it,contextptr);
rest+=f*s;
ar+=*it-f*s;
} else ar+=*it;
}
ar=ratnormal(ar,contextptr);
if (is_inZ(ar,contextptr))
return ar+rest;
if (ar.type==_FRAC)
return rest+(is_positive(ar,contextptr)?symbolic(at_floor,ar):
-symbolic(at_floor,(_abs(ar._FRACptr->num,contextptr)-1)/_abs(ar._FRACptr->den,contextptr))-1);
/* handle some cases of nesting */
if ((den=_denom(ar,contextptr)).is_integer() && den.val>0) {
num=expand(simplify_floor(_numer(ar,contextptr),contextptr),contextptr);
gen a,b,c(undef);
if (num.is_symb_of_sommet(at_floor))
return rest+simplify_floor(_floor(num._SYMBptr->feuille/den,contextptr),contextptr);
if (num.is_symb_of_sommet(at_neg) && (a=num._SYMBptr->feuille).is_symb_of_sommet(at_ceil))
return rest+simplify_floor(_floor(-a._SYMBptr->feuille/den,contextptr),contextptr);
if (num.is_symb_of_sommet(at_plus) && num._SYMBptr->feuille.type==_VECT) {
const vecteur &terms=*num._SYMBptr->feuille._VECTptr;
const_iterateur it=terms.begin(),itend=terms.end(),jt=itend;
a=undef;
for (;it!=itend;++it) {
if (it->is_symb_of_sommet(at_floor)) {
if (is_undef(a) || is_simpler(a,it->_SYMBptr->feuille)) {
a=it->_SYMBptr->feuille;
jt=it;
}
} else if (it->is_symb_of_sommet(at_neg) && (b=it->_SYMBptr->feuille).is_symb_of_sommet(at_ceil)) {
if (is_undef(a) || is_simpler(a,-b._SYMBptr->feuille)) {
a=-b._SYMBptr->feuille;
jt=it;
}
}
}
if (jt!=itend) {
vecteur t(terms);
t.erase(t.begin()+(jt-terms.begin()));
b=_sum(t,contextptr);
if (is_inZ(b,contextptr))
return rest+simplify_floor(_floor(ratnormal((a+b)/den,contextptr),contextptr),contextptr);
}
}
}
return is_zero(rest)?_floor(ar,contextptr):rest+simplify_floor(_floor(ar,contextptr),contextptr);
}
if (g.is_symb_of_sommet(at_ceil))
return simplify_floor(-symbolic(at_floor,-args),contextptr);
return symbolic(g._SYMBptr->sommet,simplify_floor(args,contextptr));
}
bool is_periodic_wrt(const gen &g_orig,const gen &x,gen &T,GIAC_CONTEXT) {
gen g=ratnormal(g_orig,contextptr);
if (is_const_wrt(g,x,contextptr))
return true;
gen f=_lin(trig2exp(g,contextptr),contextptr);
vecteur v;
lvar(f,v);
bool hasx=find(v.begin(),v.end(),x)!=v.end();
v.clear();
rlvarx(f,x,v);
islesscomplexthanf_sort(v.begin(),v.end());
int i,s=int(v.size());
if (s<2)
return false;
gen a,b,r,d,U;
bool chk=false,upd;
for (i=1;i<s && !is_inf(T);++i) {
upd=false;
if (v[i].is_symb_of_sommet(at_exp) && is_linear_wrt(v[i]._SYMBptr->feuille,x,a,b,contextptr) && !is_zero(a)) {
U=ratnormal(cst_two_pi*cst_i/a,contextptr);
if (!is_zero(ratnormal(im(U,contextptr),contextptr)))
return false;
U=_abs(U,contextptr);
upd=true;
} else if (v[i].is_symb_of_sommet(at_floor) && is_linear_wrt(v[i]._SYMBptr->feuille,x,a,b,contextptr) &&
!is_zero(a) && is_const_wrt(b,x,contextptr)) {
U=ratnormal(_inv(_abs(a,contextptr),contextptr));
upd=true;
chk=true;
} else if (v[i].type==_SYMB && v[i]._SYMBptr->feuille.type!=_VECT) {
if (!is_periodic_wrt(v[i]._SYMBptr->feuille,x,T,contextptr))
return false;
} else return false;
if (upd) {
if (is_undef(T))
T=U;
else {
r=ratnormal(T/U,contextptr);
if (!is_inZ(_numer(r,contextptr),contextptr) || !is_inZ(d=_denom(r,contextptr),contextptr))
return false;
T=T*d;
}
}
}
if (chk) {
gen s=simplify_floor(g-subst(g,x,x+T,false,contextptr),contextptr);
return is_zero(simplify(s,contextptr)) || is_zero(_trigsimplify(s,contextptr));
}
return !hasx;
}
/* Return a period of the given expression if it is periodic with respect
* to the given real variable, else return +inf.
* If the returned value is zero, it means that any positive real number is
* a period (e.g. for constant functions). */
gen _period(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
gen e,x=identificateur("x"),T(undef);
if (g.type!=_VECT || g.subtype!=_SEQ__VECT)
e=g;
else {
if (g._VECTptr->size()!=2)
return gendimerr(contextptr);
if ((x=g._VECTptr->back()).type!=_IDNT)
return gentypeerr(contextptr);
e=g._VECTptr->front();
}
e=simplify_floor(recursive_normal(e,contextptr),contextptr);
if (!is_periodic_wrt(e,x,T,contextptr))
return plus_inf;
return is_undef(T)?gen(0):T;
}
static const char _period_s[]="period";
static define_unary_function_eval (__period,&_period,_period_s);
define_unary_function_ptr5(at_period,alias_at_period,&__period,0,true);
gen _simplifyFloor(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
return simplify_floor(recursive_normal(g,contextptr),contextptr);
}
static const char _simplifyFloor_s[]="simplifyFloor";
static define_unary_function_eval (__simplifyFloor,&_simplifyFloor,_simplifyFloor_s);
define_unary_function_ptr5(at_simplifyFloor,alias_at_simplifyFloor,&__simplifyFloor,0,true);
matrice stft(const vecteur &x,int m,const unary_function_ptr *wf,GIAC_CONTEXT) {
int n=x.size(),i,j;
assert(n%m==0);
int N=n/m-1; // number of DFTs
matrice res;
res.reserve(N);
vecteur v(m),a(m),b(m);
const_iterateur it;
iterateur jt,ait,bit;
for (i=0,ait=a.begin(),bit=b.begin();i<m;++i,++ait,++bit) {
gen w=cst_i*exp(-i*cst_i*(cst_two_pi/(2.0*m)),contextptr);
*ait=(1.0-w)/2.0;
*bit=(1.0+w)/2.0;
}
for (i=0;i<N;++i) {
it=x.begin()+i*m;
jt=v.begin();
for (j=0;j<m;++j,it+=2,++jt)
*jt=gen(*it,*(it+1));
vecteur u=*_fft(_eval(symbolic(wf,v),contextptr),contextptr)._VECTptr,r;
r.reserve(m);
for (j=0,ait=a.begin(),bit=b.begin();j<m;++j,++jt,++ait,++bit)
r.push_back(*ait*u[j]+*bit*conj(u[(m-j)%m],contextptr));
res.push_back(r);
}
return res;
}
vecteur istft(const matrice &y,GIAC_CONTEXT) {
int N=mrows(y),m=mcols(y),n=(N+1)*m,i,j;
vecteur x(n,0),a(m),b(m),c(m);
const_iterateur it,ut;
iterateur jt,ait,bit;
for (i=0,ait=a.begin(),bit=b.begin();i<m;++i,++ait,++bit) {
gen w=cst_i*exp(i*cst_i*(cst_two_pi/(2.0*m)),contextptr);
*ait=(1.0+w)/2.0;
*bit=(1.0-w)/2.0;
}
for (i=0,it=y.begin();i<N;++i,++it) {
const vecteur &r=*it->_VECTptr;
for (j=0,jt=c.begin(),ait=a.begin(),bit=b.begin();j<m;++j,++jt,++ait,++bit)
*jt=*ait*r[j]+*bit*conj(r[(m-j)%m],contextptr);
vecteur u=*_ifft(c,contextptr)._VECTptr;
for (j=0,ut=u.begin(),jt=x.begin()+i*m;j<m;++j,++ut) {
*(jt++)+=re(*ut,contextptr);
*(jt++)+=im(*ut,contextptr);
}
}
return x;
}
gen _stft(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
if (g.type!=_VECT)
return gentypeerr(contextptr);
if (g._VECTptr->empty())
return gendimerr(contextptr);
gen wsize=128,wf=at_hamming_window;
bool has_opts=g.subtype==_SEQ__VECT;
if (has_opts && g._VECTptr->size()>3)
return gentoomanyargs(gettext("Too many input arguments"));
if (has_opts && g._VECTptr->front().type!=_VECT)
return gentypeerr(contextptr);
int n=g._VECTptr->size()-1,m;
if (has_opts && n==2) {
wf=g._VECTptr->at(n--);
if (wf.type!=_FUNC)
return generrtype(gettext("Expected a window function"));
}
if (has_opts && n==1) {
wsize=g._VECTptr->at(n);
if (!wsize.is_integer() || wsize.val<1)
return generrtype(gettext("Expected a positive integer"));
int e=std::floor(mylog2(wsize.val)+0.5);
if ((1<<e)!=wsize.val)
return generr(gettext("Window size must be a power of 2"));
}
vecteur x=has_opts?*g._VECTptr->front()._VECTptr:*g._VECTptr;
if (x.empty())
return gendimerr(contextptr);
if (!is_numericv(x,num_mask_withfrac | num_mask_withint))
return gensizeerr(contextptr);
if (!is_zero__VECT(*im(x,contextptr)._VECTptr,contextptr)) {
print_warning(gettext("ignoring imaginary part of input"),contextptr);
x=*re(x,contextptr)._VECTptr;
}
n=x.size();
m=wsize.val;
if (n%m) x.resize((n/m+1)*m,0);
return stft(x,m,wf._FUNCptr,contextptr);
}
static const char _stft_s[]="stft";
static define_unary_function_eval (__stft,&_stft,_stft_s);
define_unary_function_ptr5(at_stft,alias_at_stft,&__stft,0,true);
gen _istft(const gen &g,GIAC_CONTEXT) {
if (g.type==_STRNG && g.subtype==-1) return g;
if (!ckmatrix(g))
return gentypeerr(contextptr);
const matrice &y=*g._VECTptr;
if (!is_numericm(y,num_mask_withfrac | num_mask_withint))
return gensizeerr(contextptr);
return istft(y,contextptr);
}
static const char _istft_s[]="istft";
static define_unary_function_eval (__istft,&_istft,_istft_s);
define_unary_function_ptr5(at_istft,alias_at_istft,&__istft,0,true);
//
// AUDIO CLIP CLASS IMPLEMENTATION
//
audio_clip::audio_clip(int depth,int rate,int nc,int len,GIAC_CONTEXT) {
if ((depth!=8 && depth!=16 && depth!=24) || len<1 || nc<1 || rate<1)
throw std::runtime_error(gettext("Invalid sound parameters"));
_bit_depth=depth;
_pow2=1<<_bit_depth;
_range=_pow2/2-1;
_nc=nc;
_len=len;
_size=len*nc*depth/8;
_sample_rate=rate;
_data=(char*)calloc(_size,sizeof(char));
if (_data==NULL)
throw std::runtime_error(gettext("Failed to allocate memory for wave data"));
ctx=contextptr;
_filename.clear();
_file_offset=0;
}
audio_clip::audio_clip(const audio_clip &other,int offset,int len) {
_size=0;
_data=NULL;
assign(other,offset,len);
}
audio_clip::audio_clip(const char *fname,int offset,int len,GIAC_CONTEXT) {
ctx=contextptr;
FILE *f=fopen(fname,"r");
if (f==NULL)
throw std::runtime_error(gettext("Failed to open file for reading"));
_size=0;
try {
read(f,offset,len,true);
_filename=fname;
} catch (const std::runtime_error &e) {
fclose(f);
if (_size>0)
free(_data);
throw e;
}
fclose(f);
}
audio_clip::audio_clip(const char *fname,double t1,double t2,GIAC_CONTEXT) {
ctx=contextptr;
FILE *f=fopen(fname,"r");
if (f==NULL)
throw std::runtime_error(gettext("Failed to open file for reading"));
_size=0;
int offset,len;
try {
read_header(f,_bit_depth,_sample_rate,_nc,_size);
offset=(int)std::floor(t1*_sample_rate);
len=(int)std::floor((t2-t1)*_sample_rate);
read(f,offset,len,false);
_filename=fname;
} catch (const std::runtime_error &e) {
fclose(f);
if (_size>0)
free(_data);
throw e;
}
fclose(f);
}
audio_clip *audio_clip::from_gen(const gen &g) {
if (g.type!=_USER)
return NULL;
return dynamic_cast<audio_clip*>(g._USERptr);
}
gen audio_clip::giac_constructor(GIAC_CONTEXT) const {
if (!_filename.empty())
return symbolic(at_readwav,makesequence(string2gen(_filename,false),_file_offset,_len));
vecteur args;
string data;
data.reserve(_size*2);
for (int i=0;i<_size;++i)
data.append(n2hexstr(_data[i]));
args.push_back(symb_equal(at_channels,_nc));
args.push_back(symb_equal(at_bit_depth,_bit_depth));
args.push_back(symb_equal(at_samplerate,_sample_rate));
args.push_back(symb_equal(at_channel_data,string2gen(data,false)));
return symbolic(at_createwav,gen(args,_SEQ__VECT));
}
void audio_clip::assign(const audio_clip &other,int offset,int len) {
_bit_depth=other.bit_depth();
_nc=other.channel_count();
if (offset>other.length()-len)
len=other.length()-offset;
_len=len;
_sample_rate=other.sample_rate();
_pow2=other._pow2;
_range=other._range;
if (other._filename.size()>0) {
_filename=other._filename;
_file_offset=other._file_offset+offset;
} else _filename.clear();
ctx=other.ctx;
int m=_nc*_bit_depth/8,sz=len*m;
if (_size!=sz) {
char *d=(char*)calloc(sz,sizeof(char));
if (d!=NULL) {
if (_data!=NULL) free(_data);
_data=d;
_size=sz;
} else throw std::runtime_error(gettext("Failed to allocate memory for wave data"));
}
memcpy(_data,other._data+offset*m,_size);
}
gen audio_clip::operator+(const gen &g) const {
audio_clip *other=from_gen(g);
if (other==NULL)
return generrtype(gettext("Expected an audio clip"));
if (_bit_depth!=other->bit_depth())
return generr(gettext("Audio clips must have the same bit depth"));
if (_sample_rate!=other->sample_rate())
return generr(gettext("Audio clips must have the same sample rate"));
if (_nc!=other->channel_count())
return generr(gettext("Audio clips must have the same number of channels"));
audio_clip ret(_bit_depth,_sample_rate,_nc,_len+other->length(),ctx);
memcpy(ret._data,this->_data,this->_size);
memcpy(ret._data+this->_size,other->_data,other->_size);
return ret;
}
string audio_clip::print(GIAC_CONTEXT) const {
char buf[1024];
sprintf(buf,gettext("a sound clip with %d samples at %d Hz (%d bit, %s)"),_len,_sample_rate,_bit_depth,(_nc==1?"mono":"stereo"));
return buf;
}
string audio_clip::texprint(GIAC_CONTEXT) const {
string ret="\\text{";
ret+=this->print(contextptr);
ret+"}";
return ret;
}
/* Return true iff G is audio clip with the same parameters and data as this. */
bool audio_clip::operator==(const gen &g) const {
audio_clip *other=from_gen(g);
if (other==NULL)
return false;