File: 2A-RegressionModelling.R

package info (click to toggle)
fmultivar 240.10068-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,492 kB
  • ctags: 272
  • sloc: fortran: 1,128; ansic: 764; sh: 22; makefile: 1
file content (1748 lines) | stat: -rw-r--r-- 56,534 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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 Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

# Copyrights (C)
# for this R-port: 
#   1999 - 2004, Diethelm Wuertz, GPL
#   Diethelm Wuertz <wuertz@itp.phys.ethz.ch>
#   info@rmetrics.org
#   www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
#   see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
#   see Rmetrics's copyright file


################################################################################
# FUNCTION:             REGRESSION MODELLING DESCRIPTION:
#  'fREG'                S4 Class Representation
#  regSim                Returns a regression example data set
#  regFit                Wrapper Function for Regression Models
#  gregFit                Wrapper Function for Generalized Regression Models
#  .lmFit                 Linear Regression Model
#  .rlmFit                Robust Linear Regression Model
#  .glmFit                Generalized Linear Model
#  .gamFit                Generalized Additive Model
#  .pprFit                Projection Pursuit Regression Model
#  .marsFit               Multivariate Adaptive Regression Spline Model
#  .polymarsFit           Polytochomous MARS Model
#  .nnetFit               Feedforward Neural Network Model
# S3-METHODS:           DESCRIPTION:
#  print.fREG            Prints results from a regression model fit     
#  plot.fREG             Plots fit and diagnostics for a regression model
#  .plot.lm               Linear Regression Model internal plot        
#  .plot.rlm              Robust Linear Regression Model internal plot
#  .plot.glm              Generalized Linear Model internal plot
#  .plot.gam              Generalized Additive Model internal plot
#  .plot.ppr              Projection Pursuit Regression Model internal plot
#  .plot.mars             Multivariate Adaptive Regression Spline Model plot
#  .plot.polymars         Polytochomous MARS Model internal plot
#  .plot.nnet             Feedforward Neural Network Model internal plot
#  summary               Summarizes fit and diagnostics for a regression model
# S3-METHODS:           DESCRIPTION:
#  predict.fREG          Predicts values from a fitted regression model
#  coefficients.fREG     Returns coefficients from a fitted regression model
#  fitted.fREG           Returns fitted values from a fitted regression model
#  residulals.fREG       Returns residuals from a fitted regression model
#  vcov.fREG             Returns variance-covariance matrix from a fitted model
################################################################################


################################################################################
# BUILTIN:              FROM MDA - MARS DESCRIPTION:
#  .mars                 Internal Function
#  .mars.formula         Internal Function
#  .mars.default         Internal Function
#  .predict.mars         Internal Function
#  .model.matrix.mars    Internal Function
################################################################################


################################################################################
# INTERFACE:            FROM POLSPLINE - POLYMARS DESCRIPTION:
#  .polymars
#  .polymars.formula     Formula Generator for Polytochomous MARS Model
#  .polymars.default     Internal Function
#  .predict.polymars     Internal Function
################################################################################


################################################################################
# FINMETRICS-LIKE:      OLS DESCRIPTION:
#  OLS                   Fit an OLS regression model - SPlus like Call
#  print.OLS             S3 Print method for an OLS regression model
#  plot.OLS              S3 Plot method for an OLS regression model
#  summary.OLS           S3 Summary method for an OLS regression model
################################################################################


################################################################################
# MODEL:        PACKAGE     print   plot   summary   print     predict
#                                    persp           summary
#   lm          stats       x       x      x         x         x
#   rlm         MASS
#   glm         stats       x       -      x         x         x
#   gam         mgcv        x       x      x         x         x
#   ppr         modreg      x       x      x         x         x
#   mars*       mda         -       -      -         -         x 
#   polymars*   polspline   -       xx     x         -         x
#   nnet        nnet        x       -      x         x         x
#
#   *BUILTIN
#    mda        Mixture and flexible discriminant analysis
#    polspline  Polynomial spline routines
#   *IMPORTANT NOTE:
#    Both packages r-cran-mda and r-cran-polspline are not available on the
#    Debian Server, therefore we made them accessible as Builtin functions
################################################################################


################################################################################
# BUILTIN - PACKAGE DESCRIPTION:
#  Package: mda
#  Version: 0.2-23
#  Author: S original by Trevor Hastie & Robert Tibshirani.  
#    R port by Friedrich Leisch, Kurt Hornik and Brian D. Ripley.
#  Maintainer: Kurt Hornik <Kurt.Hornik@R-project.org>
#  Description: Mixture and flexible discriminant analysis, multivariate
#    additive regression splines (MARS), BRUTO, ...
#  Title: Mixture and flexible discriminant analysis
#  Depends: class, R (>= 1.5.0)
#  License: GPL version 2
#  Packaged: Sat Jan 31 13:31:19 2004; hornik
################################################################################


################################################################################
# BUILTIN - PACKAGE DESCRIPTION:
#  Package: polspline
#  Version: 1.0.5
#  Date: 2004-04-22
#  Title: Polynomial spline routines
#  Author: Charles Kooperberg <clk@fhcrc.org>
#  Maintainer: Charles Kooperberg <clk@fhcrc.org>
#  Depends: R
#  Description: Routines for the polynomial spline fitting routines
#    hazard regression, hazard estimation with flexible tails, logspline,
#    lspec, polyclass, and polymars, by C. Kooperberg and co-authors
#  License: GPL version 2 or newer
#  Packaged: Thu Apr 22 13:59:50 2004; hornik
################################################################################


# ------------------------------------------------------------------------------
# Class Representation


setClass("fREG", 
    representation(
        call = "call",
        formula = "formula",
        family = "character",  
        method = "character",
        data = "timeSeries",
        fit = "list",
        residuals = "timeSeries",
        fitted = "timeSeries",
        title = "character",
        description = "character"
    )  
)
    

# ------------------------------------------------------------------------------


regSim = 
function(model = c("LM3", "LOGIT3", "GAM3"), n = 100)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns one from three artificial regression data sets
    
    # Details:
    #   LM3         3 Variable Linear Regression Model Example
    #   LOGIT2      2 Variable GLM Logit Model Example
    #   GAM         2 Variable Generalized Additive Model Example
    
    # FUNCTION:
    
    # Select Regression Models:
    model = match.arg(model)
    
    # LM3:
    if (model == "LM3") {
        x1 = rnorm(n)
        x2 = rnorm(n)
        x3 = rnorm(n)
        y = 0.75 * x1 + 0.25 * x2 - 0.5 * x3
        eps = 0.1 * rnorm(n)
        y = y + eps
        X = data.frame(Y = y, X1 = x1, X2 = x2, X3 = x3)
    }
    
    # LOGIT2:
    if (model == "LOGIT3") {
        # GLM / BINOMIAL/LOGIT - Example Data:
        x1 = rnorm(n)
        x2 = rnorm(n)
        x3 = rnorm(n)
        eps = 0.1 * rnorm(n)
        y = 0.75 * x1 + 0.25 * x2 - 0.5 * x3 + eps
        p = 1 / ( 1 + exp(-y) )
        X = data.frame(Y = p, X1 = x1, X2 = x2, X3 = x3)
    }
    
    # GAM2:
    if (model == "GAM3") {  
        # GAM - Example Data:
        set.seed(4711)
        x1 = runif(n)
        x2 = runif(n)
        x3 = runif(n)
        y1 = scale(sin(2 * pi * x1))
        y2 = scale(exp(x2))
        y3 = scale(x3)
        y = scale(y1 + y2 + y3)
        eps = 0.1 * rnorm(n, sd = sd(y))
        y = y + eps
        X = data.frame(Y = y, X1 = x1, X2 = x2, X3 = x3)
    }
    
    # Return Value:
    X
}
    
    

