-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnikon_curve.c
2322 lines (1992 loc) · 77.1 KB
/
nikon_curve.c
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
/***************************************************
nikon_curve.c - read Nikon NTC/NCV files
Copyright 2004-2016 by Shawn Freeman, Udi Fuchs
This program reads in a Nikon NTC/NCV file,
interperates it's tone curve, and writes out a
simple ASCII file containing a table of interpolation
values. See the header file for more information.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
****************************************************/
//////////////////////////////////////////
//COMPILER CONTROLS
//////////////////////////////////////////
//Undef this if you don't want to use the stand-alone program
//This is mainly for debugging purposes
//#define _STAND_ALONE_
//Define this if you are using Microsoft Visual C++. This enables code to
//deal with the fact the MSVC does not support variable argument macros.
//#define __MSVC__
//the only remaining incompatibility between MSVC and gcc
#ifdef __MSVC__
#define vsnprintf _vsnprintf
#endif
//Define this if using with UFRaw
#define __WITH_UFRAW__
#ifdef __WITH_UFRAW__
#include "ufraw.h"
#else
#include "nikon_curve.h"
#include <stdio.h>
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define g_fopen fopen
#endif
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <stdarg.h> /* For variable argument lists */
/*************************************************
* Internal static functions
*************************************************/
/************************************************************
nc_message:
The Nikon Curve message handler.
code - Message code
format - The message to format
... - variable arguments
**************************************************************/
static void nc_message(int code, char *format, ...);
static void DEBUG_PRINT(char *format, ...);
/*******************************************************************
d3_np_fs:
Helper function for calculating and storing tridiagnol matrices.
Cubic spline calculations involve these types of matrices.
*********************************************************************/
static double *d3_np_fs(int n, double a[], double b[]);
/*******************************************************************
spline_cubic_set:
spline_cubic_set gets the second derivatives for the curve to be used in
spline construction
n = number of control points
t[] = x array
y[] = y array
ibcbeg = initial point condition (see function notes).
ybcbeg = beginning value depending on above flag
ibcend = end point condition (see function notes).
ybcend = end value depending on above flag
returns the y value at the given tval point
*********************************************************************/
static double *spline_cubic_set(int n, double t[], double y[], int ibcbeg,
double ybcbeg, int ibcend, double ybcend);
/*******************************************************************
spline_cubic_val:
spline_cubic_val gets a value from spline curve.
n = number of control points
t[] = x array
tval = x value you're requesting the data for, can be anywhere on the interval.
y[] = y array
ypp[] = second derivative array calculated by spline_cubic_set
ypval = first derivative value of requested point
yppval = second derivative value of requested point
returns the y value at the given tval point
*********************************************************************/
static double spline_cubic_val(int n, double t[], double tval, double y[],
double ypp[], double *ypval, double *yppval);
/************************************************************
SaveNikonCurveFile:
Saves out curves to a Nikon ntc or ncv file. This function
takes a single curve and uses defaults for the other curves.
Typically, the curve used is the tone curve.
curve - A NikonCurve structure. This is usually the tone curve
curve_type - The curve type (TONE_CURVE, RED_CURVE, etc.)
fileName - The filename.
filetype - Indicator for an NCV or NTC file.
NOTE: The only version tested is Nikon 4.1 anything
other than this may result in unpredictable behavior.
For now, the version passed in is ignored and is forced
to 4.1.
This function is just a helper function that allows the user
to just carry around a single curve.
**************************************************************/
#ifdef _STAND_ALONE_
static int SaveNikonCurveFile(CurveData *curve, int curve_type, char *outfile,
int filetype);
#endif
/*********************************************
SaveSampledNikonCurve:
Saves a sampling from a curve to text file to
be processed by UFRaw.
sample - Pointer to the sampled curve.
fileName - The filename.
**********************************************/
#ifdef _STAND_ALONE_
static int SaveSampledNikonCurve(CurveSample *sample, char *outfile);
#endif
/*****************************************************
FindTIFFOffset:
Moves the file pointer to the location
indicated by the TAG-TYPE pairing. This is meant just
as a helper function for this code. Uses elsewhere
may be limited.
file - Nikon File ptr
num_entries - Number of entries to search through
tiff_tag - The tiff tag to match.
tiff_type - The tiff type to match.
*******************************************************/
#ifdef _STAND_ALONE_
static int FindTIFFOffset(FILE *file, unsigned short num_entries,
unsigned short tiff_tag, unsigned short tiff_type);
#endif
/****************************************************
SampleToCameraCurve:
Transforms the curve generated by sampling the
spline interpolator into the curve that is used by
the camera.
This is a special function. While the function places
no special restrictions on sampling resolution or
output resolution, it should be noted that Nikon D70
camera curve is 4096 entries of 0-255.
If you intend on using this function as such, you should
set the sampling resolution and output resolution
accordingly.
curve - The Nikon curve to sample and transform.
*****************************************************/
#ifdef _STAND_ALONE_
static int SampleToCameraCurve(CurveData *curve, CurveSample *sample);
#endif
/****************************************
ConvertNikonCurveData:
The main driver. Takes a filename and
processes the curve, if possible.
fileName - The file to process.
*****************************************/
#ifdef _STAND_ALONE_
static int ConvertNikonCurveData(char *inFileName, char *outFileName,
unsigned int samplingRes, unsigned int outputRes);
#endif
/*******************************************************
RipNikonNEFData:
Gets Nikon NEF data. For now, this is just the tone
curve data. This is more of a helper function for running
in stand-alone. This function basically finds the correct
file offset, and then calls RipNikonNEFCurve.
infile - The input file
curve - data structure to hold data in.
sample_p - pointer to the curve sample reference.
can be NULL if curve sample is not needed.
********************************************************/
#ifdef _STAND_ALONE_
static int RipNikonNEFData(char *infile, CurveData *data,
CurveSample **sample_p);
#endif
/*******************************************************************************
Information regarding the file format.
Section Headers:
Order of Box Data: Left x, Right x, Midpoint x (gamma), Bottom y, Top y
Order of Anchor Data: Start x, Start y, Anchor 1 x, Anchor 1 y, ... , End x, End y
Anchor Point Data: This is aligned on 8 byte boundries. However, the section must
end on a 16 byte boundary, which means an 8 byte pad is added.
********************************************************************************/
//DEFINES FOR WRITING OUT DATA (for ntc/ncv files)
#define NCV_HEADER_SIZE 0x3E //Combined header length for an NCV file
#define NCV_SECOND_FILE_SIZE_OFFSET 0x3F //4 bytes (int). File size - NCV_header
#define NCV_UNKNOWN_HEADER_DATA 0x002 //2 bytes. (?)
#define NCV_SECOND_HEADER_LENGTH 23
#define NCV_FILE_TERMINATOR_LENGTH 23
#define NTC_FILE_HEADER_LENGTH 0x10 //16 bytes. Doesn't change
//This seemed to change when Nikon released an updated capture program
//from 4.1 to 4.2. This may be an int but not sure.
#define NCV_PATCH_OFFSET 0x3D //2 bytes(?)
#define NTC_PATCH_OFFSET 0x10 //2 bytes(?)
#define FILE_SIZE_OFFSET 0x12 //4 bytes (int). File size - header.
#define NTC_VERSION_OFFSET 0x16 //4 bytes (int).(?)
//9 byte pad(?)
//16 bytes. Another section header goes here.
//From here down repeats for every section
#define NTC_SECTION_TYPE_OFFSET 0x00 //4 bytes (int) (0,1,2,3)
#define NTC_UNKNOWN 0x05 //2 bytes. Doesn't change but not sure what they do (0x03ff)
#define NTC_UNKNOWN_DATA 0x3FF //
#define NTC_RED_COMPONENT_OFFSET 0x08 //4 bytes (int) (0-255)
#define NTC_GREEN_COMPONENT_OFFSET 0x0C //4 bytes (int) (0-255)
#define NTC_BLUE_COMPONENT_OFFSET 0x0F //4 bytes (int) (0-255)
//12 byte pad all zeros(align to 16?)
#define NTC_RED_WEIGHT_OFFSET 0x1F //4 bytes (int) (0-255)
#define NTC_GREEN_WEIGHT_OFFSET 0x23 //4 bytes (int) (0-255)
#define NTC_BLUE_WEIGHT_OFFSET 0x27 //4 bytes (int) (0-255)
#define END_ANCHOR_DATA_PAD_LENGTH 0x08 //Always all zeros
#define NTC_SECTION_HEADER_LENGTH 0x10 //Doesn't change
//DEFINES FOR READING IN DATA
#define HEADER_SIZE 0x10 //First characters may be unicode Japanese?
#define NTC_BOX_DATA 0x5C //Start of box data
#define NTC_NUM_ANCHOR_POINTS 0x84 //Number of anchor points plus 2 for start and end points
#define NTC_ANCHOR_DATA_START 0x88 //Beginning of anchor point data
#define NCV_BOX_DATA 0x89 //Start of box data
#define NCV_NUM_ANCHOR_POINTS 0xB2 //Number of anchor points plus 2 for start and end points
#define NCV_ANCHOR_DATA_START 0xB5 //Beginning of anchor point data
//array indices to retrive data
#define PATCH_DATA 0
#define BOX_DATA 1
#define NUM_ANCHOR_POINTS 2
#define ANCHOR_DATA 3
//Some data sections sizes for calculating offsets
#define NEXT_SECTION_BOX_DATA_OFFSET 0x43 //after the anchor data, this is the offset to
//the beginning of the next section's box data
#define NUM_POINTS_TO_ANCHOR_OFFSET 0x03 //number of bytes from the number of anchor points
//byte to the start of anchor data.
//Nikon version defines
#define NIKON_VERSION_4_1 0x00000401
#define NIKON_PATCH_4 0x04ff
#define NIKON_PATCH_5 0x05ff
//Maximum resoltuion allowed due to space considerations.
#define MAX_RESOLUTION 65536
//////////////////////////////
//NEF/TIFF MACROS AND DEFINES
//////////////////////////////
#define TIFF_TAG_EXIF_OFFSET 34665
#define TIFF_TAG_MAKER_NOTE_OFFSET 37500
#define TIFF_TAG_CURVE_OFFSET 140
#define TIFF_TYPE_UNDEFINED 7
#define TIFF_TYPE_LONG 4
//Flags used to determine what file we're trying to process.
//Should only be used in standalone mode.
#ifdef _STAND_ALONE_
#define CURVE_MODE 0
#define NEF_MODE 1
#endif
/*************************************************
* Internal static data
*************************************************/
//file offsets for the different data in different file types
static const int FileOffsets[2][4] = {
{NTC_PATCH_OFFSET, NTC_BOX_DATA, NTC_NUM_ANCHOR_POINTS, NTC_ANCHOR_DATA_START},
{NCV_PATCH_OFFSET, NCV_BOX_DATA, NCV_NUM_ANCHOR_POINTS, NCV_ANCHOR_DATA_START},
};
//file header indicating ntc file
static const unsigned char NTCFileHeader[] = {0x9d, 0xdc, 0x7d, 0x00, 0x65, 0xd4,
0x11, 0xd1, 0x91, 0x94, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00
};
//file header indicating an ncv file
static const unsigned char NCVFileHeader[] = {0x40, 0xa9, 0x86, 0x7a, 0x1b, 0xe9,
0xd2, 0x11, 0xa9, 0x0a, 0x00, 0xaa, 0x00, 0xb1, 0xc1, 0xb7
};
//This is an additional header chunk at the beginning of the file
//There are some similarities between the headers, but not enough to fully crack.
//This does not appear to change.
static const unsigned char NCVSecondFileHeader[] = {0x01, 0x32, 0xa4, 0x76, 0xa2,
0x17, 0xd4, 0x11, 0xa9, 0x0a, 0x00, 0xaa, 0x00, 0xb1, 0xc1,
0xb7, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01
};
//This is the terminator of an NCV file. Again there are some similarites
//to other sections, but not enough for to crack what it means. However,
//it does not appear to change.
static const unsigned char NCVFileTerminator[] = {0x45, 0xd3, 0x0d, 0x77, 0xa3, 0x6e,
0x1e, 0x4e, 0xa4, 0xbe, 0xcf, 0xc1, 0x8e, 0xb5, 0xb7, 0x47,
0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01
};
//File section header. Only a one byte difference between this and an NTC file header
static const unsigned char FileSectionHeader[] = {0x9d, 0xdc, 0x7d, 0x03, 0x65, 0xd4,
0x11, 0xd1, 0x91, 0x94, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00
};
//file type header array
static const unsigned char *FileTypeHeaders[NUM_FILE_TYPES] = {
NTCFileHeader,
NCVFileHeader,
};
/**STANDALONE**/
#ifdef _STAND_ALONE_
//filenames
char exportFilename[1024];
char nikonFilename[1024];
unsigned int standalone_samplingRes = 65536;
unsigned int standalone_outputRes = 256;
unsigned int program_mode = CURVE_MODE;
/*******************************************
ProcessArgs:
Convenient function for processing the args
for the test runner.
********************************************/
static int ProcessArgs(int num_args, char *args[])
{
exportFilename[0] = '\0';
nikonFilename[0] = '\0';
int i;
for (i = 0; i < num_args; i++) {
if (strcmp(args[i], "-h") == 0 || strcmp(args[i], "-H") == 0 || num_args <= 1) {
printf("NikonCurveGenerator %s %s\n", NC_VERSION, NC_DATE);
printf("Written by Shawn Freeman\n");
printf("Thanks go out to Udi Fuchs, UFRaw, and GIMP :)\n\n");
printf("Usage:\n");
printf("-o Specify output file.\n");
printf("-sr Specify sampling resolution. Default is 65536.\n");
printf("-or Specify output resolution. Default is 256.\n\n");
printf("-nef Specify an NEF file to get tone curve data from.\n\n");
printf(" The -or and -sr options are ignored for NEF files\n\n");
printf("NOTE: If a resolution is not specified, a default one will be used.\n");
printf(" If the -o option is not specified, default files will be used.\n\n");
printf("Example:\n");
printf("%s -sr 65536 -or 256 curveFile -o exportFile\n", args[0]);
//signal that processing cannot occur
return NC_ERROR;
} else if (strcmp(args[i], "-o") == 0 || strcmp(args[i], "-O") == 0) {
i++;
strncpy(exportFilename, args[i], 1023);
exportFilename[1023] = '\0';
} else if (strcmp(args[i], "-sr") == 0) {
i++;
standalone_samplingRes = atoi(args[i]);
if (standalone_samplingRes < 1) {
nc_message(NC_WARNING, "WARNING: Sampling resolution must be"
">= 1! Using default of 65535.\n");
}
} else if (strcmp(args[i], "-or") == 0) {
i++;
standalone_outputRes = atoi(args[i]);
if (standalone_outputRes < 1) {
nc_message(NC_WARNING, "WARNING: Output resolution must be"
">= 1! Using default of 256.\n");
}
} else if (strcmp(args[i], "-nef") == 0) {
i++;
program_mode = NEF_MODE;
strncpy(nikonFilename, args[i], 1023);
nikonFilename[1023] = '\0';
}
//don't load argument 0
else if (i != 0) {
//consider this the file name to load
strncpy(nikonFilename, args[i], 1023);
nikonFilename[1023] = '\0';
}
}
if (strlen(exportFilename) == 0) {
//set it to have a default output file name
strncpy(exportFilename, nikonFilename, 1023);
strncat(exportFilename, "_CURVE_OUTPUT.txt", 1023);
exportFilename[1023] = '\0';
}
return NC_SUCCESS;
}
#endif //End STAND_ALONE
/************************************************************
nc_message_handler:
The Nikon Curve message handler. Udi Fuchs created this
to make the error handling consistent acros the code.
code - Message code
message - The message
**************************************************************/
static void nc_message(int code, char *format, ...)
{
char message[256];
va_list ap;
va_start(ap, format);
vsnprintf(message, 255, format, ap);
message[255] = '\0';
va_end(ap);
#ifdef _STAND_ALONE_ //if we're running standalone mode
code = code;
fprintf(stderr, "%s", message);
fflush(stderr);
#else
#ifdef __WITH_UFRAW__ //and if compiling with UFRAW
if (code == NC_SET_ERROR) {
ufraw_message(UFRAW_SET_ERROR, message);
} else {
ufraw_message(code, message);
}
#else //else, just print out the errors normally
code = code;
g_printerr("%s", message);
#endif //End WITH_UFRAW
#endif //End STAND_ALONE
}
static void DEBUG_PRINT(char *format, ...)
{
#ifdef _DEBUG
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
fflush(stderr);
va_end(ap);
#else
format = format;
#endif
}
/* nc_merror(): Handle memory allocaltion errors */
static void nc_merror(void *ptr, char *where)
{
if (ptr) return;
#ifdef __WITH_UFRAW__
g_error("Out of memory in %s\n", where);
#else
fprintf(stderr, "Out of memory in %s\n", where);
exit(1);
#endif
}
static size_t nc_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t num = fread(ptr, size, nmemb, stream);
if (num != nmemb)
nc_message(NC_WARNING, "WARNING: nc_fread %d != %d\n", num, nmemb);
return num;
}
static size_t nc_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t num = fwrite(ptr, size, nmemb, stream);
if (num != nmemb)
nc_message(NC_WARNING, "WARNING: nc_fwrite %d != %d\n", num, nmemb);
return num;
}
// Assert something at compile time (must use this inside a function);
// works because compilers won't let us declare negative-length arrays.
#define STATIC_ASSERT(cond) \
{ (void)((int (*)(char failed_static_assertion[(cond)?1:-1]))0); }
/***********************************************************************
isBigEndian:
Determines if the machine we are running on is big endian or not.
************************************************************************/
static int isBigEndian()
{
STATIC_ASSERT(sizeof(short) == 2);
union {
unsigned char c[2];
short x;
} EndianTest;
EndianTest.c[0] = 1;
EndianTest.c[1] = 0;
return (EndianTest.x != 1);
}
/***********************************************************************
ShortVal:
Convert short int (16 bit) from little endian to machine endianess.
************************************************************************/
static short ShortVal(short s)
{
STATIC_ASSERT(sizeof(short) == 2);
if (isBigEndian()) {
unsigned char b1, b2;
b1 = s & 255;
b2 = (s >> 8) & 255;
return (b1 << 8) + b2;
} else
return s;
}
/***********************************************************************
LongVal:
Convert long int (32 bit) from little endian to machine endianess.
************************************************************************/
static int LongVal(int i)
{
STATIC_ASSERT(sizeof(int) == 4);
if (isBigEndian()) {
unsigned char b1, b2, b3, b4;
b1 = i & 255;
b2 = (i >> 8) & 255;
b3 = (i >> 16) & 255;
b4 = (i >> 24) & 255;
return ((int)b1 << 24) + ((int)b2 << 16) + ((int)b3 << 8) + b4;
} else
return i;
}
/***********************************************************************
DoubleVal:
Convert double from little endian to machine endianess.
************************************************************************/
static double DoubleVal(double d)
{
STATIC_ASSERT(sizeof(double) == 8);
if (isBigEndian()) {
union {
double d;
unsigned char b[8];
} dat1, dat2;
dat1.d = d;
dat2.b[0] = dat1.b[7];
dat2.b[1] = dat1.b[6];
dat2.b[2] = dat1.b[5];
dat2.b[3] = dat1.b[4];
dat2.b[4] = dat1.b[3];
dat2.b[5] = dat1.b[2];
dat2.b[6] = dat1.b[1];
dat2.b[7] = dat1.b[0];
return dat2.d;
} else
return d;
}
//**********************************************************************
//
// Purpose:
//
// D3_NP_FS factors and solves a D3 system.
//
// Discussion:
//
// The D3 storage format is used for a tridiagonal matrix.
// The superdiagonal is stored in entries (1,2:N), the diagonal in
// entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the
// original matrix is "collapsed" vertically into the array.
//
// This algorithm requires that each diagonal entry be nonzero.
// It does not use pivoting, and so can fail on systems that
// are actually nonsingular.
//
// Example:
//
// Here is how a D3 matrix of order 5 would be stored:
//
// * A12 A23 A34 A45
// A11 A22 A33 A44 A55
// A21 A32 A43 A54 *
//
// Modified:
//
// 07 January 2005 Shawn Freeman (pure C modifications)
// 15 November 2003 John Burkardt
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the linear system.
//
// Input/output, double A[3*N].
// On input, the nonzero diagonals of the linear system.
// On output, the data in these vectors has been overwritten
// by factorization information.
//
// Input, double B[N], the right hand side.
//
// Output, double D3_NP_FS[N], the solution of the linear system.
// This is NULL if there was an error because one of the diagonal
// entries was zero.
//
static double *d3_np_fs(int n, double a[], double b[])
{
int i;
double *x;
double xmult;
//
// Check.
//
for (i = 0; i < n; i++) {
if (a[1 + i * 3] == 0.0E+00) {
return NULL;
}
}
x = (double *)calloc(n, sizeof(double));
nc_merror(x, "d3_np_fs");
for (i = 0; i < n; i++) {
x[i] = b[i];
}
for (i = 1; i < n; i++) {
xmult = a[2 + (i - 1) * 3] / a[1 + (i - 1) * 3];
a[1 + i * 3] = a[1 + i * 3] - xmult * a[0 + i * 3];
x[i] = x[i] - xmult * x[i - 1];
}
x[n - 1] = x[n - 1] / a[1 + (n - 1) * 3];
for (i = n - 2; 0 <= i; i--) {
x[i] = (x[i] - a[0 + (i + 1) * 3] * x[i + 1]) / a[1 + i * 3];
}
return x;
}
//**********************************************************************
//
// Purpose:
//
// SPLINE_CUBIC_SET computes the second derivatives of a piecewise cubic spline.
//
// Discussion:
//
// For data interpolation, the user must call SPLINE_SET to determine
// the second derivative data, passing in the data to be interpolated,
// and the desired boundary conditions.
//
// The data to be interpolated, plus the SPLINE_SET output, defines
// the spline. The user may then call SPLINE_VAL to evaluate the
// spline at any point.
//
// The cubic spline is a piecewise cubic polynomial. The intervals
// are determined by the "knots" or abscissas of the data to be
// interpolated. The cubic spline has continous first and second
// derivatives over the entire interval of interpolation.
//
// For any point T in the interval T(IVAL), T(IVAL+1), the form of
// the spline is
//
// SPL(T) = A(IVAL)
// + B(IVAL) * ( T - T(IVAL) )
// + C(IVAL) * ( T - T(IVAL) )**2
// + D(IVAL) * ( T - T(IVAL) )**3
//
// If we assume that we know the values Y(*) and YPP(*), which represent
// the values and second derivatives of the spline at each knot, then
// the coefficients can be computed as:
//
// A(IVAL) = Y(IVAL)
// B(IVAL) = ( Y(IVAL+1) - Y(IVAL) ) / ( T(IVAL+1) - T(IVAL) )
// - ( YPP(IVAL+1) + 2 * YPP(IVAL) ) * ( T(IVAL+1) - T(IVAL) ) / 6
// C(IVAL) = YPP(IVAL) / 2
// D(IVAL) = ( YPP(IVAL+1) - YPP(IVAL) ) / ( 6 * ( T(IVAL+1) - T(IVAL) ) )
//
// Since the first derivative of the spline is
//
// SPL'(T) = B(IVAL)
// + 2 * C(IVAL) * ( T - T(IVAL) )
// + 3 * D(IVAL) * ( T - T(IVAL) )**2,
//
// the requirement that the first derivative be continuous at interior
// knot I results in a total of N-2 equations, of the form:
//
// B(IVAL-1) + 2 C(IVAL-1) * (T(IVAL)-T(IVAL-1))
// + 3 * D(IVAL-1) * (T(IVAL) - T(IVAL-1))**2 = B(IVAL)
//
// or, setting H(IVAL) = T(IVAL+1) - T(IVAL)
//
// ( Y(IVAL) - Y(IVAL-1) ) / H(IVAL-1)
// - ( YPP(IVAL) + 2 * YPP(IVAL-1) ) * H(IVAL-1) / 6
// + YPP(IVAL-1) * H(IVAL-1)
// + ( YPP(IVAL) - YPP(IVAL-1) ) * H(IVAL-1) / 2
// =
// ( Y(IVAL+1) - Y(IVAL) ) / H(IVAL)
// - ( YPP(IVAL+1) + 2 * YPP(IVAL) ) * H(IVAL) / 6
//
// or
//
// YPP(IVAL-1) * H(IVAL-1) + 2 * YPP(IVAL) * ( H(IVAL-1) + H(IVAL) )
// + YPP(IVAL) * H(IVAL)
// =
// 6 * ( Y(IVAL+1) - Y(IVAL) ) / H(IVAL)
// - 6 * ( Y(IVAL) - Y(IVAL-1) ) / H(IVAL-1)
//
// Boundary conditions must be applied at the first and last knots.
// The resulting tridiagonal system can be solved for the YPP values.
//
// Modified:
//
// 07 January 2005 Shawn Freeman (pure C modifications)
// 06 February 2004 John Burkardt
//
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of data points. N must be at least 2.
// In the special case where N = 2 and IBCBEG = IBCEND = 0, the
// spline will actually be linear.
//
// Input, double T[N], the knot values, that is, the points were data is
// specified. The knot values should be distinct, and increasing.
//
// Input, double Y[N], the data values to be interpolated.
//
// Input, int IBCBEG, left boundary condition flag:
// 0: the cubic spline should be a quadratic over the first interval;
// 1: the first derivative at the left endpoint should be YBCBEG;
// 2: the second derivative at the left endpoint should be YBCBEG.
//
// Input, double YBCBEG, the values to be used in the boundary
// conditions if IBCBEG is equal to 1 or 2.
//
// Input, int IBCEND, right boundary condition flag:
// 0: the cubic spline should be a quadratic over the last interval;
// 1: the first derivative at the right endpoint should be YBCEND;
// 2: the second derivative at the right endpoint should be YBCEND.
//
// Input, double YBCEND, the values to be used in the boundary
// conditions if IBCEND is equal to 1 or 2.
//
// Output, double SPLINE_CUBIC_SET[N], the second derivatives of the cubic spline.
//
static double *spline_cubic_set(int n, double t[], double y[], int ibcbeg,
double ybcbeg, int ibcend, double ybcend)
{
double *a;
double *b;
int i;
double *ypp;
//
// Check.
//
if (n <= 1) {
nc_message(NC_SET_ERROR, "spline_cubic_set() error: "
"The number of data points must be at least 2.\n");
return NULL;
}
for (i = 0; i < n - 1; i++) {
if (t[i + 1] <= t[i]) {
nc_message(NC_SET_ERROR, "spline_cubic_set() error: "
"The knots must be strictly increasing, but "
"T(%u) = %e, T(%u) = %e\n", i, t[i], i + 1, t[i + 1]);
return NULL;
}
}
a = (double *)calloc(3 * n, sizeof(double));
nc_merror(a, "spline_cubic_set");
b = (double *)calloc(n, sizeof(double));
nc_merror(b, "spline_cubic_set");
//
// Set up the first equation.
//
if (ibcbeg == 0) {
b[0] = 0.0E+00;
a[1 + 0 * 3] = 1.0E+00;
a[0 + 1 * 3] = -1.0E+00;
} else if (ibcbeg == 1) {
b[0] = (y[1] - y[0]) / (t[1] - t[0]) - ybcbeg;
a[1 + 0 * 3] = (t[1] - t[0]) / 3.0E+00;
a[0 + 1 * 3] = (t[1] - t[0]) / 6.0E+00;
} else if (ibcbeg == 2) {
b[0] = ybcbeg;
a[1 + 0 * 3] = 1.0E+00;
a[0 + 1 * 3] = 0.0E+00;
} else {
nc_message(NC_SET_ERROR, "spline_cubic_set() error: "
"IBCBEG must be 0, 1 or 2. The input value is %u.\n", ibcbeg);
free(a);
free(b);
return NULL;
}
//
// Set up the intermediate equations.
//
for (i = 1; i < n - 1; i++) {
b[i] = (y[i + 1] - y[i]) / (t[i + 1] - t[i])
- (y[i] - y[i - 1]) / (t[i] - t[i - 1]);
a[2 + (i - 1) * 3] = (t[i] - t[i - 1]) / 6.0E+00;
a[1 + i * 3] = (t[i + 1] - t[i - 1]) / 3.0E+00;
a[0 + (i + 1) * 3] = (t[i + 1] - t[i]) / 6.0E+00;
}
//
// Set up the last equation.
//
if (ibcend == 0) {
b[n - 1] = 0.0E+00;
a[2 + (n - 2) * 3] = -1.0E+00;
a[1 + (n - 1) * 3] = 1.0E+00;
} else if (ibcend == 1) {
b[n - 1] = ybcend - (y[n - 1] - y[n - 2]) / (t[n - 1] - t[n - 2]);
a[2 + (n - 2) * 3] = (t[n - 1] - t[n - 2]) / 6.0E+00;
a[1 + (n - 1) * 3] = (t[n - 1] - t[n - 2]) / 3.0E+00;
} else if (ibcend == 2) {
b[n - 1] = ybcend;
a[2 + (n - 2) * 3] = 0.0E+00;
a[1 + (n - 1) * 3] = 1.0E+00;
} else {
nc_message(NC_SET_ERROR, "spline_cubic_set() error: "
"IBCEND must be 0, 1 or 2. The input value is %u", ibcend);
free(a);
free(b);
return NULL;
}
//
// Solve the linear system.
//
if (n == 2 && ibcbeg == 0 && ibcend == 0) {
ypp = (double *)calloc(2, sizeof(double));
nc_merror(ypp, "spline_cubic_set");
ypp[0] = 0.0E+00;
ypp[1] = 0.0E+00;
} else {
ypp = d3_np_fs(n, a, b);
if (!ypp) {
nc_message(NC_SET_ERROR, "spline_cubic_set() error: "
"The linear system could not be solved.\n");
free(a);
free(b);
return NULL;
}
}
free(a);
free(b);
return ypp;
}
//**********************************************************************
//
// Purpose:
//
// SPLINE_CUBIC_VAL evaluates a piecewise cubic spline at a point.
//
// Discussion:
//
// SPLINE_CUBIC_SET must have already been called to define the values of YPP.
//
// For any point T in the interval T(IVAL), T(IVAL+1), the form of
// the spline is
//
// SPL(T) = A
// + B * ( T - T(IVAL) )
// + C * ( T - T(IVAL) )**2
// + D * ( T - T(IVAL) )**3
//
// Here:
// A = Y(IVAL)
// B = ( Y(IVAL+1) - Y(IVAL) ) / ( T(IVAL+1) - T(IVAL) )
// - ( YPP(IVAL+1) + 2 * YPP(IVAL) ) * ( T(IVAL+1) - T(IVAL) ) / 6
// C = YPP(IVAL) / 2
// D = ( YPP(IVAL+1) - YPP(IVAL) ) / ( 6 * ( T(IVAL+1) - T(IVAL) ) )
//
// Modified:
//
// 07 January 2005 Shawn Freeman (pure C modifications)
// 04 February 1999 John Burkardt
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int n, the number of knots.
//
// Input, double Y[N], the data values at the knots.
//
// Input, double T[N], the knot values.
//
// Input, double TVAL, a point, typically between T[0] and T[N-1], at
// which the spline is to be evalulated. If TVAL lies outside
// this range, extrapolation is used.
//
// Input, double Y[N], the data values at the knots.
//
// Input, double YPP[N], the second derivatives of the spline at
// the knots.
//
// Output, double *YPVAL, the derivative of the spline at TVAL.
//
// Output, double *YPPVAL, the second derivative of the spline at TVAL.
//
// Output, double SPLINE_VAL, the value of the spline at TVAL.
//
static double spline_cubic_val(int n, double t[], double tval, double y[],
double ypp[], double *ypval, double *yppval)
{
double dt;
double h;
int i;
int ival;
double yval;
//
// Determine the interval [ T(I), T(I+1) ] that contains TVAL.
// Values below T[0] or above T[N-1] use extrapolation.
//
ival = n - 2;
for (i = 0; i < n - 1; i++) {
if (tval < t[i + 1]) {
ival = i;
break;
}
}
//
// In the interval I, the polynomial is in terms of a normalized
// coordinate between 0 and 1.
//
dt = tval - t[ival];
h = t[ival + 1] - t[ival];