forked from matt-weinstein/adigator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
adigator.m
executable file
·1336 lines (1263 loc) · 53.2 KB
/
adigator.m
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
function [Outputs,varargout] = adigator(UserFunName,UserFunInputs,DerFileName,varargin)
% ADiGator Main Function: Called in order to initiate source transformation
% on a user's function file.
%
% ------------------------------ Usage ---------------------------------- %
% adigator(UserFunName,UserFunInputs,DerFileName)
% or
% adigator(UserFunName,UserFunInputs,DerFileName,Options)
%
% ------------------------ Input Information ---------------------------- %
% UserFunName: String name of the user function to be differentiated
%
% UserFunInputs: N x 1 cell array containing the inputs to the UserFun
% - any inputs (or cell array elements/structure fields)
% which have derivatives must be created using the
% adigatorCreateDerivInput function.
% i.e. if the first input is the variable of
% differentiation, then the first input must be created
% using adigatorCreateDerivInput prior to calling adigator.
% - any other numeric inputs should be defined as they will
% be when calling the derivative function. These will be
% assumed to have fixed sizes and zero locations, but the
% non-zero locations may change values. If the values are
% always fixed, then adigatorOptions may be used to change
% the handling of these auxiliary inputs.
% - auxiliary inputs may also be created using the
% adigatorCreateAuxInput function.
%
% DerFileName: String which derivative file is to be named.
%
% Options (optional): option structure generated by adigatorOptions
% function
%
% Copyright 2011-2014 Matthew J. Weinstein and Anil V. Rao
% Distributed under the GNU General Public License version 3.0
%
% Please report any bugs/suggestions to the forums at
% https://sourceforge.net/projects/adigator/
%
% See also adigatorCreateDerivInput, adigatorCreateAuxInput, adigatorOptions
% ADiGator 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.
%
% ADiGator 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 ADiGator in adigator/COPYING.txt.
% If not, see <http://www.gnu.org/licenses/>.
global ADIGATOR ADIGATORFORDATA ADIGATORDATA ADIGATORVARIABLESTORAGE
tstart = tic;
version = '1.4';
%% ~~~~~~~~~~~~~~~~~~~~~~~~~~ OPTIONS SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
opts = adigatorOptions();
if nargin == 4
optfields = fieldnames(varargin{1});
for Fcount = 1:length(optfields)
opts.(lower(optfields{Fcount})) = varargin{1}.(lower(optfields{Fcount}));
end
elseif nargin ~= 3
error('Invalid number of inputs')
end
ADIGATOR.OPTIONS.AUXDATA = opts.auxdata;
ADIGATOR.OPTIONS.ECHO = opts.echo;
ADIGATOR.OPTIONS.UNROLL = opts.unroll;
ADIGATOR.OPTIONS.COMMENTS = opts.comments;
ADIGATOR.OPTIONS.OVERWRITE = opts.overwrite;
ADIGATOR.OPTIONS.KEYBOARD = 0;
ADIGATOR.OPTIONS.PREALLOCATE = 0;
ADIGATOR.OPTIONS.MAXWHILEITER = opts.maxwhileiter;
ADIGATOR.OPTIONS.COMPLEX = opts.complex;
%% ~~~~~~~~~~~~~~~~~~~~~~~~~ FILE KEEPING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
CallingDir = cd;
if exist([CallingDir,filesep,DerFileName,'.m'],'file');
if ADIGATOR.OPTIONS.OVERWRITE
delete([CallingDir,filesep,DerFileName,'.m']);
rehash
else
error(['The file ',CallingDir,filesep,DerFileName,'.m already exists, ',...
'quitting transformation. To set manual overwrite of file use ',...
'''''adigatorOptions(''OVERWRITE'',1);''''. Alternatively, delete the ',...
'existing file and any associated .mat file.']);
end
end
if exist([CallingDir,filesep,DerFileName,'.mat'],'file')
if ADIGATOR.OPTIONS.OVERWRITE
delete([CallingDir,filesep,DerFileName,'.mat']);
else
error(['The file ',CallingDir,filesep,DerFileName,'.mat already exists, ',...
'quitting transformation. To set manual overwrite of file use ',...
'''''adigatorOptions(''OVERWRITE'',1);''''. Alternatively, delete the ',...
'existing file.']);
end
rehash
end
[~,adigatorTempDir] = filekeeping();
%% ~~~~~~~~~~~~~~~~~~ PARSE USERFUNINPUTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
if ~ischar(UserFunName)
error(['First input to adigator must be string name of function to be ',...
'differentiated']);
end
if ~iscell(UserFunInputs)
error(['Second input to adigator must be cell array of inputs to ',...
'the function described by first input string']);
end
if ~ischar(DerFileName)
error(['Third input to adigator must be string of desired name of ',...
'generated derivative file']);
end
UserFun = str2func(UserFunName);
NumUserFunInputs = numel(UserFunInputs);
if nargin(UserFun) ~= NumUserFunInputs
error('Invalid number of elements in UserFunInputs')
end
ADIGATOR.VARINFO = struct('COUNT',[],'NAMELOCS',[],'LASTOCC',[],...
'NAMES',[],'OVERMAP',[],'SAVE',[],'RETURN',[]);
ADIGATOR.NVAROFDIFF = 0;
ADIGATOR.VAROFDIFF = struct('name',[],'size',[],'usize',[]);
TestInputs = cell(size(UserFunInputs));
for Icount = 1:NumUserFunInputs
UserFunInputs{Icount} = ParseUserFunInputs(UserFunInputs{Icount},0);
end
TestEvalStr = cell(1,NumUserFunInputs);
for Icount = 1:NumUserFunInputs
[UserFunInputs{Icount},TestInputs{Icount}] = ...
ParseUserFunInputs(UserFunInputs{Icount},1);
TestEvalStr{Icount} = sprintf('TestInputs{%1.0f},',Icount);
end
NUMvod = ADIGATOR.NVAROFDIFF;
if ~NUMvod
error('No derivative inputs defined')
end
% Test users function file to make sure it works
TestEvalStr = cell2mat(TestEvalStr);
TestEvalStr = [UserFunName,'(',TestEvalStr(1:end-1),');'];
try
eval(TestEvalStr);
catch UserFunErr
warning('ADiGator:initialevalfail',...
'Error in initial test evaluation of user file on given input info');
rethrow(UserFunErr)
end
%% ~~~~~~~~~~~~~~~~~ GET FLOW CONTROL STRUCTURE ~~~~~~~~~~~~~~~~~~~~~~~~ %%
% See if there are any other called functions
depfunwarning = warning('query','MATLAB:DEPFUN:DeprecatedAPI');
warning('off','MATLAB:DEPFUN:DeprecatedAPI');
CalledFunctions = mydepfun(UserFunName);
warning(depfunwarning.state,'MATLAB:DEPFUN:DeprecatedAPI');
NUMcf = length(CalledFunctions);
if NUMcf > 1
CalledFunctions = [CalledFunctions{1}; unique(CalledFunctions(2:end))];
NUMcf = length(CalledFunctions);
end
FunctionInfo = struct('File',{},'Input',{},'Output',{},'VARINFO',...
{},'FORDATA',{},'DERNUMBER',{},'Iteration',{},'PreviousDerivData',{},...
'FunAsLoopFlag',{});
FunCount = 0;
DataCount = 0;
FunFlowInfo = cell(NUMcf,1);
for CFcount = 1:NUMcf
% --------------------Main Function or Called Function----------------- %
FunCount = FunCount+1;
DataCount = DataCount+1; % Need a datacount for the inputs of each function
if length(FunctionInfo) < FunCount
% Pre-Allocate FUNCITONINFO if needed
FunctionInfo(FunCount*2,1).DERNUMBER = [];
end
% -----Set Global FILE field-----
NameLoc = strfind(CalledFunctions{CFcount},filesep);
FILENAME = CalledFunctions{CFcount}(NameLoc(end)+1:end-2);
FID = fopen(CalledFunctions{CFcount},'r');
FunctionInfo(FunCount).File.Name = FILENAME;
FunctionInfo(FunCount).File.fid = FID;
FunctionInfo(FunCount).File.Path = CalledFunctions{CFcount};
% -----Parse the users function line of the file----
[OutNames,InNames,~,FunEvalLoc,EvalMajorLineCount] = parsefuncIO(FID,1,0);
% This is an actual function file so it better have a function line
if isempty(FunEvalLoc)
if CFcount == 1
error(['unable to find function line in :''',FILENAME,'''']);
else
error(['Called file, ''',FILENAME,''', appears to be a script ',...
'and not a function. Please either turn it into a function with',...
' distinct inputs/outputs or copy the code to the calling function.']);
end
end
FunctionInfo(FunCount).Input.Names = InNames;
FunctionInfo(FunCount).Output.Names = OutNames;
FunctionInfo(FunCount).Iteration.CallCount = 0;
FunctionInfo(FunCount).FunAsLoopFlag = 0;
% -----Check to see if this is a previously created Derivative File---- %
MajorLineCount = EvalMajorLineCount; fseek(FID,FunEvalLoc,-1);
fgets(FID); MajorLineCount = MajorLineCount+1;
BreakFlag = 0;
PrevDerFlag = 0;
PrevDerString = ['global ADiGator_',FILENAME];
while ~BreakFlag
FunLine = strtrim(fgets(FID));
MajorLineCount = MajorLineCount+1;
if strcmp(FunLine,PrevDerString)
% This is a previously created deriv file
PrevDerFlag = 1;
BreakFlag = 1;
elseif ~isempty(FunLine) && ~strcmp(FunLine(1),'%')
% Not a previously created deriv file
BreakFlag = 1;
end
end
if PrevDerFlag
% We don't want to read in all of the global stuff, will do this
% seperately. But, we do want to store information about the previous
% derivatives.
PreviousDerivData = load([FILENAME,'.mat']);
ParentPrevDerivData = PreviousDerivData.(FILENAME);
NumPrevDerivs = length(ParentPrevDerivData.Derivative);
FunctionInfo(FunCount).PreviousDerivData = ParentPrevDerivData;
PrevDerString = sprintf('ADiGator Start Derivative Computations');
% Last Line that we dont need is PrevDerString.
FunLine = strtrim(fgets(FID)); MajorLineCount = MajorLineCount+1;
while isempty(strfind(FunLine,PrevDerString))
% Get to the last line that we dont need to read.
FunEvalLoc = ftell(FID);
FunLine = strtrim(fgets(FID));
MajorLineCount = MajorLineCount+1;
end
EvalMajorLineCount = MajorLineCount;
FunctionInfo(FunCount).DERNUMBER = NumPrevDerivs+1;
else
FunctionInfo(FunCount).PreviousDerivData = [];
FunctionInfo(FunCount).DERNUMBER = 1;
end
% -----Get FlowInfo-----
FlowInfo = struct('Type','main',...
'StartLocation',[EvalMajorLineCount,1,1,FunEvalLoc],...
'EndLocation',[],'Children',[]);
FlowInfo.Children = struct('Type',cell(0),'StartLocation',cell(0),...
'EndLocation',cell(0),'Children',cell(0));
InnerCount = 0; MinorLineCount = 0;
MajorLineCount = EvalMajorLineCount-1;
FileLoc = FunEvalLoc;
EndFlag = 0;
while EndFlag == 0
[MajorLineCount,MinorLineCount,TempFlowInfo,FileLoc,InnerCount,DataCount,OffSet] =...
flowread(FID,MajorLineCount,MinorLineCount,FlowInfo.Children,FileLoc,InnerCount,DataCount);
if isempty(TempFlowInfo)
EndFlag = 1;
else
FlowInfo.Children = TempFlowInfo(1:InnerCount);
MajorLineCount = MajorLineCount - OffSet;
end
end
DataCount = DataCount+1; % Need another DataCount for the End of the File
FlowInfo.EndLocation = [MajorLineCount,MinorLineCount,DataCount,FileLoc];
FunFlowInfo{FunCount} = FlowInfo;
% -----------------------Sub-Functions--------------------------------- %
SubFlag = 1;
while SubFlag
% Parse the users sub-function line (if exists)
[OutNames,InNames,FunStr,FunEvalLoc,EvalMajorLineCount] = parsefuncIO(FID,MajorLineCount,FileLoc);
if ~isempty(FunEvalLoc)
% Found a sub-function
if strfind(FunStr,'ADiGator_LoadData()')
break
end
FunCount = FunCount+1;
DataCount = DataCount+1;
NameLoc1 = strfind(FunStr,'=');
NameLoc2 = strfind(FunStr,'(');
FILENAME = strtrim(FunStr(NameLoc1(1)+1:NameLoc2(1)-1));
FunctionInfo(FunCount).File.Name = FILENAME;
FunctionInfo(FunCount).File.fid = FID;
FunctionInfo(FunCount).File.Path = CalledFunctions{CFcount};
FunctionInfo(FunCount).Input.Names = InNames;
FunctionInfo(FunCount).Output.Names = OutNames;
FunctionInfo(FunCount).Iteration.CallCount = 0;
FunctionInfo(FunCount).FunAsLoopFlag = 0;
if PrevDerFlag
% Parent of this sub-function is a previously created derivative
% file, so this has to be too.
ChildDerivData = PreviousDerivData.(FILENAME);
NumPrevDerivs = length(ChildDerivData.Derivative);
FunctionInfo(FunCount).PreviousDerivData = ChildDerivData;
PrevDerString = sprintf('ADiGator Start Derivative Computations');
% Last Line that we dont need is PrevDerString.
fseek(FID,FunEvalLoc,-1); FunLine = strtrim(fgets(FID));
EvalMajorLineCount = EvalMajorLineCount+1;
while isempty(strfind(FunLine,PrevDerString));
FunEvalLoc = ftell(FID); FunLine = strtrim(fgets(FID));
EvalMajorLineCount = EvalMajorLineCount+1;
end
FunctionInfo(FunCount).DERNUMBER = NumPrevDerivs+1;
else
FunctionInfo(FunCount).DERNUMBER = 1;
FunctionInfo(FunCount).PreviousDerivData = [];
end
FlowInfo = struct('Type','main',...
'StartLocation',[EvalMajorLineCount,1,1,FunEvalLoc],...
'EndLocation',[],'Children',[]);
FlowInfo.Children = struct('Type',cell(0),'StartLocation',cell(0),...
'EndLocation',cell(0),'Children',cell(0));
InnerCount = 0; MinorLineCount = 0;
MajorLineCount = EvalMajorLineCount-1;
FileLoc = FunEvalLoc;
EndFlag = 0;
while EndFlag == 0
[MajorLineCount,MinorLineCount,TempFlowInfo,FileLoc,InnerCount,DataCount,OffSet] =...
flowread(FID,MajorLineCount,MinorLineCount,FlowInfo.Children,FileLoc,InnerCount,DataCount);
if isempty(TempFlowInfo)
EndFlag = 1;
else
FlowInfo.Children = TempFlowInfo(1:InnerCount);
MajorLineCount = MajorLineCount - OffSet;
end
end
DataCount = DataCount+1; % Need another DataCount for the End of the File
FlowInfo.EndLocation = [MajorLineCount,MinorLineCount,DataCount,FileLoc];
FunFlowInfo{FunCount} = FlowInfo;
else
% There are no more subfunctions
SubFlag = 0;
end
end
end
FunctionInfo = FunctionInfo(1:FunCount);
% -----Check and make sure that no two functions are named the same thing
% (either called functions or sub functions)-----
FunStrChecks = cell(FunCount,1);
for Fcount = 1:FunCount
CheckName = FunctionInfo(Fcount).File.Name;
for F2count = Fcount+1:FunCount
if strcmp(CheckName,FunctionInfo(F2count).File.Name)
error(['Function name ''',CheckName,''' appears to exist as a ',...
'function or sub-function in two separate places. This is not ',...
'allowed.'])
end
end
FunStrChecks{Fcount} = ['\W',CheckName,'('];
end
%% ~~~~~~~~~~~~~~~ DETERMINE WHAT NEEDS DERIV TAKEN ~~~~~~~~~~~~~~~~~~~~ %%
ADIGATOR.DERIVCHECKS = struct('STRINGS',cell(FunCount,1),'NUM',cell(FunCount,1));
for Fcount = 1:FunCount
[DerivCheckCell, LastDerivNum,DerNumber] =...
getderivchecks(FunctionInfo(Fcount).PreviousDerivData);
FunctionInfo(Fcount).DERNUMBER = DerNumber;
ADIGATOR.DERIVCHECKS(Fcount).STRINGS = DerivCheckCell;
ADIGATOR.DERIVCHECKS(Fcount).NUM = LastDerivNum;
end
%% ~~~~~~~~~~~~~~ CREATE INTERMEDIATE PROGRAM FILES ~~~~~~~~~~~~~~~~~~~~ %%
for Fcount = 1:FunCount
ADIGATOR.SVACOUNT = 0; ADIGATOR.SVRCOUNT = 0;
DerNumber = FunctionInfo(Fcount).DERNUMBER;
TempFunStr = sprintf('adigatortempfunc%1.0d',Fcount);
Tfid = fopen([adigatorTempDir,filesep,TempFunStr,'.m'],'w+');
% Function Header
fprintf(Tfid,['function [adigatorFunInfo, adigatorOutputs] = ',...
TempFunStr,'(adigatorFunInfo,adigatorInputs)\n']);
% Call to adigatorFunctionInitialize
if DerNumber == 1
fprintf(Tfid,['[flag, adigatorFunInfo, adigatorInputs] = ',...
'adigatorFunctionInitialize(%1.0d,adigatorFunInfo,adigatorInputs);\n'],Fcount);
else
fprintf(Tfid,['[flag, adigatorFunInfo, adigatorInputs, adigatorDerivData] = ',...
'adigatorFunctionInitialize(%1.0d,adigatorFunInfo,adigatorInputs);\n'],Fcount);
end
fprintf(Tfid,'if flag; adigatorOutputs = adigatorInputs; return; end;\n');
% Print out Previous Derivative Data References
for Dcount = 1:DerNumber-1
%fprintf(Tfid,['Gator%1.0dIndices = ',...
% 'adigatorDerivData.Gator%1.0dIndices;\n'],Dcount,Dcount);
fprintf(Tfid,['Gator%1.0dData = ',...
'adigatorDerivData.Gator%1.0dData;\n'],Dcount,Dcount);
end
NumOutputs = length(FunctionInfo(Fcount).Output.Names);
NumInputs = length(FunctionInfo(Fcount).Input.Names);
% Assign adigatorInputs to proper names
for Icount = 1:NumInputs
fprintf(Tfid,[FunctionInfo(Fcount).Input.Names{Icount},...
' = adigatorInputs{%1.0d};\n'],Icount);
end
fprintf(Tfid,'nargin = %1.0d; nargout = %1.0d;',NumInputs,NumOutputs);
if Fcount > 1 && ~ADIGATOR.OPTIONS.UNROLL
ForCount = 1;
else
ForCount = 0;
end
% Print the body of the file with adigatorPrintTempFiles
[ForCount,IfCount] = adigatorPrintTempFiles(FunctionInfo(Fcount).File.fid,Tfid,...
FunFlowInfo{Fcount},DerNumber,ForCount,FunStrChecks);
% Assign outputs to adigatorOutputs
OutputStr = cell(1,NumOutputs);
for Ocount = 1:NumOutputs
OutputStr{Ocount} = [FunctionInfo(Fcount).Output.Names{Ocount},';'];
end
OutputStr = cell2mat(OutputStr);
fprintf(Tfid,['adigatorOutputs = {',OutputStr(1:end-1),'};\n']);
% Call to adigatorFunctionEnd
fprintf(Tfid,['[adigatorFunInfo, adigatorOutputs] = ',...
'adigatorFunctionEnd(%1.0f,adigatorFunInfo,adigatorOutputs);\n'],Fcount);
FunctionInfo(Fcount).FORDATA = struct('START',cell(0,1),'END',[],...
'COUNTNAME',[],'PREVOVERMAP',[],'COUNT',[],'FOR',[],'SUBSREF',...
[],'SUBSASGN',[],'SPARSE',[],'NONZEROS',[],'HORZCAT',[],'VERTCAT',...
[],'TRANSPOSE',[],'REPMAT',[],'RESHAPE',[],'SIZE',[],'OTHER',[],...
'STRUCTREF',[],'STRUCTASGN',[],'CONTRESTORE',[],'PARENTLOC',[],...
'WHILEFLAG',[]);
if ForCount
FunctionInfo(Fcount).FORDATA(ForCount,1).COUNT = [];
end
FunctionInfo(Fcount).IFDATA = struct('ELSEFLAG',cell(0,1),'BROS',[]);
if IfCount
FunctionInfo(Fcount).IFDATA(IfCount,1).BROS(1).START = [];
end
FunctionInfo(Fcount).STRUCASGN = struct('dummy',...
cell(1,ADIGATOR.SVACOUNT),'inds',[]);
fclose(Tfid);
end
rehash
%% ~~~~~~~~~~~~~~~~~~~~~~ ECHO PRE-PRINTING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
if ADIGATOR.OPTIONS.ECHO
if NUMvod > 1
disp(['Transforming User Function: ''',UserFunName,'''']);
DispStr = cell(1,NUMvod);
DispStr{1} = sprintf([' Taking Derivatives wrt: ''',...
ADIGATOR.VAROFDIFF(1).name,', ']);
for Vcount = 2:NUMvod-1
DispStr{Vcount} = sprintf([' ''',...
ADIGATOR.VAROFDIFF(Vcount).name,', ']);
end
DispStr{NUMvod} = sprintf(['''',...
ADIGATOR.VAROFDIFF(NUMvod).name,'...']);
disp(cell2mat(DispStr));
else
fprintf('Call to <strong>adigator</strong>:\n');
fprintf(['Transforming user function: ''',UserFunName,'''\n',...
' taking derivatives wrt: ''',ADIGATOR.VAROFDIFF(1).name,...
'''...\n']);
end
end
%% ~~~~~~~~~~~~~~~~~~~~ SET GLOBAL ENVIRONMENT ~~~~~~~~~~~~~~~~~~~~~~~~~ %%
ADIGATOR.DERNUMBER = 0;
ADIGATOR.VARINFO.COUNT = 0;
ADIGATOR.FORINFO.FLAG = 0;
ADIGATOR.FILE.FUNID = 0;
ADIGATOR.FILE.CALLFLAG = 0;
ADIGATOR.FILE.PARENTID = [];
ADIGATORFORDATA = [];
ADIGATOR.SUBSINDEXFLAG = 0;
ADIGATOR.CELLEVALFLAG = 0;
ADIGATORDATA.FILENAME = DerFileName;
Dfid = fopen([CallingDir,filesep,DerFileName,'.m'],'w+');
ADIGATOR.PRINT.FILENAME = DerFileName;
ADIGATOR.PRINT.FID = Dfid;
ADIGATOR.PRINT.FLAG = 0;
ADIGATOR.PRINT.INDENT = [];
% Print the derivative function header
fprintf(Dfid,['%% This code was generated using ADiGator version ',version,'\n']);
fprintf(Dfid,['%% ',char(169),'2010-2014 Matthew J. Weinstein and Anil V. Rao\n']);
fprintf(Dfid,'%% ADiGator may be obtained at https://sourceforge.net/projects/adigator/ \n');
fprintf(Dfid,'%% Contact: [email protected]\n');
fprintf(Dfid,'%% Bugs/suggestions may be reported to the sourceforge forums\n');
fprintf(Dfid,'%% DISCLAIMER\n');
fprintf(Dfid,'%% ADiGator is a general-purpose software distributed under the GNU General\n');
fprintf(Dfid,'%% Public License version 3.0. While the software is distributed with the\n');
fprintf(Dfid,'%% hope that it will be useful, both the software and generated code are\n');
fprintf(Dfid,'%% provided ''AS IS'' with NO WARRANTIES OF ANY KIND and no merchantability\n');
fprintf(Dfid,'%% or fitness for any purpose or application.\n\n');
%% ~~~~~~~~~ PREALLOCATION RUN (if Struc/Cell Assignments) ~~~~~~~~~~~~~ %%
if ADIGATOR.OPTIONS.PREALLOCATE
ADIGATOR.RUNFLAG = 0;
FunctionInfo = adigatortempfunc1(FunctionInfo,TestInputs);
ADIGATOR.OPTIONS.PREALLOCATE = 0;
end
%% ~~~~~~~~~~~~~~~~~~~ PERFORM EMPTY TRACE RUN ~~~~~~~~~~~~~~~~~~~~~~~~~ %%
ADIGATOR.RUNFLAG = 0;
FunctionInfo = adigatortempfunc1(FunctionInfo,UserFunInputs);
RollFlag = 0;
for Fcount = 1:FunCount
if FunctionInfo(Fcount).Iteration.CallCount > 0
FunctionInfo(Fcount).Iteration.CallCount = 0;
FORDATA = FunctionInfo(Fcount).FORDATA;
IFDATA = FunctionInfo(Fcount).IFDATA;
VARINFO = FunctionInfo(Fcount).VARINFO;
BREAKLOCS = FunctionInfo(Fcount).BREAKLOCS;
CONTLOCS = FunctionInfo(Fcount).CONTLOCS;
ERRORLOCS = FunctionInfo(Fcount).ERRORLOCS;
FunAsLoopFlag = FunctionInfo(Fcount).FunAsLoopFlag;
[FORDATA,IFDATA,VARINFO,VARSTORAGE] = adigatorAssignOvermapScheme(Fcount,...
FunAsLoopFlag,FORDATA,IFDATA,VARINFO,BREAKLOCS,CONTLOCS,ERRORLOCS,ADIGATOR.OPTIONS.UNROLL);
FunctionInfo(Fcount).FORDATA = FORDATA;
FunctionInfo(Fcount).IFDATA = IFDATA;
FunctionInfo(Fcount).VARINFO = VARINFO;
FunctionInfo(Fcount).VARSTORAGE = VARSTORAGE;
if ~isempty(VARINFO.OVERMAP.FOR) || ~isempty(VARINFO.OVERMAP.IF)
RollFlag = 1;
end
end
end
UserUnrollFlag = ADIGATOR.OPTIONS.UNROLL;
if ~RollFlag
ADIGATOR.OPTIONS.UNROLL = 1;
end
%% ~~~~~~~~~~~~~~~~~~ OVERMAPPING RUN (IF NEEDED) ~~~~~~~~~~~~~~~~~~~~~~ %%
if ~ADIGATOR.OPTIONS.UNROLL
ADIGATOR.RUNFLAG = 1;
ADIGATOR.EMPTYFLAG = 0;
ADIGATOR.FILE.FUNID = 0;
ADIGATOR.FILE.PARENTID = [];
FunctionInfo = adigatortempfunc1(FunctionInfo,UserFunInputs);
% ------------------- Anaylyze any FOR Data --------------------------- %
dummyVar = cada([],[],[]);
ADIGATOR.PRINT.FLAG = 1;
IterationDependency = zeros(FunCount,1);
for Fcount = 1:FunCount
ADIGATORFORDATA = FunctionInfo(Fcount).FORDATA;
ADIGATORVARIABLESTORAGE = FunctionInfo(Fcount).VARSTORAGE;
ADIGATORDATA.INDEXCOUNT = 0;
ADIGATORDATA.INDEXCOUNT = 0; ADIGATORDATA.DATACOUNT = 0;
%ADIGATORDATA.INDICES = [];
%ADIGATORDATA.INDICES.Index1 = [];
ADIGATORDATA.DATA = [];
ADIGATORDATA.DATA.Data1 = [];
ADIGATORDATA.DATA.Index1 = [];
ADIGATOR.DERNUMBER = FunctionInfo(Fcount).DERNUMBER;
ADIGATOR.VARINFO = FunctionInfo(Fcount).VARINFO;
ADIGATOR.FUNDEP = 0;
for ForCount = 1:length(ADIGATORFORDATA)
if ~ADIGATORFORDATA(ForCount).PARENTLOC
adigatorAnalyzeForData(ForCount,dummyVar);
end
end
if FunctionInfo(Fcount).FunAsLoopFlag && ADIGATOR.FUNDEP
IterationDependency(Fcount) = 1;
end
FunctionInfo(Fcount).FORDATA = ADIGATORFORDATA;
FunctionInfo(Fcount).DATA = ADIGATORDATA;
end
% Second Pass - For Functions which think they are Independent
% - Check and see if they call any other functions which are dependent.
% - If they do, then they have to be Dependent.
IterationDependency2 = zeros(FunCount,1);
while ~isequal(IterationDependency,IterationDependency2)
% Need to run this in a while loop until nothing changes - if a function
% is indep. and calls another which is indep. which calls another which
% is dep. then the first needs to be made dependent too.
IterationDependency2 = IterationDependency;
for Fcount = 2:FunCount
if IterationDependency(Fcount)
% This Function is Dependent - Make All Functions which call this be
% dependent as well.
CallerFuncs = FunctionInfo(Fcount).Iteration.CallerID(1,:);
IterationDependency(CallerFuncs) = 1;
end
end
end
% Third Pass - Assign Dependencies
for Fcount = 1:FunCount
if IterationDependency(Fcount) &&...
FunctionInfo(Fcount).Iteration.IterCount > 1
if FunctionInfo(Fcount).DERNUMBER > 1
% Second or Higher Derivative - Can check and see if the previous run
% was dependent and we can use the same funcount or not.
LastCountStr = FunctionInfo(Fcount).Input.Names{end};
if length(LastCountStr) > 12 && strcmp(LastCountStr(1:4),'cada')...
&& strcmp(LastCountStr(end-7:end),'funcount')
% Already have a funcount coming in to the function
InCounts = FunctionInfo(Fcount).Input.StrucVars(end,:);
SameFlag = 1;
for Icount = 1:length(InCounts)
if numel(InCounts{Icount}.func.value) ~= 1 ||...
InCounts{Icount}.func.value ~= Icount
SameFlag = 0; break
end
end
if SameFlag
FunctionInfo(Fcount).Iteration.DepFlag = [1 0];
else
FunctionInfo(Fcount).Iteration.DepFlag = [1 1];
end
else
FunctionInfo(Fcount).Iteration.DepFlag = 1;
end
else
FunctionInfo(Fcount).Iteration.DepFlag = 1;
end
else
FunctionInfo(Fcount).Iteration.DepFlag = 0;
end
end
else
for Fcount = 1:FunCount
ADIGATORDATA.INDEXCOUNT = 0; ADIGATORDATA.DATACOUNT = 0;
ADIGATORDATA.DATA = [];
ADIGATORDATA.DATA.Index1 = []; ADIGATORDATA.DATA.Data1 = [];
FunctionInfo(Fcount).DATA = ADIGATORDATA;
FunctionInfo(Fcount).Iteration.DepFlag = 0;
end
end
%% ~~~~~~~~~~~~~~~~~~~~~~~~~~ PRINTING RUN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
if ADIGATOR.OPTIONS.ECHO
disp(['Printing derivatives to file ''',DerFileName,'''']);
end
ADIGATOR.RUNFLAG = 2;
ADIGATOR.FILE.FUNID = 0;
ADIGATOR.FILE.PARENTID = [];
ADIGATOR.PRINT.FLAG = 1;
ADIGATOR.EMPTYFLAG = 0;
% Call Main Function
FunctionInfo(1).Iteration.CallCount = 0;
[FunctionInfo, Outputs] = adigatortempfunc1(FunctionInfo,UserFunInputs);
if ~ADIGATOR.OPTIONS.UNROLL
FunctionInfo(1).Iteration.CallCount = 1;
% Call Sub-Functions
for Fcount = 2:FunCount
if FunctionInfo(Fcount).Iteration.CallCount == 0
% Function which never gets called, just skip it.
continue
end
% Need to get Overmapped Inputs
FunctionInfo(Fcount).Iteration.CallCount = 0;
if FunctionInfo(Fcount).FunAsLoopFlag
OverInputs = cell(size(FunctionInfo(Fcount).Input.StrucNames));
for Ocount = 1:length(OverInputs)
OverLoc = FunctionInfo(Fcount).VARINFO.OVERMAP.FOR(Ocount,1);
OverInputs{Ocount} = FunctionInfo(Fcount).VARSTORAGE.OVERMAP{OverLoc};
end
OverInputs = cadaGetOverVars(Fcount,FunctionInfo,OverInputs);
else
OverInputs = FunctionInfo(Fcount).Input.StrucVars;
OverInputs = cadaGetOverVars(Fcount,FunctionInfo,OverInputs);
end
ADIGATOR.EMPTYFLAG = 0;
FuncStr = sprintf('adigatortempfunc%1.0d',Fcount);
FuncCall = str2func(FuncStr);
FunctionInfo = feval(FuncCall,FunctionInfo,OverInputs);
FunctionInfo(Fcount).Iteration.CallCount = 1;
end
end
if ADIGATOR.OPTIONS.UNROLL
for Fcount = 2:FunCount
tempfilename = sprintf('adigatortempsubfunc%1.0f.m',Fcount);
if exist(tempfilename,'file')
tfid = FunctionInfo(Fcount).TempFID;
frewind(tfid);
subfuncc = fread(tfid,1024*1024);
while ~isempty(subfuncc)
fwrite(Dfid,subfuncc,'uchar');
subfuncc = fread(tfid,1024*1024);
end
fclose(tfid);
delete(tempfilename);
end
end
end
fprintf(Dfid,'\n\nfunction ADiGator_LoadData()\n');
fprintf(Dfid,['global ADiGator_',ADIGATOR.PRINT.FILENAME,'\n']);
fprintf(Dfid,['ADiGator_',ADIGATOR.PRINT.FILENAME,' = load(''',...
ADIGATOR.PRINT.FILENAME,'.mat'');\n']);
fprintf(Dfid,'return\nend');
eval(['global ADiGator_',ADIGATOR.PRINT.FILENAME]);
eval(['ADiGator_',ADIGATOR.PRINT.FILENAME,' = load(''',...
ADIGATOR.PRINT.FILENAME,'.mat'');']);
fclose('all');
if ADIGATOR.OPTIONS.ECHO
display(['Successfully transformed user function ''',UserFunName,...
''' to derivative function ''',DerFileName,'''']);
gentime = toc(tstart);
display(['Total file generation time: ',num2str(gentime)]);
end
ADIGATOR.OPTIONS.UNROLL = UserUnrollFlag;
if nargout == 2
varargout{1} = FunctionInfo(1);
end
rmpath(adigatorTempDir);
[sflag,msg] = rmdir(adigatorTempDir,'s');
if ~sflag
warning('Could not remove old temp directory -- message produced: %s',msg);
end
end
%% ~~~~~~~~~~~~~~~~~~~~~~~~~~ FILEKEEPING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
function [SoftwareLocation,adigatorTempDir] = filekeeping()
SoftwareLocation = which('adigator');
SoftwareLocation = SoftwareLocation(1:end-11);
% Delete any previously created dummy files
adigatorTempDir = [SoftwareLocation,filesep,'adigatorTempDir',filesep];
if exist(adigatorTempDir,'dir')
P = path;
if ~isempty(strfind(P,[adigatorTempDir(1:end-1),':']))
rmpath(adigatorTempDir);
end
[sflag,msg] = rmdir(adigatorTempDir,'s');
if ~sflag
warning('Could not remove old temp directory -- message produced: %s',msg);
end
end
[sflag,msg] = mkdir(adigatorTempDir);
if ~sflag
error('Could not create temp directory -- message produced: %s',msg);
end
addpath(adigatorTempDir);
rehash
end
%% ~~~~~~~~~~~~~~~~~~~~~~~~~~ INPUT PARSE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %%
function [x, xt] = ParseUserFunInputs(x,changeflag)
global ADIGATOR
nvod = ADIGATOR.NVAROFDIFF;
xt = x;
if isa(x,'adigatorInput') || isa(x,'cada')
if ~changeflag
for Vcount = 1:length(x.deriv)
vodname = x.deriv(Vcount).vodname;
vodsize = x.deriv(Vcount).vodsize;
matchflag = 0;
for V2count = 1:ADIGATOR.NVAROFDIFF
if strcmp(ADIGATOR.VAROFDIFF(V2count).name,vodname)
matchflag = 1;
if ~isequal(ADIGATOR.VAROFDIFF(V2count).size,vodsize)
error(['multiple inputs have derivatives wrt ''',vodname,...
''', where the size of ''',vodname,...
''' has been defined differently for two or more of the inputs'])
end
end
end
if ~matchflag
nvod = nvod+1;
ADIGATOR.NVAROFDIFF = nvod;
ADIGATOR.VAROFDIFF(nvod).name = vodname;
ADIGATOR.VAROFDIFF(nvod).size = vodsize;
if any(isinf(vodsize))
ADIGATOR.VAROFDIFF(nvod).usize = vodsize(~isinf(vodsize));
else
ADIGATOR.VAROFDIFF(nvod).usize = prod(vodsize);
end
end
end
else
deriv2 = struct('name',cell(nvod,1),'nzlocs',cell(nvod,1));
for Vcount = 1:length(x.deriv)
vodname = x.deriv(Vcount).vodname;
nzlocs = x.deriv(Vcount).nzlocs;
for V2count = 1:nvod
if strcmp(vodname,ADIGATOR.VAROFDIFF(V2count).name)
deriv2(V2count).nzlocs = nzlocs;
break
end
end
end
x = cada(1,x.func,deriv2);
xsize = x.func.size;
xsize(isinf(xsize)) = 10;
xt = rand(xsize);
end
elseif iscell(x)
cellsize = numel(x);
for Ccount = 1:cellsize
[x{Ccount}, xt{Ccount}] = ParseUserFunInputs(x{Ccount},changeflag);
end
elseif isstruct(x)
strucnames = fieldnames(x);
strucsize = numel(x);
for Scount = 1:strucsize
for S2count = 1:length(strucnames)
[x(Scount).(strucnames{S2count}), xt(Scount).(strucnames{S2count})]...
= ParseUserFunInputs(x(Scount).(strucnames{S2count}),changeflag);
end
end
end
end
%% ~~~~~~~~~~~~~~~~~~~~~~ LOOK FOR CALLED FUNCTIONS ~~~~~~~~~~~~~~~~~~~~ %%
function CalledFunctions = mydepfun(UserFunName)
%--------------------------------------------------------------------------%
% BEGIN: Code Added by Anil V. Rao. 15 October 2015. %
%--------------------------------------------------------------------------%
% Mathworks has removed the function DEPFUN from R2015b (version 8.6) %
% and has replaced it with MATLAB.CODETOOLS.REQUIREDFILESANDPRODUCTS. %
% As a result, it is necessary to check the version of MATLAB being used %
% to ensure that function dependencies are identified correctly. %
% The block of code below checks the MATLAB version and calls the function %
% DEPFUN if the version is R2015a or earlier, and calls the function %
% MATLAB.CODETOOLS.REQUIREDFILESANDPRODUCTS for R2015b and beyond.
%
%mjw - used verLassThan check for version number, also, new function
%already has recursion built in so the recursive nature is not necessary.
% - keeping the old code due to fact that new code is extremely slow.
%
% mjw - changed this to look at all cada methods and throw out any
% functions that have been overloaded.
%--------------------------------------------------------------------------%
cadaMethods = methods(cada(0,struct(),struct()));
cadaMethods{end+1} = 'rmfield';
if verLessThan('matlab','8.6')
% Original Code in ADIGATOR.M prior to introduction of new code
% consists of only the ONE line below.
CalledFunctions = depfun(UserFunName,'-quiet','-toponly');
CFtotal = length(CalledFunctions);
OtherFuncs = cell(CFtotal,1);
for CFcount = 2:CFtotal
fileloc = strfind(CalledFunctions{CFcount},filesep);
if isempty(fileloc); fileloc=0; end;
filename = CalledFunctions{CFcount}(fileloc(end)+1:end-2);
if any(strcmp(filename,cadaMethods))
CalledFunctions{CFcount} = [];
CFtotal = CFtotal-1;
else
OtherFuncs{CFcount} = mydepfun(CalledFunctions{CFcount});
CFtotal = CFtotal+length(OtherFuncs{CFcount});
end
end
CalledFunctions = CalledFunctions(~cellfun('isempty',CalledFunctions));
if length(CalledFunctions) < CFtotal
CFcount2 = length(CalledFunctions);
CalledFunctions{CFtotal,1} = [];
for CFcount = 1:length(OtherFuncs)
OtherFun = OtherFuncs{CFcount};
OFlength = length(OtherFun);
CalledFunctions(CFcount2+1:CFcount2+OFlength) = OtherFun;
CFcount2 = CFcount2+OFlength;
end
end
else
%----------------------------------------------------------------------------%
% The block of code below works as follows. First, the MATLAB function %
% MATLAB.CODETOOLS.REQUIREDFILESANDPRODUCTS is called and returns a cell %
% array CalledFunctions which contains the dependencies of the function %
% UserFunName. Note that the dependencies found in CalledFunctions include %
% UserFunName itself. Next, because the cell array CalledFunctions is a row %
% array in R2015b and beyond (while in R2015a and prior CalledFunctions was %
% a column vector), CalledFunctions must be transposed to give a cell array %
% that is oriented as a column. Third, prior to R2015b, CalledFunctions was %
% ordered such that its FIRST entry was the full path to UserFunName. As of %
% R2015b and beyond, however, UserFunName is NOT the first entry in the cell %
% array CalledFunctions. Because ADIGATOR assumes that CalledFunctions is %
% ordered such that CalledFunctions{1} = $full-path/UserFunName, a swap must %
% be performed to place UserFunName in CalledFunctions{1}. %
%----------------------------------------------------------------------------%
[CalledFunctions,~] = matlab.codetools.requiredFilesAndProducts(UserFunName);
CalledFunctions = CalledFunctions(:);
for kk = 1:length(CalledFunctions)
if(strcmp(filesep,'\'))
indexOfString = regexp(CalledFunctions{kk},...
[filesep,filesep,UserFunName,'.m$'],'once');
else
indexOfString = regexp(CalledFunctions{kk},...
[filesep,UserFunName,'.m$'],'once');
end
%indexOfString = strfind(CalledFunctions{kk},[filesep,UserFunName,'.m']);
if ~isempty(indexOfString)
thisIsIt = kk;
break
end
end
CFswap = CalledFunctions{thisIsIt};
CalledFunctions{thisIsIt} = CalledFunctions{1};
CalledFunctions{1} = CFswap;
% The new format is already recursive - just check through and remove any
% adigatorEvalInterp2pp/adigatorGenInterp2pp files
for CFcount = 2:length(CalledFunctions)
fileloc = strfind(CalledFunctions{CFcount},filesep);
if isempty(fileloc); fileloc=0; end;
% MJW Fix for 2016b including .mat files in CalledFunctions
dotLoc = strfind(CalledFunctions{CFcount},'.');
extName = CalledFunctions{CFcount}(dotLoc(end)+1:end);
if ~strcmp(extName,'m')
CalledFunctions{CFcount} = [];
continue
end
filename = CalledFunctions{CFcount}(fileloc(end)+1:end-2);
if any(strcmp(filename,cadaMethods))
CalledFunctions{CFcount} = [];
end
end
CalledFunctions = CalledFunctions(~cellfun('isempty',CalledFunctions));
end
%--------------------------------------------------------------------------%
% END: Code Added by Anil V. Rao. 15 October 2015. %
%--------------------------------------------------------------------------%
% [CalledFunctions,~] = matlab.codetools.requiredFilesAndProducts(UserFunName,'toponly');
end
%% ~~~~~~~~~~~~~~~~~~~~~~ PARSE FUNCTION INPUT/OUTPUT ~~~~~~~~~~~~~~~~~~ %%
function [OutNames,InNames,Fstr, FileLoc,MajorLineCount] = parsefuncIO(fid,MajorLineCount,FileLoc)
% ---------------Parse Function Input String------------------------------%
fseek(fid,FileLoc,-1);
Fstr = fgets(fid);
if isnumeric(Fstr)
OutNames = []; InNames = []; Fstr = []; FileLoc = []; MajorLineCount = [];
return
end
Fstr = strtrim(Fstr);
while length(Fstr) < 8 || strcmp(Fstr(1:8),'function') == 0 % -- get to function line --
FileLoc = ftell(fid);
Fstr = fgets(fid);
if isnumeric(Fstr)
OutNames = []; InNames = []; Fstr = []; FileLoc = []; MajorLineCount = [];
return
end
Fstr = strtrim(Fstr);
MajorLineCount = MajorLineCount+1;
end
while strcmp(Fstr(end-2:end),'...');
Fstr = [Fstr(1:end-3),strtrim(fgets(fid))];
end
% -- find outputs --
outloc1 = strfind(Fstr,'[');
outloc2 = strfind(Fstr,']');
if isempty(outloc1)
outloc2 = strfind(Fstr,'=');
if isempty(outloc2)
NumOutVars = 0;
else
OutNames = cell(1,1);
OutNames{1} = strtrim(Fstr(9:outloc2-1));
NumOutVars = 1;
end
else
outstr = strtrim(Fstr(outloc1+1:outloc2-1));
SpaceLocs = isspace(outstr);
CommaLocs = strfind(outstr,',');
SpaceLocs(CommaLocs) = true;
SpaceLocs1 = 1:length(outstr);
SpaceLocs = SpaceLocs1(SpaceLocs);
if isempty(SpaceLocs)
OutNames = cell(1);
OutNames{1} = outstr;
NumOutVars = 1;
else
% First
VarLocs = zeros(length(SpaceLocs)+1,2);
VarLocs(1,1) = 1; VarLocs(1,2) = SpaceLocs(1)-1;
NumOutVars = 1;
% Middle
for Scount = 1:length(SpaceLocs)-1
% Looking for the start of a variable.
if SpaceLocs(Scount)+1 ~= SpaceLocs(Scount+1)
NumOutVars = NumOutVars+1;
VarLocs(NumOutVars,1) = SpaceLocs(Scount)+1;
VarLocs(NumOutVars,2) = SpaceLocs(Scount+1)-1;
end
end
% Last
NumOutVars = NumOutVars+1;
VarLocs(NumOutVars,1) = SpaceLocs(end)+1;