# ------------------------------------------------------------------------------


regFit = 
function (formula, data,
use = c("lm", "rlm", "am", "ppr", "mars", "polymars", "nnet"), 
title = NULL, description = NULL, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Common function call for several selected regression models.
    
    # Details:
    #   This is a wrapper function for the following regrssion models:
    #   LM          Linear Regression Modelling
    #   RLM         Robust Linear Regression Modelling
    #   AM          Additive Modelling
    #   PPR         Projection Pursuit Regression
    #   MARS        Multivariate Adaptive Regression Splines
    #   POLYMARS    Polytochomous MARS Modeling
    #   NNET        Feedforward Neural Net
    
    # Notes:
    #   Available Methods are
    #   "print", "plot", "summary", and "predict" method
    #   coefficients, "residuals" "fitted", "vcov" method
    
    # Example:
    #   regFit(Y ~ X1 + X2, regSim())
    
    # FUNCTION:
    
    # Trace:
    trace = FALSE
    
    # Get Method:
    if (!(class(data) == "timeSeries")) data = as.timeSeries(data)
    fun = use = match.arg(use)
    if (use == "am") fun = "gam"
    if (use == "mars") fun = ".mars"
    if (use == "polymars") fun = ".polymars"

    # Title:
    if (is.null(title)) {
        if (use == "lm") title = "Linear Regression Modelling"
        if (use == "rlm") title = "Robust Linear Regression Modelling"
        if (use == "am") title = "Additive Modelling"
        if (use == "ppr") title = "Projection Pursuit Regression"
        if (use == "mars") title = "Multivariate Adaptive Regression Splines"
        if (use == "polymars") title = "Polytochomous MARS Modeling"
        if (use == "nnet") title = "Feedforward Neural Network Modelling" 
    } 
    
    # Description:
    if (is.null(description)) {
        description = .description()
    }
    
    # Evaluate:
    cmd = match.call()
    if (!is.null(cmd$use)) cmd = cmd[-match("use", names(cmd), 0)]    
    cmd[[1]] <- as.name(fun)
    if (use == "ppr"  & !match("nterm",  names(cmd), 0) ) cmd$nterm = 2
    if (use == "nnet" & !match("trace",  names(cmd), 0) ) cmd$trace = FALSE
    if (use == "nnet" & !match("size",   names(cmd), 0) ) cmd$size = 2
    if (use == "nnet" & !match("linout", names(cmd), 0) ) cmd$linout = TRUE
    if (trace) print(cmd)
    fit <- eval(cmd, parent.frame()) 
    if (trace) print(fit)
      
    # Add to Fit:
    if (is.null(fit$xlevels)) fit$xlevels = list()
    fit$residuals = as.vector(fit$residuals)    
    fit$fitted.values = as.vector(fit$fitted.values)
    fit$parameters = fit$coef
    if (use == "am") fit$fake.formula = interpret.gam(formula)$fake.formula
    noFitModels = c("ppr", "mars", "nnet")
    FitModelTest = as.logical(match(use, noFitModels, 0))
    if (FitModelTest) {
        mf <- match.call(expand.dots = FALSE)
        Names = c("formula", "data", "subset", "weights", "na.action", "offset")
        mf <- mf[c(1, match(Names, names(mf), 0))]
        mf$drop.unused.levels <- TRUE
        mf[[1]] <- as.name("model.frame")
        fit$model <- eval(mf, parent.frame())
    }
    class(fit) = c("list", class(fit))
    if (!inherits(fit, "lm")) class(fit) = c(class(fit), "lm")

    # Add Units to timeSeries:
    resUnits = paste(as.character(formula)[2], "RES", sep = ".")
    fittedUnits = paste(as.character(formula)[2], "FITTED", sep = ".")
    residualsTS = 
        timeSeries(fit$residuals, rownames(data), units = resUnits)
    fittedTS = 
        timeSeries(fit$fitted.values, rownames(data), units = fittedUnits)
        
    # Return Value:
    new("fREG",     
        call = as.call(match.call()),
        formula = as.formula(formula), 
        family = as.character(gaussian()),
        method = use,
        data = data,
        fit = fit,
        residuals = residualsTS,
        fitted = fittedTS,
        title = as.character(title), 
        description = as.character(description) 
    )
}


# ------------------------------------------------------------------------------


gregFit = 
function (formula, family, data, use = c("glm", "gam"), 
title = NULL, description = NULL, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Common function call for several selected regression models.
    
    # Details:
    #   This is a wrapper function for the following regrssion models:
    #   GLM         Generalized Linear Modelling
    #   GAM         Generalized Additive Modelling
    
    # Notes:
    #   Available Methods are
    #   "print", "plot", "summary", and "predict" method
    #   coefficients, "residuals" "fitted", "vcov" method
    
    # FUNCTION:
    
    # Get Method:
    if (class(data) == "data.frame") data = as.timeSeries(data)
    fun = use = match.arg(use)

    # Title:
    if (is.null(title)) {
        if (use == "glm") title = "Generalized Linear Modelling"
        if (use == "gam") title = "Generalized Additive Modelling"
    }  
    
    # Description:
    if (is.null(description)) {
        description  = .description()
    }  
    
    # Evaluate:
    cmd = match.call()
    if (!is.null(cmd$use)) cmd = cmd[-match("use", names(cmd), 0)]    
    cmd[[1]] <- as.name(fun)
    fit <- eval(cmd, parent.frame()) 
        
    # Add to Fit:
    fit$residuals = as.vector(fit$residuals)    
    fit$fitted.values = as.vector(fit$fitted.values)
    fit$parameters = fit$coef
    class(fit) = c("list", class(fit))
    
    # Return Value:
    new("fREG",     
        call = as.call(match.call()),
        formula = as.formula(formula), 
        family = as.character(gaussian()),
        method = as.character(use),
        data = timeSeries(data, rownames(data)),
        fit = fit,
        residuals = timeSeries(fit$residuals, rownames(data)),
        fitted = timeSeries(fit$fitted.values, rownames(data)),
        title = as.character(title), 
        description = as.character(description) 
    )
}


# ------------------------------------------------------------------------------


print.fREG = 
function(x, ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Print method for Regression Modelling, an object of class "fREG"
    
    # FUNCTION:
    
    # Settings:
    object = x
    
    # Title:
    cat("\nTitle:\n ")
    cat(as.character(object@title), "\n")
    
    # Call:
    # cat("\nCall:\n")
    # cat(paste(deparse(object@call), sep = "\n", collapse = "\n"), 
    #    "\n", sep = "") 
        
    # Formula:
    cat("\nFormula:\n ")
    # cat(as.character(object@formula), "\n")
    print(object@formula)
    
    # Family:
    if (object@family[1] != "" && object@family[2] != "") {     
        cat("\nFamily:\n ")
        cat(as.character(object@family[1:2]), "\n") }
    
    # Digits:
    digits = max(4, getOption("digits") - 4)
        
    # Model Parameters:
    cat("\nModel Parameters:\n")        
        
        # Regression Model LM / RLM:
        if (object@method == "lm" | object@method == "rlm") {
            print.default(format(object@fit$coef, digits = digits), 
                print.gap = 2, quote = FALSE) 
        }
        
        # Regression Model GLM:
        if (object@method == "glm") {
            if (length(object@fit$coef)) {
                if (is.character(co = object@fit$contrasts)) 
                cat("  [contrasts: ", apply(cbind(names(co), co), 
                    1, paste, collapse = "="), "]")
                # cat(":\n")
                print.default(format(object@fit$coefficients,
                    digits = digits), print.gap = 2, quote = FALSE)
            } else { 
                cat("No coefficients\n\n") 
            } 
        }   
        
        # Regression Model GAM:
        if (object@method == "gam" | object@method == "am") {
            print.default(format(object@fit$coef, digits = digits), 
                print.gap = 2, quote = FALSE) 
                
        }       
        
        # Regression Model PPR:
        if (object@method == "ppr") {
            cat("-- Projection Direction Vectors --\n")
            print(object@fit$alpha)
            cat("-- Coefficients of Ridge Terms --\n")
            print(object@fit$beta) 
        }    
        
        # Regression Model MARS:
        if (object@method == "mars") {      
            Parameters = round(object@fit$parameters, digits = digits)      
            print(data.frame(Parameters)) 
        }             
        
        # Regression Model POLYMARS:
        if (object@method == "polymars") {
            print(object@fit$Model) 
        }  
        
        # Regression Model NNET:
        if (object@method == "nnet") {
            cat("   a ",object@fit$n[1], "-", object@fit$n[2], "-", 
                object@fit$n[3], " network", " with ", 
                length(object@fit$wts), " weights\n", sep="")
            cat("   options were -")
            tconn = diff(object@fit$nconn)
            if (tconn[length(tconn)] > object@fit$n[2]+1) 
                cat(" skip-layer connections ")
            if (object@fit$nunits > object@fit$nsunits && 
                !object@fit$softmax) 
                cat(" linear output units ")
            if (object@fit$entropy) 
                cat(" entropy fitting ")
            if (object@fit$softmax) 
                cat(" softmax modelling ")
            if (object@fit$decay[1] > 0) 
                cat(" decay=", object@fit$decay[1], sep="")
            cat("\n")
            Weights = object@fit$wts
            print(Weights) 
        } 
        
    # Residual Variance:
    # cat("\nResidual Variance:\n", var(object@fit$residuals))
    cat("\n")
        
    # Return Value:
    invisible()
}            
    

# ------------------------------------------------------------------------------


plot.fREG = 
function(x, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Plot method for Regression Modelling, an object of class "fREG"
    
    # FUNCTION:
    
    # Settings:
    .plot(x@fit)
    
    # Return Value:
    invisible()
}    


# ------------------------------------------------------------------------------


.plot.lm =
function(x, which = "ask", ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Tailored plot function for an object of class 'lm', 'rlm', 'glm'
    
    # Changes:
    #
    
    # FUNCTION:
    
    # 1. Responses + Fitted Values Plot:
    # 2. Residuals Plot:
    # 3. Quantile Plot:
    # 4. Fitted Values vs. Residuals Plot:
    # 5. ACF Plot
    # 6. PACF Plot
    # 7. Positive Mean Excess Plot"
    # 8. Negative Mean Excess Plot"
    .plot1 <<- function(x, ...) .responsesPlot(residuals(x)+fitted(x),fitted(x))
    .plot2 <<- function(x, ...) .residualsPlot(residuals(x))    
    .plot3 <<- function(x, ...) .qqbayesPlot(residuals(x))
    .plot4 <<- function(x, ...) .firePlot(fitted(x), residuals(x)) 
    .plot5 <<- function(x, ...) .acfPlot(residuals(x))
    .plot6 <<- function(x, ...) .pacfPlot(residuals(x))
    .plot7 <<- function(x, ...) .mrlPlot(residuals(x))
    .plot8 <<- function(x, ...) .mrlPlot(-residuals(x))
    
    # 1. lm: Residuals vs Fitted:
    # 2. lm: Normal Q-Q:
    # 3. lm: Scale-Location:
    # 4. lm: Cook's distance:
    # 5. lm: Residuals vs Leverage:
    # 6. lm: Cook's distance vs Leverage:
    .plot9 <<- function(x, ...) plot(x, 1, pch = 19, col = "steelblue", ...)  
    .plot10<<- function(x, ...) plot(x, 2, pch = 19, col = "steelblue", ...)
    .plot11<<- function(x, ...) plot(x, 3, pch = 19, col = "steelblue", ...)
    .plot12<<- function(x, ...) plot(x, 4, pch = 19, col = "steelblue", ...)
    .plot13<<- function(x, ...) plot(x, 5, pch = 19, col = "steelblue", ...)
    .plot14<<- function(x, ...) plot(x, 6, pch = 19, col = "steelblue", ...)
    
    # Plot:
    .interactiveRegressionPlot(
        x,
        choices = c(
            "Responses + Fitted Values",
            "Residuals",
            "Normal Q-Q",
            "Residuals vs Fitted",
            "ACF of Residuals",
            "PACF of Residuals",
            "Positive Mean Excess Plot",
            "Negative Mean Excess Plot",
            "lm: Residuals vs Fitted", 
            "lm: Normal Q-Q", 
            "lm: Scale-Location", 
            "lm: Cook's distance", 
            "lm: Residuals vs Leverage", 
            "lm: Cook's distance vs Leverage"),
        plotFUN = paste(".plot", 1:14, sep = ""),
        which = which) 
            
    # Return Value:
    invisible(x)
} 


# ------------------------------------------------------------------------------


.plot.common =
function(x, which = "ask", ...)
{
    # 1. Responses + Fitted Values Plot:
    # 2. Residuals Plot:
    # 3. Quantile Plot:
    # 4. Fitted Values vs. Residuals Plot:
    .plot1 <<- function(x, ...) .responsesPlot(residuals(x)+fitted(x),fitted(x))
    .plot2 <<- function(x, ...) .residualsPlot(residuals(x))    
    .plot3 <<- function(x, ...) .qqbayesPlot(residuals(x))
    .plot4 <<- function(x, ...) .firePlot(fitted(x), residuals(x)) 
    .plot5 <<- function(x, ...) .acfPlot(residuals(x))
    .plot6 <<- function(x, ...) .pacfPlot(residuals(x))
    .plot7 <<- function(x, ...) .mrlPlot(residuals(x))
    .plot8 <<- function(x, ...) .mrlPlot(-residuals(x))
    
    # Plot:
    .interactiveRegressionPlot(
        x,
        choices = c(
            "Responses + Fitted Values",
            "Residuals",
            "Normal Q-Q",
            "Residuals vs Fitted",
            "ACF of Residuals",
            "PACF of Residuals",
            "Positive Mean Excess Plot",
            "Negative Mean Excess Plot"),
        plotFUN = paste(".plot", 1:8, sep = ""),
        which = which) 
            
    # Return Value:
    invisible(x)
}


# ------------------------------------------------------------------------------


.plot.gam = .plot.common
.plot.ppr = .plot.common
.plot.mars = .plot.common
.plot.polymars = .plot.common
.plot.nnet = .plot.common


# ******************************************************************************


summary.fREG =       
function(object, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Summary method for Regression Modelling, an object of class "fREG"
    
    # FUNCTION:
    
    # Digits:
    digits = max(4, getOption("digits") - 4)
    
    # Print all from print Method:
    print(object)
    
    # Add Residual Variance:
    cat("Residual Variance:\n", var(object@fit$residuals))
    cat("\n\n")

    # Internal Function: fResiduals
    fResiduals = 
    function(x, digits) 
    {
        cat("Non-Weighted Residuals:\n")
        names = c("Min", "1Q", "Median", "3Q", "Max")
        rq = structure(quantile(x), names = names)
        print(rq, digits = digits) 
        names = c("Variance", "StDev", "Skewness", "Kurtosis")
        skewness = sum((x - mean(x))^3/sqrt(var(x))^3)/length(x)
        kurtosis = sum((x - mean(x))^4/var(x)^2)/length(x) - 3
        rq = structure(c(var(x), sqrt(var(x)), skewness, kurtosis), 
            names = names)
        print(rq, digits = digits) 
        print("done")
        cat("\n") 
        invisible() 
    }
        
    # Internal Function: print.summary.LM
    print.summary.LM = 
    function (x, ...) 
    {
        digits = max(4, getOption("digits") - 4)
        symbolic.cor = x$symbolic.cor
        signif.stars = getOption("show.signif.stars")
        # cat("\nCall:\n")
        # cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), 
        #   "\n\n", sep = "")
        resid = x$residuals
        df = x$df
        rdf = df[2]
        cat(if (!is.null(x$w) && diff(range(x$w))) 
            "Weighted ", "Residuals:\n", sep = "")
        if (rdf > 5) {
            nam = c("Min", "1Q", "Median", "3Q", "Max")
            rq = if (length(dim(resid)) == 2) 
                structure(apply(t(resid), 1, quantile), 
                    dimnames = list(nam, dimnames(resid)[[2]]))
            else structure(quantile(resid), names = nam)
            print(rq, digits = digits, ...) 
        } else if (rdf > 0) {
            print(resid, digits = digits, ...)
        } else {
            cat("ALL", df[1], "residuals are 0: no residual ",
                "degrees of freedom!\n") 
        }
        if (length(x$aliased) == 0) {
            cat("\nNo Coefficients\n") 
        } else {
            if (nsingular<-df[3] - df[1]) {
                cat("\nCoefficients: (", nsingular, " not defined ",
                    "because of singularities)\n", sep = "")
            } else {
                cat("\nCoefficients:\n")
            }
            coefs = x$coefficients
            if (!is.null(aliased = x$aliased) && any(x$aliased)) {
                cn = names(aliased)
                coefs = matrix(NA, length(aliased), 4, dimnames = 
                    list(cn, colnames(coefs)))
                coefs[!aliased, ] = x$coefficients 
            }
            printCoefmat(coefs, digits = digits, signif.stars = 
                signif.stars, na.print = "NA", ...) 
        }
        cat("\nResidual standard error:", format(signif(x$sigma, 
            digits)), "on", rdf, "degrees of freedom\n")
        if (!is.null(x$fstatistic)) {
            cat("Multiple R-Squared:", formatC(x$r.squared, 
                digits = digits))
            cat(",  Adjusted R-squared:", formatC(x$adj.r.squared, 
                digits = digits), "\nF-statistic:", 
                formatC(x$fstatistic[1], digits = digits), "on", 
                x$fstatistic[2], "and", x$fstatistic[3], 
                "DF,  p-value:", format.pval(pf(x$fstatistic[1], 
                x$fstatistic[2], x$fstatistic[3], lower.tail = FALSE), 
                digits = digits), "\n") }
        correl = x$correlation
        if (!is.null(correl)) {
            p = NCOL(correl)
            if (p > 1) {
                cat("\nCorrelation of Coefficients:\n")
                if (is.logical(symbolic.cor) && symbolic.cor) {
                    print(symnum(correl, abbr.col = NULL)) }
                else {
                    correl = format(round(correl, 2), nsmall = 2, 
                      digits = digits)
                    correl[!lower.tri(correl)] = ""
                    print(correl[-1, -p, drop = FALSE], quote = FALSE) }} }
        cat("\n")
        invisible() 
    }
        
    # Internal Function: print.summary.GLM
    print.summary.GLM = 
    function (x, ...) 
    {
        digits = max(4, getOption("digits") - 4)
        symbolic.cor = x$symbolic.cor
        signif.stars = getOption("show.signif.stars")
        #cat("\nCall:\n")
        #cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), 
        #   "\n\n", sep = "")
        cat("Deviance Residuals: \n")
        if (x$df.residual > 5) {
            x$deviance.resid = quantile(x$deviance.resid, na.rm = TRUE)
            names(x$deviance.resid) = c("Min", "1Q", "Median", "3Q", 
                "Max") }
        print.default(x$deviance.resid, digits = digits, na = "", 
            print.gap = 2)
        if (length(x$aliased) == 0) {
            cat("\nNo Coefficients\n") 
        } else {
            if (!is.null(df = x$df) && (nsingular = df[3] - df[1])) 
                cat("\nCoefficients: (", nsingular, " not defined ",
                "because of singularities)\n", sep = "")
            else cat("\nCoefficients:\n")
            coefs = x$coefficients
            if (!is.null(aliased = x$aliased) && any(aliased)) {
                cn = names(aliased)
                coefs = matrix(NA, length(aliased), 4, dimnames = 
                    list(cn, colnames(coefs)))
                coefs[!aliased, ] = x$coefficients }
            printCoefmat(coefs, digits = digits, signif.stars = 
                signif.stars, na.print = "NA", ...) 
            }
        cat("\n(Dispersion parameter for ", x$family$family, 
            " family taken to be ", format(x$dispersion), ")\n\n", 
            apply(cbind(paste(format.char(c("Null", "Residual"), 
            width = 8, flag = ""), "deviance:"), 
            format(unlist(x[c("null.deviance", "deviance")]), 
            digits = max(5, digits + 1)), " on", 
            format(unlist(x[c("df.null", "df.residual")])), 
            " degrees of freedom\n"), 1, paste, collapse = " "), 
            "AIC: ", format(x$aic, digits = max(4, digits + 1)), 
            "\n\n", "Number of Fisher Scoring iterations: ", 
            x$iter, "\n", sep = "")
        correl = x$correlation
        if (!is.null(correl)) {
            p = NCOL(correl)
            if (p > 1) {
                cat("\nCorrelation of Coefficients:\n")
                if (is.logical(symbolic.cor) && symbolic.cor) {
                    print(symnum(correl, abbr.col = NULL)) }
                else {
                    correl = format(round(correl, 2), nsmall = 2, 
                      digits = digits)
                    correl[!lower.tri(correl)] = ""
                    print(correl[-1, -p, drop = FALSE], quote = FALSE) }}}
        cat("\n")
        invisible() 
    }

    # Internal Function: print.summary.GAM
    print.summary.GAM = 
    function(x, ...) 
    { 
        if (length(x$p.coeff) > 0) {
            cat("Parametric coefficients:\n")
            width = max(nchar(names(x$p.coeff)))
            cat(rep(" ",width), "   Estimate  std. err.    t ratio",
                "    Pr(>|t|)\n", sep = "")
            for (i in 1:length(x$p.coeff))
                cat(formatC(names(x$p.coeff)[i], width = width), " ",
                    formatC(x$p.coeff[i], width=10, digits=5), " ",
                    formatC(x$se[i], width = 10, digits = 4), " ",
                    formatC(x$p.t[i], width = 10, digits = 4), "    ",
                    format.pval(x$p.pv[i]), "\n", sep="") }
        cat("\n")
        if (x$m > 0) { 
            cat("Approximate significance of smooth terms:\n")
            width = max(nchar(names(x$chi.sq)))
            cat(rep(" ",width), "        edf       chi.sq     ",
                "p-value\n", sep = "")
            for (i in 1:x$m)
                cat(formatC(names(x$chi.sq)[i], width = width), " ", 
                    formatC(x$edf[i], width = 10, digits = 4), "   ",
                    formatC(x$chi.sq[i], width = 10, digits = 5), "     ",
                    format.pval(x$s.pv[i]), "\n", sep = "") }
        cat("\nR-sq.(adj) = ", formatC(x$r.sq, digits = 3, width = 5),
            "   Deviance explained = ", formatC(x$dev.expl*100, 
            digits = 3, width = 4), "%", sep = "")
        if (is.null(x$ubre)) {
            cat("\nGCV score = ", formatC(x$gcv, digits = 5), " ", sep = "")
        } else {
            cat("\nUBRE score = ", formatC(x$ubre, digits = 5), sep = "")
        }
        cat("  Scale est. = ", formatC(x$scale, digits = 5, 
            width = 8, flag = "-"), "  n = ", x$n, "\n", sep = "") 
        invisible() 
    }           

    # Fit:
    fit = object@fit 
            
    # Regression Model: LM
    if (object@method == "lm") {
        class(fit) = "lm"
        ans = summary.lm(object = fit, ...)
        print.summary.LM(x = ans, ...) 
    }    
    
    # Regression Model: GLM
    if (object@method == "glm") {
        class(fit) = c("glm", "lm")
        ans = summary.glm(object = fit, ...)
        print.summary.GLM(x = ans, ...) 
    }   
    
    # Regression Model: GAM
    if (object@method == "gam") {
        class(fit) = "gam"
        ans = summary.gam(object = fit, ...)
        print.summary.GAM(x = ans, ...) 
    }   
    
    # Regression Model: GAM
    if (object@method == "gam") {
        class(fit) = "gam"
        ans = summary.gam(object = fit, ...)
        print.summary.GAM(x = ans, ...) 
    }
        
    # Regression Model: PPR
    if (object@method == "ppr") {
        # This is what print.ppr produces.
        mu = fit$mu; ml = fit$ml
        cat("Goodness of fit:\n")
        gof = fit$gofn; names(gof) = paste(1:ml, "terms")
        print(format(gof[mu:ml], ...), quote = FALSE)
        # This is what summary.ppr produces.
        if (any(fit$edf > 0)) {
            cat("\nEquivalent df for ridge terms:\n")
            edf = fit$edf
            names(edf) = paste("term", 1:fit$mu)
            print(round(edf, 2), ...)} 
    }        
                
    # Regression Model: MARS
    if (object@method == "mars") {
        # Use the print Method 
    } 
            
    # Regression Model: POLYMARS
    if (object@method == "polymars") {
        # This is what summary.polymars produces.
        # There is no print.summary.polymars.
        cat("Model Fitting:\n")
        print(fit$fitting)
        if(fit$responses != 1)
            cat("\nResponses:", fit$responses, "\n")
        if(!is.null(fit$Rsquared))
            cat("\nRsquared:",round(fit$Rsquared, 4),"\n") 
        cat("\n") 
    }
        
    # Regression Model: NNET
    if (object@method == "nnet") {
        # Use the print Method
    }       

    # Return Value:
    invisible() 
}


# ------------------------------------------------------------------------------


.predict.lm = predict.lm
.predict.gam = predict.gam
.predict.glm = predict.glm 
.predict.ppr = function(object, ...) { predict(object, ...) }
.predict.nnet = function(object, ...) { predict(object, ...) }


# ------------------------------------------------------------------------------


predict.fREG =
function(object, newdata, se.fit = FALSE, type = "response", ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Predict method for Regression Modelling, an object of class "fREG"
    
    # FUNCTION:
    
    # Fit:
    fit = object@fit
      
    # Data:
    if (missing(newdata)) newdata = object@data
    newdata = as.data.frame(newdata)
     
    # Predict:
    if (object@method == "nnet" & type == "response") type = "raw"
    ans = .predict(object = fit, newdata = newdata, se.fit = se.fit, 
        type = type, ...) 
    
    # Make the output from 'predict' unique:
    if (se.fit) {
        if (!is.list(ans)) {
            if (is.matrix(ans)) ans = as.vector(ans)
            names(ans) = rownames(newdata) 
            ans = list(fit = ans, se.fit = NA*ans) 
        } else {
            ans = ans[1:2]
        }
    } else {
        if (is.matrix(ans)) ans = as.vector(ans)
        names(ans) = rownames(newdata) 
    }
            
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------

        
coef.fREG = 
function(object, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Coefficients method for Regression Modelling
    
    # FUNCTION:
    
    # Fitted Values:
    ans = coefficients(object@fit) 
            
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------

        
fitted.fREG = 
function(object, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Fitted values method for Regression Modelling
    
    # FUNCTION:
    
    # Fitted Values:
    ans = object@fitted
            
    # Return Value:
    ans
}
        

# ------------------------------------------------------------------------------

                   
residuals.fREG = 
function(object, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Residuals method for Regression Modelling
    
    # FUNCTION:
    
    # Residuals:
    ans = object@residuals
            
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------

        
vcov.fREG = 
function(object, ...)
{   # A function imlemented by Diethelm Wuertz

    # Description:
    #   Variance-Covariance Matrix method for Regression Modelling
    
    # FUNCTION:
    
    # Fitted Values:
    ans = vcov(object@fit) 
            
    # Return Value:
    ans
}


################################################################################
# FUNCTION:
#  .mars
#  .mars.default
#  .predict.mars
#  .showcuts.mars


.mars = 
function(formula, data, ...) 
{   # A function implemented by Diethelm Wuertz

    # FUNCTION:
    
    # Settings:
    m = match.call(expand = FALSE)
    m$contrasts = m$... = NULL
    m[[1]] = as.name("model.frame")
    m = eval(m, parent.frame())
    na.act = attr(m, "na.action")
    Terms = attr(m, "terms")
    attr(Terms, "intercept") = 0
    X = model.matrix(Terms, m, contrasts)
    Y = model.extract(m, response)
    w = model.extract(m, weights)
    if (length(w) ==  0) w = rep(1, nrow(X))
    
    # Fit:
    fit = .mars.default(X, Y, w, ...)
    fit$terms = Terms   
    
    # Result:
    fit$family = c("", "")
    fit$parameters = as.vector(fit$coefficients)
    fit$model = data
    
    # Return Value:
    fit 
}


# ------------------------------------------------------------------------------


.mars.default = 
function (x, y, w = rep(1, nrow(x)), wp, degree = 1, nk = max(21, 
2 * ncol(x) + 1), penalty = 2, thresh = 0.001, prune = TRUE, 
trace.mars = FALSE, forward.step = TRUE, prevfit = NULL, ...) 
{   # A function implemented by Diethelm Wuertz

    # Note:
    #   A (modified) copy from contributed R-package 'mda' 
    
    # FUNCTION:
        
    # MARS:
    this.call = match.call()
    if ((nk%%2) != 1) nk = nk - 1
    x = as.matrix(x)
    np = dim(x)
    n = np[1]
    p = np[2]
    y = as.matrix(y)
    nclass = ncol(y)
    if (is.null(np)) {
        np = c(length(x), 1)
        x = as.matrix(x) 
    }
    if (forward.step) {
        interms = 1
        lenb = nk
        bx = matrix(rep(0, nrow(x) * nk), nrow = n)
        res = matrix(rep(0, nrow(x) * ncol(y)), nrow = n)
        fullin = rep(0, nk)
        cuts = NULL
        factor = NULL 
    } else {
        bx = model.matrix.mars(prevfit, x, full = TRUE)
        interms = ncol(bx)
        lenb = prevfit$lenb
        o = prevfit$all.terms
        fullin = rep(0, ncol(bx))
        fullin[o] = 1
        res = prevfit$res
        factor = prevfit$factor
        cuts = prevfit$cuts
        if (missing(penalty)) 
            penalty = prevfit$penalty
        degree = prevfit$degree
        nk = lenb
        thresh = prevfit$thresh 
    }
    if (missing(penalty) & (degree > 1)) {
        penalty = 3
    }
    if (!missing(wp)) {
        if (any(wp <= 0)) 
            stop("wp should all be positive")
        wp = sqrt(wp/sum(wp))
        y = y * outer(rep(1, n), wp) 
    } else {
        wp = NULL
    }
    tagx = x
    storage.mode(tagx) = "integer"
    for (j in 1:p) {
        tagx[, j] = order(x[, j]) 
    }
    bestin = rep(0, nk)
    flag = matrix(rep(0, nk * p), nrow = nk, ncol = p)
    if (is.null(cuts)) {
        cuts = matrix(rep(0, nk * p), nrow = nk, ncol = p)
    }
    if (is.null(factor)) {
        dir = matrix(rep(0, nk * p), nrow = nk, ncol = p) 
    } else {
        dir = factor 
    }
    alpha = rep(0, nclass)
    beta = matrix(rep(0, nk * nclass), nrow = nk)
    bestgcv = 0
    storage.mode(y) = "double"
    storage.mode(x) = "double"
    storage.mode(bx) = "double"
    storage.mode(flag) = "integer"
    storage.mode(cuts) = "double"
    storage.mode(dir) = "double"
    storage.mode(res) = "double"
    storage.mode(beta) = "double"
    lenscrat = 1 + n + 2 * n * nk + 4 * nk * nk + 3 * nk + 3 * 
        nk * nclass + 3 * nclass + 28 * n + 51
    junk = .Fortran("marss", as.integer(n), as.integer(n), as.integer(p), 
        as.integer(nclass), as.matrix(y), as.matrix(x), as.double(w), 
        as.matrix(tagx), as.integer(degree), as.integer(nk), 
        as.double(penalty), as.double(thresh), as.logical(forward.step), 
        as.integer(interms), as.logical(prune), bx = as.matrix(bx), 
        fullin = as.integer(fullin), lenb = as.integer(lenb), 
        bestgcv = as.double(bestgcv), bestin = as.integer(bestin), 
        flag = as.matrix(flag), cuts = as.matrix(cuts), dir = as.matrix(dir), 
        res = as.matrix(res), alpha = as.double(alpha), beta = as.matrix(beta), 
        double(lenscrat), integer(4 * nk), trace.mars, PACKAGE = "fMultivar")
    lenb = junk$lenb
    all.terms = seq(lenb)[junk$fullin[1:lenb] == 1]
    selected.terms = seq(lenb)[junk$bestin[1:lenb] == 1]
    coefficients = junk$beta[seq(selected.terms), , drop = FALSE]
    residuals = junk$res
    fitted.values = y - residuals
    if (!is.null(wp)) {
        TT = outer(rep(1, n), wp)
        residuals = residuals/TT
        fitted.values = fitted.values/TT
        coefficients = coefficients/outer(rep(1, length(selected.terms)), wp) 
    }
    dir = junk$dir[seq(lenb), , drop = FALSE]
    dimnames(dir) = list(NULL, dimnames(x)[[2]])
    cutss = junk$cuts[seq(lenb), , drop = FALSE]
    x = junk$bx[, selected.terms, drop = FALSE]
    
    # Return Value:
    structure(list(call = this.call, all.terms = all.terms, 
        selected.terms = selected.terms, 
        penalty = penalty, degree = degree, nk = nk, thresh = thresh, 
        gcv = junk$bestgcv, factor = dir, cuts = cutss, 
        residuals = residuals, 
        fitted.values = fitted.values, lenb = junk$lenb, 
        coefficients = coefficients
        #x = x
        ), 
        class = "mars")
}


# ------------------------------------------------------------------------------


.predict.mars = 
function (object, newdata, se.fit = FALSE, ...) 
{   # A function implemented by Diethelm Wuertz

    # Note:
    #   A (modified) copy from contributed R-package 'mda' 
    
    # FUNCTION:
    
    # Select Object:
    if (class(object)[1] == "fREG") object = object@fit
    
    # Predict:
    if (missing(newdata)) {
        z <- fitted(object)
        if (is.null(z)) {
            stop("need to supply newdata")
        } else {
            ans = z
        }
    } else {
        tt = terms(object)
        Terms = delete.response(tt)
        x <- model.frame(Terms, newdata)
        x = as.matrix(x)
        dd = dim(x)
        n = dd[1]
        p = dd[2]
        which = object$selected.terms
        nterms = length(which)
        dir = object$factor
        cut = object$cuts
        
        modelMatrix = matrix(1, nrow = n, ncol = nterms)
        which = which[-1]
        for (i in seq(along = which)) {
            j = which[i]
            if (all(dir[j, ] == 0)) { stop("error in factor or which") }
            temp1 = 1
            for (k in 1:p) {
                if (dir[j, k] != 0) {
                    temp2 = dir[j, k] * (x[, k] - cut[j, k])
                    temp1 = temp1 * temp2 * (temp2 > 0) 
                } 
            }
            modelMatrix[, i + 1] = temp1
        }    
        ans = modelMatrix %*% object$coefficients
        ans = as.vector(ans)
        names(ans) = rownames(newdata)
    }
    
    # Add Standard Errors ?
    if (se.fit) {
        se.fitted = NA*ans
        names(se.fitted) = names(ans)
        ans = list(fit = ans, se.fit = se.fitted)
    }
    
    # Return Value:
    ans
}



# ------------------------------------------------------------------------------


.showcuts.mars = 
function(object)
{   # A function implemented by Diethelm Wuertz

    # Note:
    #   A (modified) copy from contributed R-package 'mda' 
    
    # FUNCTION:
    
    # Select Object:
    if (class(object)[1] == "fREG") object = object@fit
    
    # Cuts:
    tmp = object$cuts[object$sel, ]
    dimnames(tmp) = list(NULL, names(trees)[-3])
    
    # Return Value:
    tmp
}


################################################################################
# FUNCTION:
#  .polymars
#  .polymars.default
#  .predict.polymars
#  Contributed package "polspline" is required!


.polymars =
function(formula, data, ...)
{   # A function implemented by Diethelm Wuertz
    
    # FUNCTION:
    
    # Extract Model Data:
    mf = match.call(expand.dots = FALSE)
    m = match(c("formula", "data"), names(mf), 0)
    mf = mf[c(1, m)]
    mf$drop.unused.levels <- TRUE
    mf[[1]] <- as.name("model.frame")
    Data = eval(mf, parent.frame())
    y = Data[, 1]
    x = Data[, -1]
    
    # Fit:
    fit = .polymars.default(responses = y, predictors = x, ...) 
    
    # Add to fit:
    fit$fitted.values = fit$fitted
    fit$terms = terms(formula)
    fit$Model = fit$model
    fit$model = Data
    class(fit) = "polymars"
    
    # Return Value:
    fit
}


# ------------------------------------------------------------------------------


.polymars.default = 
function(responses, predictors, maxsize, gcv = 4, additive = FALSE, 
startmodel, weights, no.interact, knots, knot.space = 3, ts.resp, ts.pred, 
ts.weights, classify, factors, tolerance = 1e-06, verbose = FALSE) 
{   # A function implemented by Diethelm Wuertz
    
    # Arguments:
    #  responses - a vector (or matrix) of responses. (Can be a a vector of 
    #       characters for classification)
    #  predictors - a matrix of predictors with same number of cases as 
    #       response. Columns are predictors.
    
    # Optional Arguments:
    #  maxsize - maximum number of basis function the model can contain 
    #  gcv - parameter for overall best model seletion
    #  additive - boolean, is the model to be additive
    #  startmodel - either a matrix (m*4 or m*5) or a polymars object from 
    #       a previous call to polymars 
    #       an initial model the procedure should start with in model 
    #       selection
    #  weights - a vector of length equal to the number of cases
    #  no.interact - a 2*l matrix of columns numbers of the predictor 
    #       matrix (each row pair cannot have interaction terms)
    #  knots - a vector specifying many knots per predictor are 
    #       wanted (with -1 for categorical variables) 
    #       ncol(predictors)==length(knots), or a matrix with 
    #       ncol(predictors) == ncol(knots) with actual knot 
    #       specified and filled out with NA's.
    #       Can also be a single number - "knots" number of knots 
    #       per predictor                    
    #  knot.space - minimum number of order statistics between knots
    #  ts.resp - testset reponses, same format as responses
    #  ts.pred - testset predictors, same format as predictors
    #  ts.weights - testset weights, same format as weights
    #  classify - whether classification is to be done, set = TRUE if the 
    #       response vector is integer, if 
    #       if character classify is automatically true
    #  factors - a vector of column numbers of the predictor matrix of 
    #       categorical variables
    #  tolerance - a numerical parameter which may need to be made smaller 
    #       if the program crashes store the call to the polymars 
    #       function

    # FUNCTION:
    
    # require(polspline)
    require(polspline)
    
    # Fit:
    .Call <- match.call()
    .Call[[1]] <- as.name("polymars")
    ans = eval(.Call, parent.frame())
    
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------


.predict.polymars =
function(object, newdata, se.fit = FALSE, ...)
{   # A function implemented by Diethelm Wuertz

    # FUNCTION:
    
    # Predict:
    if (missing(newdata)) {
        y = as.vector(object$fitted)
    } else {
        object$model = object$Model
        tt = terms(object)
        Terms = delete.response(tt)
        modelFrame = model.frame(Terms, newdata)
        x = model.matrix(Terms, modelFrame)[, -1]
        class(object) = "polymars"
        y = as.vector(predict(object, x = x, ...))
        names(y) = rownames(newdata)
    }
    
    # Add optionally standard errors:
    if (se.fit) y = list(fit = y, se.fit = NA*y)
   
    # Return Value:
    y
}


################################################################################
#  OLS            Fit an OLS regression model
#   print.OLS      S3 Print method for an OLS regression model
#   plot.OLS       S3 Plot method for an OLS regression model
#   summary.OLS    S3 Summary method for an OLS regression model


OLS = 
function(formula, data, ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   OLS Estimator
    
    # Notes:
    #   A Finmetrics S-Plus like implementation
    
    # FUNCTION:
    
    # Estimate:
    fit = lm(formula = formula, data = data, ...)
    fit$call = match.call()
    fit$formula = formula
    fit$data = data
    class(fit) = "OLS"
    
    # Return Value:
    fit 
}

# ------------------------------------------------------------------------------


print.OLS = 
function(x, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   S3 Print Method
    
    # FUNCTION:
    
    # Print:
    class(x) = "lm"
    print.lm(x, ...) 
    
    # Return Value:
    inbvisible(x)
}
    

# ------------------------------------------------------------------------------


plot.OLS = 
function(x, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   S3 Plot Method
    
    # FUNCTION:
    
    # Plot:
    class(x) = "lm"
    plot.lm(x, ...)
    
    # Return Value:
    inbvisible(x)
}


# ------------------------------------------------------------------------------

    
summary.OLS = 
function(object, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   S3 Summary Method
    
    # FUNCTION:
    
    # Summary:
    class(object) = "lm"
    summary.lm(object, ...) 
    
    # Return Value:
    inbvisible(object)
}


################################################################################


.interactiveRegressionPlot = 
function(x, choices = paste("Plot", 1:19), 
plotFUN = paste("plot.", 1:19, sep = ""), which = "all", ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Plot method for an object of class "template".
    
    # Arguments:
    #   x - an object to be plotted
    #   choices - the character string for the choice menu
    #   plotFUN - the names of the plot functions
    #   which - plot selection, which graph should be 
    #     displayed. If a character string named "ask" the 
    #     user is interactively asked which to plot, if
    #     a logical vector of length N, those plots which
    #     are set "TRUE" are displayed, if a character string
    #     named "all" all plots are displayed.
    
    # Note:
    #   At maximum 19 plots are supported.

    # FUNCTION:
    
    # Some cecks:
    if (length(choices) != length(plotFUN)) 
        stop("Arguments choices and plotFUN must be of same length.")
    if (length(which) > length(choices)) 
        stop("Arguments which has incorrect length.")
    if (length(which) > length(plotFUN)) 
        stop("Arguments which has incorrect length.")
    if (length(choices) > 19)
        stop("Sorry, only 19 plots at max are supported.")
    
    # Internal "askPlot" Function:                
    multPlot = function (x, choices, ...) 
    {
        # Selective Plot:
        selectivePlot = function (x, choices, FUN, which){
            # Internal Function:
            askPlot = function (x, choices, FUN) {
                # Pick and Plot:
                pick = 1; n.plots = length(choices)
                while (pick > 0) { pick = menu (
                    choices = paste("plot:", choices), 
                    title = "\nMake a plot selection (or 0 to exit):")
                    if (pick > 0) match.fun(FUN[pick])(x) } }                   
            if (as.character(which[1]) == "ask") {
                askPlot(x, choices = choices, FUN = FUN, ...) }
            else { 
                for (i in 1:n.plots) if (which[i]) match.fun(FUN[i])(x) }
            invisible() }  
        # match Functions, up to nine ...
        if (length(plotFUN) < 19) plotFUN = 
            c(plotFUN, rep(plotFUN[1], times = 19 - length(plotFUN)))
        plot.1  = match.fun(plotFUN[1]);  plot.2  = match.fun(plotFUN[2]) 
        plot.3  = match.fun(plotFUN[3]);  plot.4  = match.fun(plotFUN[4]) 
        plot.5  = match.fun(plotFUN[5]);  plot.6  = match.fun(plotFUN[6]) 
        plot.7  = match.fun(plotFUN[7]);  plot.8  = match.fun(plotFUN[8]) 
        plot.9  = match.fun(plotFUN[9]);  plot.10 = match.fun(plotFUN[10])
        plot.11 = match.fun(plotFUN[11]); plot.12 = match.fun(plotFUN[12]) 
        plot.13 = match.fun(plotFUN[13]); plot.14 = match.fun(plotFUN[14]) 
        plot.15 = match.fun(plotFUN[15]); plot.16 = match.fun(plotFUN[16]) 
        plot.17 = match.fun(plotFUN[17]); plot.18 = match.fun(plotFUN[18]) 
        plot.19 = match.fun(plotFUN[19])        
        pick = 1
        while (pick > 0) { pick = menu (
            ### choices = paste("plot:", choices),
            choices = paste(" ", choices), 
            title = "\nMake a plot selection (or 0 to exit):")
            # up to 19 plot functions ...
            switch (pick, 
                plot.1(x),  plot.2(x),  plot.3(x),  plot.4(x),  plot.5(x), 
                plot.6(x),  plot.7(x),  plot.8(x),  plot.9(x),  plot.10(x),
                plot.11(x), plot.12(x), plot.13(x), plot.14(x), plot.15(x), 
                plot.16(x), plot.17(x), plot.18(x), plot.19(x)) 
        } 
    }
                              
    # Plot:
    if (is.numeric(which)) {
        Which = rep(FALSE, times = length(choices))
        Which[which] = TRUE
        which = Which
    }
    if (which[1] == "all") {
        which = rep(TRUE, times = length(choices))
    }
    if (which[1] == "ask") {
        multPlot(x, choices, ...) 
    } else {
        for ( i in 1:length(which) ) {
            FUN = match.fun(plotFUN[i])
            if (which[i]) FUN(x) 
        } 
    }
            
    # Return Value:
    invisible(x)
}


################################################################################


.terms.fREG = 
function(object, formula = Y ~ X1)
{  
    select = all.vars(formula)
    print(class(object@fit)[-1])
    
    fit = object@fit
    data = as.data.frame(object@data)
    X = predict(fit, data, type = "terms")[, select[2]]
    Y = predict(fit, data, type = "response")
    
    plot(X, Y, xlab = select[2], ylab = select[1], col = "steelblue", pch = 19)
    grid()   
    rug(X)
    
    invisible()
}


# ------------------------------------------------------------------------------


.response2Plot = 
function(object, formula = Y ~ X1 + X2, N = 10, fun = mean)
{  
    Data = fit@data
    select = all.vars(formula)
    
    X = data[, select[2]]
    Y = data[, select[3]]
    Z = data[, select[1]]
    rangeX = range(X)
    rangeY = range(Y)
    statsData = colStats(Data, fun)
    
    U = seq(rangeX[1], rangeX[2], length = N)
    V = seq(rangeY[1], rangeY[2], length = N)
    newGrid = grid2d(U, V)
    
    newData = matrix(rep(statsData, times = N*N), 
        byrow = TRUE, ncol = ncol(Data))
    colnames(newData) = colnames(Data)
    newData[, select[2]] = newGrid$x
    newData[, select[3]] = newGrid$y
    newData[, select[1]] = NA
    newData = data.frame(newData)
    P = predict(object, newdata = newData)$fit
    
    W = matrix(P, byrow = FALSE, ncol = N)
    persp(U, V, W, xlab = select[2], ylab = select[3], zlab = select[1],
        phi = 30, theta = -40, col = "steelblue")->res
        
    R = sign(fit@residuals)
    points(trans3d(X[R>0], Y[R>0], Z[R>0], pm = res), col = 5, pch =16)
    points(trans3d(X[R<0], Y[R<0], Z[R<0], pm = res), col = 6, pch =16)
    
    invisible()
}


################################################################################