Changeset 4239
- Timestamp:
- Jun 13, 2005, 12:41:59 PM (21 years ago)
- Location:
- trunk/doc/pslib
- Files:
-
- 2 edited
-
ChangeLogSDRS.tex (modified) (2 diffs)
-
psLibSDRS.tex (modified) (22 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/doc/pslib/ChangeLogSDRS.tex
r4208 r4239 1 %%% $Id: ChangeLogSDRS.tex,v 1.13 5 2005-06-10 03:56:03price Exp $1 %%% $Id: ChangeLogSDRS.tex,v 1.136 2005-06-13 22:41:59 price Exp $ 2 2 3 3 \subsection{Changes from version 00 to version 01} … … 697 697 \item Updating section on thread safety, and added \code{psMutex}. 698 698 \item add \code{psFitsOpenFD()} 699 \end{itemize} 699 \item Removed example destructor function, since the current 700 implementation does not follow it, but achieves the same result. 701 \item Reorganised document: collections and mathematical structures 702 are now separate sections; metadata, pixels lists and bit sets are 703 collections; type information goes into system utilities. 704 \end{itemize} -
trunk/doc/pslib/psLibSDRS.tex
r4208 r4239 1 %%% $Id: psLibSDRS.tex,v 1.27 4 2005-06-10 03:56:03price Exp $1 %%% $Id: psLibSDRS.tex,v 1.275 2005-06-13 22:41:59 price Exp $ 2 2 \documentclass[panstarrs,spec]{panstarrs} 3 3 … … 66 66 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 67 67 68 \section{Introduction }68 \section{Introduction and policies} 69 69 70 70 This document describes the Pan-STARRS Image Processing Pipeline (IPP) … … 163 163 memory management functions). 164 164 165 \subsection{ Conventions}165 \subsection{Angles} 166 166 167 167 To maintain consistency throughout the library, angles shall be … … 623 623 \end{prototype} 624 624 % 625 The corresponding callback s have the following form:625 The corresponding callback functions have the following form: 626 626 % 627 627 \begin{datatype} 628 628 typedef psMemId (*psMemAllocCallback)(const psMemBlock *ptr); 629 \end{datatype} 629 typedef psMemId (*psMemFreeCallback)(const psMemBlock *ptr); 630 \end{datatype} 631 632 and are set with the following functions: 630 633 631 634 \begin{prototype} 632 635 psMemAllocCallback psMemAllocCallbackSet(psMemAllocCallback func); 633 \end{prototype}634 635 \begin{datatype}636 typedef psMemId (*psMemFreeCallback)(const psMemBlock *ptr);637 \end{datatype}638 639 \begin{prototype}640 636 psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func); 641 637 psMemId psMemGetId(void); … … 744 740 corresponding constructors and destructors. The destructors are 745 741 private functions used only by the memory management system. 746 Instances of, for example, \code{ps MyType} should be constructed using747 \code{ps MyTypeAlloc()} calls, and are destroyed using the basic748 \code{psFree} function, which calls \code{p sMyTypeFree()} to free the742 Instances of, for example, \code{psSomeType} should be constructed using 743 \code{psSomeTypeAlloc()} calls, and are destroyed using the basic 744 \code{psFree} function, which calls \code{p_psSomeTypeFree()} to free the 749 745 components of the structure, but leaves the task of freeing the 750 746 structure to \code{psFree}. The allocator will allocate the required … … 754 750 The existence of complicated structures which include pointers to 755 751 other structures require that we lay out a rule regarding destructors 756 (i.e., \code{psMyTypeFree}) and reference counters. Simply put, 757 \textit{the destructor for every structure should only call 758 \code{psFree} if \code{refCounter == 1}; otherwise, it decrements the 759 reference counter and returns.} An example destructor is shown below: 760 761 \filbreak 762 \begin{verbatim} 763 void psMyTypeFree(psMyType *myType) 764 { 765 /* data is not defined */ 766 if (psMemGetRefCounter(myType) < 1) { 767 return; 768 } 769 /* Only call psFree if reference counter is 1 */ 770 if (psMemGetRefCounter(myType) == 1) { 771 psSubFree (myType->sub); 772 psFree(myType); 773 return; 774 } 775 /* Otherwise, decrement the reference counter only */ 776 psMemDecrRefCounter(myType); 777 } 778 \end{verbatim} 779 780 Note that the element of \code{myType}, \code{myType.sub} is 781 explicitly freed with its associated destructor. If this element 782 points to a data block with multiple references, this call would only 783 decrement the counter. 784 785 \subsection{Conventions adopted} 786 787 Only pointers allocated with the PSLib memory functions are compatible 788 with the various PSLib container types (e.g., \code{psList, 752 and reference counters. Simply put, \textit{the destructor for every 753 structure should only free the structure if the \code{refCounter == 754 1}; otherwise, it decrements the reference counter and returns.} 755 756 \subsubsection{Conventions adopted for pointers} 757 758 Only pointers to memory allocated with the PSLib memory functions are 759 compatible with the various PSLib container types (e.g., \code{psList, 789 760 psMetadata}), because the functions working with the container types 790 search for the attached \code{psMemBlock}. If a pointer allocated791 with another memory system (e.g., the system \code{malloc}), or 792 generated by offsetting from another pointer that was allocated with 793 \code{psAlloc}, is used with PSLib, the PSLib functions would falsely 794 determine that memory is corrupted, because of the missing761 search for the attached \code{psMemBlock}. If a pointer to memory 762 allocated with another memory system (e.g., the system \code{malloc}), 763 or generated by offsetting from another pointer that was allocated 764 with \code{psAlloc}, is used with PSLib, the PSLib functions would 765 falsely determine that memory is corrupted, because of the missing 795 766 \code{psMemBlock}. 796 767 797 768 To pilot our way through the potential confusion, instead of calling 798 769 all pointers (of unspecified type) a ``\code{void*}'', we adopt a 799 convention, both in this document and in the source, of referring to a800 pointer that has a \code{psMemBlock} attached as a \code{psPtr}: 801 770 convention, both in this document and to be used in the source, of 771 referring to a pointer that has a \code{psMemBlock} attached as a 772 \code{psPtr}: 802 773 \begin{datatype} 803 774 typedef void* psPtr; 804 \end{data Type}775 \end{datatype} 805 776 806 777 For the same reason, we also adopt a convention of referring to a string 807 778 that has a \code{psMemBlock} attached as a \code{psString}: 808 809 779 \begin{datatype} 810 780 typedef char* psString; … … 817 787 \code{psStringCopy} or \code{psStringNCopy}). 818 788 819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 820 821 \subsection{Threads} 822 823 As pointed out earlier, PSLib makes no guarantees for thread-safety 824 outside of the memory management functions. Nevertheless, the following 825 facilities are provided as a convenience to the user. 826 827 Each of the data structures classified as a ``collection'' (i.e., 828 \code{psList, psHash, psMetadata, psArray, psPixels, psVector, 829 psBitSet}) and \code{psImage} shall contain an additional member, 830 \code{void *lock}, which provides a place for the user to carry around 831 a mutex or semaphore. This is provided so that the user doesn't have 832 to pass around both the structure and a mutex, or wrap PSLib 833 structures in their own thread-safe structures that contain a mutex. 834 835 We also define the following conveniences: 836 \begin{datatype} 837 typedef struct { 838 pthread_mutex_t mutex; 839 } psMutex; 840 \end{datatype} 841 842 \begin{prototype} 843 psMutex *psMutexAlloc(void); 844 bool psMutexLock(psMutex *mutex); 845 bool psMutexUnlock(psMutex *mutex); 846 \end{prototype} 847 848 \code{psMutex} simply wraps a POSIX thread mutex (this is necessary in 849 order to use the PS memory management system). 850 851 \code{psMutexAlloc} shall allocate memory for a \code{psMutex}, and 852 initialise the mutex. \code{psMutexLock} shall lock the mutex in 853 \code{thread}, and \code{psMutexUnlock} shall unlock the mutex in 854 \code{thread}. No distinction is made between read and write locks. 855 856 These functions, in the interests of speed, should be implemented as 857 preprocessor macros. 858 859 These functions should only be defined if \code{_REENTRANT} is 860 defined, and poisoned otherwise. 861 862 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 863 864 \subsection{Tracing and Logging} 865 866 This section defines the \PS{} Tracing and Logging APIs; the former 867 refers to debug information that we wish to be able to turn on and off 868 without recompiling (it will \emph{not} be available in production 869 code); the latter means information about the processing that must be 870 collected and saved, even in the production system. We envision that 871 extensive use will be made of \code{psTrace} throughout the \PS{} 872 code. 873 874 \subsubsection{Tracing APIs} 875 \hlabel{psTrace} 876 877 A code-tracing facility should allow the programmer to place messages 878 in the code which, when called, will print some useful information 879 about the containing block of code. Ideally, different messages may 880 be specified to have different levels (of severity or interest). For 881 a given run of the program, the level of interest should be set to 882 provide more or less feedback, depending on the needs of the 883 programmer. In a typical situation, low-level messages would be 884 placed generously throughout the code, indicating the flow of the 885 program. Higher-level messages would be placed in a limited number of 886 special locations, such as the start of major code segments or where a 887 particularly unusual condition is met. Top-level messages would be 888 placed in code triggered under serious error conditions. A normal run 889 of the program would have the trace messages printed only for the 890 top-level. If the user needs to dig deeper into the code, the trace 891 level should be set lower, and the more detailed messages could be 892 examined. In a case of a serious, poorly-understood problem with the 893 code, the trace threshold would be placed to the bottom and the 894 lowest-level step-by-step messages would be printed. 895 896 The PSLib tracing facility provides the above functionality, along 897 with the ability to assign different trace levels to messages from 898 different software components. Each trace message, when placed in the 899 code, is assigned to be part of a specific tracing 'facility', defined 900 in more detail below. The trace level for that specific message is 901 also set when the message is placed. Each facility may have its trace 902 level set independently. Thus, it is possible to request detailed 903 trace output for one facility while minimizing the verbosity of the 904 trace output from the rest of the program. 905 906 The trace facilities consist of a hierarchy of names. A trace 907 facility is defined by a string consisting of words separated by dots, 908 with a hierarchy equivalent to that of UNIX directory names. The 909 top-level facility is simply \code{'.'} (one dot). The next level 910 would be \code{'.A'}, followed by \code{.A.B}, and so on. The 911 relationship is seen in two ways. First, a facility inherits the 912 trace level of its parent unless explicitly specified. Second, the 913 hierarchy is used to format the listing of the trace facilities so 914 that they are easy to read. The first of these rules provides a 915 mechanism to define the default trace levels for any facility even if 916 it has not been registered explicitly since all named facilities are 917 implicitly children of the top level facility (\code{.}). The second 918 rule is simply an organizational technique to make the listing of 919 facility information clear. In specifying a facility, the leading 920 dot shall be optional, as a convenience to the user. 921 922 The API to place a trace message in the code, and simultaneously set 923 its trace level and facility, is: 924 % 925 \begin{prototype} 926 void psTrace(const char *facil, int level, const char *fmt,...); 927 void psTraceV(const char *facil, int level, const char *fmt, va_list ap); 928 \end{prototype} 929 % 930 where the \code{fmt} argument is a printf-style formatting code 931 followed by possible arguments to that formatting statement, to be 932 implemented using the \code{vprintf} functions. This command 933 specifies the name of the facility to which the message belongs 934 (\code{facil}), the trace level for this message in that facility 935 (\code{level}) and the message itself. The \code{psTraceV} version of 936 the command accepts a \code{va_list} argument list rather than a 937 variable number of arguments. 938 939 The trace level for any facility may be set at any time with the 940 following function: 941 % 942 \begin{prototype} 943 int psTraceSetLevel(const char *facil, int level); 944 \end{prototype} 945 % 946 where \code{level} specifies the current trace level for the facility 947 named by \code{facil}. The currently defined trace level for a given 948 facility may be determined by the function: 949 % 950 \begin{prototype} 951 int psTraceGetLevel(const char *facil); 952 \end{prototype} 953 % 954 which returns the trace level of the named facility following the 955 rules specified above. A specified trace message (identified by 956 \code{psTrace}) must be printed if and only if 957 \code{psTraceGetLevel(facil)} returns a value greater than or equal to 958 the value of \code{level} for that message. That is, a larger 959 number for the trace level corresponds to lower-level statements, and 960 hence is more verbose. 961 962 PSLib includes a utility function for examining the current tracing 963 levels of all facilities: 964 % 965 \begin{prototype} 966 void psTracePrintLevels(void); 967 \end{prototype} 968 % 969 This function prints the hierarchy of trace facilities along with the 970 current trace level for each facility. For example, a particular 971 program may have a few facilities defined, along with their trace 972 levels. A call to \code{psTracePrintLevels} may produce a listing 973 which appears as: 974 \begin{verbatim} 975 . 0 976 .IPP 0 977 .IPP.debias 1 978 .IPP.flatten 1 979 .IPP.flatten.divide 2 980 .IPP.object.findpeak 1 981 .IPP.object.getsky 1 982 \end{verbatim} 983 984 Considering the same program, the programmer might place a variety of 985 trace messages throughout the \code{flatten} portion of the code with 986 different types of messages, such as: 987 % 988 \begin{verbatim} 989 psTrace("IPP.flatten", 2, "starting flatten function\n"); 990 psTrace("IPP.flatten", 0, "flat-field image is \%s\n", filename); 991 psTrace("IPP.flatten.divide", 2, "doing the divide\n"); 992 psTrace("IPP.flatten.divide", 3, "trying the loop, i = \%d\n", i); 993 psTrace("IPP.flatten.divide", 1, "got an invalid pixel value (NaN) at \%d,\%d\n"); 994 psTrace("IPP.flatten.divide", 2, "divide is done\n"); 995 \end{verbatim} 996 % 997 Under the trace levels set above, if the code actually reached each of 998 these trace messages, the following messages would be printed: 999 % 1000 \begin{verbatim} 1001 flat-field image is foo.fits 1002 doing the divide 1003 got an invalid pixel value (NaN) at 500,20 1004 divide is done 1005 \end{verbatim} 1006 % 1007 while these two would not be printed because their facility level was 1008 too low: 1009 % 1010 \begin{verbatim} 1011 starting flatten function 1012 trying the loop, i = 0 1013 trying the loop, i = 1 1014 trying the loop, i = 2 1015 ... 1016 \end{verbatim} 1017 % 1018 1019 The availability of the tracing facility at run-time, must be decided 1020 at compilation: If the C pre-processor macro \code{PS_NO_TRACE} is 1021 defined, all trace code must be replaced by empty space so that none 1022 of the code is compiled. This can be implemented via macro front-ends 1023 to private versions of the user APIs. In addition, a function 1024 \code{bool psTraceReset(void)} will free memory used by \code{psTrace} 1025 functions, effectively resetting all trace levels to 0. 1026 1027 The trace may optionally be written to a file or other output 1028 destination with \code{psTraceSetDestination}: 1029 \begin{prototype} 1030 void psTraceSetDestination(int fd); 1031 \end{prototype} 1032 If the \code{fd} is 0, then the trace is sent to standard output, 1033 otherwise it is sent to the specified file descriptor. A call to 1034 \code{psTraceSetDestination} automatically closes the file descriptor. 1035 1036 The corresponding function 1037 \begin{prototype} 1038 int psTraceGetDestination(); 1039 \end{prototype} 1040 returns the current trace destination file descriptor. If the 1041 destination has not been defined by the user, the descriptor for 1042 \code{stdout} is returned. 1043 1044 The trace output format is controlled with the function: 1045 % 1046 \begin{prototype} 1047 bool psTraceSetFormat(const char *fmt); 1048 \end{prototype} 1049 % 1050 which expects a string consisting of the letters \code{H} (host), 1051 \code{L} (level), \code{M} (message), \code{N} (name), and \code{T} 1052 (time). The default is \code{THLNM}, which produces trace messages in 1053 the form: 1054 \begin{verbatim} 1055 YYYY-MM-DD hh:mm:ssZ | hostname | L | name 1056 The message goes here 1057 and is indented by 4 spaces. 1058 \end{verbatim} 1059 where \code{YYYY}, \code{MM}, \code{DD}, \code{hh}, \code{mm}, and 1060 \code{ss} are the year, month (Jan is 01), day of the month, hours 1061 (0--23), minutes, and seconds when the trace message was received. Note 1062 that the timestamp is in ISO order, and that the timezone is GMT 1063 (hence the \code{Z}). The \code{hostname} is returned by 1064 \code{gethostname}, \code{L} is a character associated with the level 1065 (\code{A}, \code{E}, \code{W}, and \code{I} for \code{PS_LOG_ABORT}, 1066 \code{PS_LOG_ERROR}, \code{PS_LOG_WARN}, and \code{PS_LOG_INFO} 1067 respectively. Other levels are represented numerically (\code{5} 1068 etc.). The other two fields, \code{facil} and \code{msg}, are the 1069 arguments to \code{psTrace}. The \code{msg} is placed on a new line 1070 (allowing the \code{name} to fill the rest of the previous line), 1071 with each line indented by 4 spaces. An example message is: 1072 % 1073 \begin{verbatim} 1074 2004:02:24 20:14:18Z | alibaba.IfA.Hawaii.Edu | I | example.utils.helloWorld 1075 Hello world, 1076 it's me calling. 1077 \end{verbatim} 1078 % 1079 The possible order of the format entries is fixed and not determined 1080 by the order of the letters used in \code{psTraceSetFormat}. Selecting 1081 an output format with fewer than the complete set of 5 entries simply 1082 removes those entries from the output messages. 1083 1084 Specifying a \code{fmt} of \code{NULL} turns off logging (equivalent 1085 to calling \code{psLogSetDestination(PS_LOG_TO_NONE)}, whereas if the 1086 \code{fmt} is \code{""}, then the format reverts to the default. 1087 1088 \subsubsection{Message Logging} 1089 \hlabel{psLogMsg} 1090 1091 Message logging is similar in some respects to tracing. Like trace 1092 messages, log messages are placed in the code at various locations to 1093 provide output describing the current state of the program. Like 1094 the PSLib trace facility, a good log facility should have the 1095 capability of associating each message with an importance or severity 1096 level, and at any point, the level for which messages are actually 1097 printed should be set in a flexible manner. Unlike trace messages, 1098 however, log messages are always part of the code and are available in 1099 the production version as well as in test versions. 1100 1101 The PSLib logging facility does not include the extensive facility 1102 levels which are provided by the trace facility. Less control over 1103 the granularity is needed for the log messages than for the trace 1104 messages. 1105 1106 A log message is placed in the code with the command: 1107 % 1108 \begin{prototype} 1109 void psLogMsg(const char *name, int level, const char *fmt, ...); 1110 void psLogMsgV(const char *name, int level, const char *fmt, va_list ap); 1111 \end{prototype} 1112 where \code{name} is a word to describe the source of the message, 1113 \code{level} is the severity level of this message, and \code{fmt} 1114 is a printf-style formatting statement defining the actual message, 1115 and is followed by the arguments to the formatting code. The second 1116 form, \code{psLogMsgV} is an equivalent command which takes a 1117 \code{va_list} argument. 1118 1119 A log message may have any level specified in the range 0-9, though 1120 the first 4 levels are associated with symbolic names: 1121 % 1122 \begin{datatype} 1123 enum { PS_LOG_ABORT = 0, PS_LOG_ERROR, PS_LOG_WARN, PS_LOG_INFO }; 1124 \end{datatype} 1125 % 1126 1127 At any time, the program may set the current log level, the level 1128 above which log messages are ignored, using the function: 1129 % 1130 \begin{prototype} 1131 int psLogSetLevel(int level); 1132 \end{prototype} 1133 % 1134 This function returns the previous log level. A specific message 1135 invoked with \code{psLogMsg} is only printed if its value of 1136 \code{level} is less than the current value set by 1137 \code{psLogSetLevel}. The default log level is set to 1138 \code{PS_LOG_INFO}. 1139 1140 Log messages are sent to the destination most recently set using: 1141 % 1142 \begin{prototype} 1143 bool psLogSetDestination(int fd); 1144 \end{prototype} 1145 % 1146 If the \code{fd} is 0, then the log is sent to standard output, 1147 otherwise it is sent to the specified file descriptor. A call to 1148 \code{psLogSetDestination} automatically closes an open file 1149 descriptor. 1150 1151 The corresponding function 1152 \begin{prototype} 1153 int psLogGetDestination(); 1154 \end{prototype} 1155 returns the current log destination file descriptor. If the 1156 destination has not been defined by the user, the descriptor for 1157 \code{stdout} is returned. 1158 1159 The output format is controlled with the function: 1160 % 1161 \begin{prototype} 1162 bool psLogSetFormat(const char *fmt); 1163 \end{prototype} 1164 % 1165 which expects a string consisting of the letters \code{H} (host), 1166 \code{L} (level), \code{M} (message), \code{N} (name), and \code{T} 1167 (time). The default is \code{THLNM}, which produces log messages in 1168 the form: 1169 \begin{verbatim} 1170 YYYY-MM-DD hh:mm:ssZ | hostname | L | name 1171 The message goes here 1172 and is indented by 4 spaces. 1173 \end{verbatim} 1174 where \code{YYYY}, \code{MM}, \code{DD}, \code{hh}, \code{mm}, and 1175 \code{ss} are the year, month (Jan is 01), day of the month, hours 1176 (0--23), minutes, and seconds when the log message was received. Note 1177 that the timestamp is in ISO order, and that the timezone is GMT 1178 (hence the \code{Z}). The \code{hostname} is returned by 1179 \code{gethostname}, \code{L} is a character associated with the level 1180 (\code{A}, \code{E}, \code{W}, and \code{I} for \code{PS_LOG_ABORT}, 1181 \code{PS_LOG_ERROR}, \code{PS_LOG_WARN}, and \code{PS_LOG_INFO} 1182 respectively. Other levels are represented numerically (\code{5} 1183 etc.). The other two fields, \code{name} and \code{msg}, are the 1184 arguments to \code{psLogMsg}. The \code{msg} is placed on a new line 1185 (allowing the \code{name} to fill the rest of the previous line), 1186 with each line indented by 4 spaces. An example message is: 1187 % 1188 \begin{verbatim} 1189 2004:02:24 20:14:18Z | alibaba.IfA.Hawaii.Edu | I | example.utils.helloWorld 1190 Hello world, 1191 it's me calling. 1192 \end{verbatim} 1193 % 1194 The possible order of the format entries is fixed and not determined 1195 by the order of the letters used in \code{psLogSetFormat}. Selecting 1196 an output format with fewer than the complete set of 5 entries simply 1197 removes those entries from the output messages. 1198 1199 Specifying a \code{fmt} of \code{NULL} turns off logging (equivalent 1200 to calling \code{psLogSetDestination(PS_LOG_TO_NONE)}, whereas if the 1201 \code{fmt} is \code{""}, then the format reverts to the default. 1202 1203 The following utility opens an output file descriptor for use by the 1204 trace and log facilities. 1205 \begin{prototype} 1206 int psMessageDestination (const char *dest); 1207 \end{prototype} 1208 % 1209 The destination string consists of a URL in the form 1210 \code{protocol:location}. The \code{protocol} value may be 1211 \code{file}, to send the log to a local file named by the value of 1212 \code{location}. Future expansion may allow the logger to send 1213 messages to an IP logger, with a protocol to be defined later. Three 1214 other special values are allowed for the \code{dest} parameter 1215 (without specifying a protocol): \code{stderr} and \code{stdout}, 1216 which return the file descriptors for \code{stderr} and \code{stdout} 1217 respectively, and \code{none} which returns the special descriptor to 1218 turn off logging. 1219 1220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1221 1222 \subsection{Error Handling} 1223 \hlabel{errorStack} 1224 1225 \PS{} errors must be raised using a function, \code{psError}, with the 1226 caller supplying a component name and error message. It is desireable 1227 to be able to trace an error through the program so that the events 1228 that led to the error may be quickly and clearly identified. 1229 \code{psError} prints an error message and doesn't abort, but instead 1230 returns the error code. 1231 \begin{prototype} 1232 psErrorCode p_psError(const char *filename, unsigned int lineno, const char *func, psErrorCode code, bool new, 1233 const char *fmt, ...); 1234 \end{prototype} 1235 \begin{datatype} 1236 #define psError(code, new, fmt, ...) psError(__FILE__, __LINE__, __func__, code, new, fmt, __VA_ARGS__) 1237 \end{datatype} 1238 1239 \code{psError} is a macro definition that allows the filename, line 1240 number and function name to be inputted to a private function, 1241 \code{p_psError}. The \code{code} is an enumerated type which lists 1242 the possible \textit{classes} of errors (e.g. \code{PS_ERR_IO}) that 1243 \PS{} code can generate (see section \ref{psErrorCodes}). The 1244 \code{new} argument takes a boolean which, if \code{TRUE} specifies 1245 that the error was set initially at this location, and if \code{FALSE} 1246 specifies that an error was passed to this location. Raising new 1247 error should clear the error stack. The final required argument, 1248 \code{fmt}, is a \code{printf}-style format that is passed to 1249 \code{psLogMsgV} with code \code{PS_LOG_ERROR}, and component equal to 1250 the concatenation of the file name and the line number, separated by a 1251 colon. The result of a call to \code{psError} must be to push an 1252 error onto a stack; this stack is cleared if \code{new} is true, or by 1253 a call to \code{psErrorClear}. 1254 1255 The errors on the error stack are defined as the following: 1256 \begin{datatype} 1257 typedef struct { 1258 char *name; ///< category of code that caused the error 1259 psErrorCode code; ///< class of error (equivalent to errno) 1260 char *msg; ///< the message associated with the error 1261 } psErr; 1262 \end{datatype} 1263 1264 The last error reported is available from \code{psErrorLast}; if no 1265 errors are current, a non-\code{NULL} \code{psErr} must be returned 1266 with code \code{PS_ERR_NONE}. Previous errors on the stack must be 1267 returned by \code{psErrorGet} (a value of \code{0} passed to 1268 \code{psErrorGet} is equivalent to a call to \code{psErrorLast}). 1269 The error stack may be completely cleared with \code{psErrorClear}. 1270 % 1271 \begin{prototype} 1272 unsigned int psErrorGetStackSize(void); 1273 const psErr *psErrorGet(int which); 1274 const psErr *psErrorLast(void); 1275 void psErrorClear(void); 1276 \end{prototype} 1277 1278 \code{psErrorGetStackSize} shall return the number of errors on the 1279 stack. The entire error stack may be printed to an open file 1280 descriptor by calling \code{psErrorStackPrint} (or 1281 \code{psErrorStackPrintV}); if and only if there are current errors, 1282 the printf-style string \code{fmt} is first printed to the file 1283 descriptor \code{fd}. In this printout, error codes must be replaced 1284 by their string equivalents as defined in the next section. Note that 1285 these are also available in the \code{psErr} structure. The successive 1286 lines of the traceback should be indented by an additional space. 1287 \code{psErrorStackPrintV} must not invoke \code{va_end}. 1288 % 1289 \begin{prototype} 1290 void psErrorStackPrint(FILE *fd, const char *fmt, ...); 1291 void psErrorStackPrintV(FILE *fd, const char *fmt, va_list va); 1292 \end{prototype} 1293 1294 Any \code{errorCode}s less then or equal to \code{PS_ERR_BASE} (see 1295 next section) must be taken to be valid values of \code{errno}, and 1296 \code{psErrorStackPrint} must print the value returned by 1297 \code{strerror} if such error codes are encountered. 1298 1299 The routine \code{psErrorCodeString} returns the string associated 1300 with an error code: 1301 \begin{prototype} 1302 const char *psErrorCodeString(psErrorCode code); 1303 \end{prototype} 1304 1305 \subsubsection{Error Codes} 1306 \hlabel{psErrorCodes} 1307 1308 Both error codes for PSLib and error codes for projects that use PSLib 1309 may be registered. In the former case, the error codes must be 1310 registered on initialisation, whereas in the latter case, they must be 1311 explicitly registered by the programmer. 1312 1313 \paragraph{Registering error codes} 1314 1315 PSLib and any project needed to use PSLib must define the necessary 1316 error codes and associated message strings. An array of error codes 1317 may be registered with the PSLib error handler using the function: 1318 \begin{prototype} 1319 void psErrorRegister(const psErrorDescription *errors, psS32 nerror); 1320 \end{prototype} 1321 where the errors are represented internally as follows: 1322 \begin{datatype} 1323 typedef struct { 1324 psErrorCode code; ///< An error code 1325 const char *descrip; ///< the associated description 1326 } psErrorDescription; 1327 \end{datatype} 1328 PSLib internal errors must be registered with the function 1329 \code{psErrorRegister}, which should be called as part of the 1330 program initialization to set up the error codes. It is left to the 1331 external project to produce their own error registration functions 1332 which must also be called during initialization. There is a clear need 1333 to coordinate the choice of error numbers. It is expected that error 1334 code ranges for different projects must be managed by the Project 1335 Office within Pan-STARRS. 1336 1337 \paragraph{Error Codes for PSLib} 1338 1339 For ease of maintenance, error codes for PSLib must be defined by an 1340 auxiliary file, conventionally named \file{psErrorCodes.dat}. The 1341 format of this file must consist of a number of lines, each of the 1342 form: 1343 \begin{verbatim} 1344 NAME [ = value ][,] STRING 1345 \end{verbatim} 1346 where \code{[ = value]} and the comma are optional, and no spaces are 1347 significant except in the STRING. Comments extend from \code{#} to 1348 the end of the line (except that a \code{\#} must be replaced by 1349 \code{#} and not taken to start a comment). For example, 1350 \begin{verbatim} 1351 # 1352 # This file is used to generate psErrorClasses.h 1353 # 1354 NONE = 0, not an error; must be 0 1355 BASE = 256, first value we use; should avoid errno conflicts 1356 UNKNOWN, unknown error 1357 # This is a comment, and is ignored. 1358 IO, I/O error 1359 BADFREE, bad argument to psFree() 1360 MEMORY_CORRUPTION, memory corruption detected 1361 \end{verbatim} 1362 The values \code{NONE = 0} and {UNKNOWN} must be present. 1363 1364 A script, called from the Makefiles, must generate two files, 1365 \file{psErrorCodes.h} and \file{psErrorCodes.c} from the input file 1366 \file{psErrorCodes.dat}. \file{psErrorCodes.h} must define an 1367 enumerated type \code{psErrorCode} with elements \code{PS_ERR_NAME} 1368 and values as specified in \file{psErrorCodes.dat}, e.g. 1369 \begin{datatype} 1370 #if !defined(PS_ERROR_CODES_H) 1371 #define PS_ERROR_CODES_H 1372 1373 typedef enum { 1374 PS_ERR_NONE = 0, 1375 PS_ERR_BASE = 256, 1376 PS_ERR_UNKNOWN, 1377 PS_ERR_IO, 1378 PS_ERR_BADFREE, 1379 PS_ERR_MEMORY_CORRUPTION, 1380 PS_ERR_N_ERR_CLASSES, 1381 } psErrorCode; 1382 #endif 1383 \end{datatype} 1384 1385 Any \code{errorCode}s less then or equal to \code{PS_ERR_BASE} must be 1386 taken to be valid values of \code{errno}. \file{psErrorCodes.c} must 1387 define the necessary function to register the error codes. 1388 1389 1390 1391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1392 1393 \subsection{Abort} 1394 1395 \code{psAbort}, must call \code{psLogMsgV} with a level of 1396 \code{PS_LOG_ABORT}, and then call \code{abort}. 1397 1398 \begin{prototype} 1399 void psAbort(const char *name, const char *fmt,...); 1400 \end{prototype} 1401 1402 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1403 1404 \pagebreak 1405 \section{Basic Data Types and Collections} 1406 1407 We require general data containers, so that associated values (e.g.\ 1408 the elements of an array) may be connected as a whole. We require the 1409 following types of containers: 1410 \begin{itemize} 1411 \item Arrays; 1412 \item Doubly-linked lists; and 1413 \item Hashes. 1414 \end{itemize} 1415 1416 \subsection{Data Structure Type Information} 1417 1418 Throughout PSLib, we require a variety of structures which correspond 1419 to different mathematical data concepts. For example, we have a data 1420 structure which corresponds to one-dimensional arrays (vectors) of 1421 different data types (\code{int}, \code{float}, etc). We also have a 1422 data structure which corresponds to two-dimensional arrays (images or 1423 matrices), again with different data types for the individual 1424 elements. 1425 1426 A variety of functions perform operations which are equivalent for 1427 different data types of the same dimension, or may even be defined for 1428 different data types of different dimensions. For example, if we 1429 write the operation $x + y$, the operation is clearly defined 1430 regardless of whether the operands $x$ and $y$ are both zero 1431 dimensional (single numbers), one dimensional (vectors), two 1432 dimensional (images), etc. It is even reasonable to define the meaning 1433 of such an operation if the data dimensions do not match: if $x$ is a 1434 scalar and $y$ is an image, the natural operation is to add the value 1435 of $x$ to every element of $y$; we can also define the meaning of the 1436 operation if $x$ is a vector and $y$ is a matrix. Nor does it matter 1437 mathematically that the element data types match; the sum of a float 1438 and an integer is a well-defined quantity. One constraint should be 1439 noted: the size of the elements in each dimension must match. For 1440 example, if $x$ were a vector of 100 elements, but $y$ were a vector 1441 of 1000 elements, the meaning of the operation $x + y$ is unclear. 1442 This type of operation should be invalid and should generate an error. 1443 1444 Given that some functions should be able to operate equivalently (or 1445 identically) on a wide range of data types, we define a mechanism 1446 which allows the C functions to accept a generic data type, and 1447 determine the type of the data on the basis of the data. 1448 Supported data types must be defined by a structure in which 1449 the first element is always of type \code{psType}: 1450 \begin{datatype} 1451 typedef struct { 1452 psDimen dimen; ///< The dimensionality 1453 psElemType type; ///< The type 1454 } psType; 1455 \end{datatype} 1456 where \code{psDimen dimen} defines the dimensionality of the data and 1457 \code{psElemType type} defines the data type of each element. These 1458 two variable types are defined as: 1459 \begin{datatype} 1460 typedef enum { 1461 PS_DIMEN_SCALAR, ///< Scalar 1462 PS_DIMEN_VECTOR, ///< A vector 1463 PS_DIMEN_TRANSV, ///< A transposed vector 1464 PS_DIMEN_IMAGE, ///< An image (matrix) 1465 PS_DIMEN_OTHER ///< Not supported for arithmetic 1466 } psDimen; 1467 \end{datatype} 1468 and 1469 \begin{datatype} 1470 typedef enum { 1471 PS_TYPE_S8, ///< Character 1472 PS_TYPE_S16, ///< Short integer 1473 PS_TYPE_S32, ///< Integer 1474 PS_TYPE_S64, ///< Long integer 1475 PS_TYPE_U8, ///< Unsigned character 1476 PS_TYPE_U16, ///< Unsigned short integer 1477 PS_TYPE_U32, ///< Unsigned integer 1478 PS_TYPE_U64, ///< Unsigned long integer 1479 PS_TYPE_F32, ///< Floating point 1480 PS_TYPE_F64, ///< Double-precision floating point 1481 PS_TYPE_C32, ///< Complex numbers consisting of floats 1482 PS_TYPE_C64, ///< Complex numbers consisting of doubles 1483 PS_TYPE_BOOL ///< Boolean value 1484 } psElemType; 1485 \end{datatype} 1486 We discuss the application of \code{psType} in more detail in 1487 section~\ref{sec:arithmetic}. 1488 1489 \subsection{Type checking} 789 790 \subsubsection{Type information} 1490 791 1491 792 Several of the collections contain data using a \code{void*} pointer. … … 1498 799 the \code{ptr} matches the desired type, as determined from the 1499 800 registered deallocator function. These functions may be implemented 1500 as macros if that is deemed convenient.801 as macros or inline functions if that is deemed convenient. 1501 802 1502 803 \begin{prototype} … … 1544 845 \end{prototype} 1545 846 1546 \subsection{Simple Scalars} 847 \tbd{Need to define psType.} 848 849 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 850 851 \subsection{Threads} 852 853 As pointed out earlier, PSLib makes no guarantees for thread-safety 854 outside of the memory management functions. Nevertheless, the following 855 facilities are provided as a convenience to the user. 856 857 Each of the data structures classified as a ``collection'' (i.e., 858 \code{psList, psHash, psMetadata, psArray, psPixels, psVector, 859 psBitSet}) and \code{psImage} shall contain an additional member, 860 \code{void *lock}, which provides a place for the user to carry around 861 a mutex or semaphore. This is provided so that the user doesn't have 862 to pass around both the structure and a mutex, or wrap PSLib 863 structures in their own thread-safe structures that contain a mutex. 864 865 We also define the following conveniences: 866 \begin{datatype} 867 typedef struct { 868 pthread_mutex_t mutex; 869 } psMutex; 870 \end{datatype} 871 872 \begin{prototype} 873 psMutex *psMutexAlloc(void); 874 bool psMutexLock(psMutex *mutex); 875 bool psMutexUnlock(psMutex *mutex); 876 \end{prototype} 877 878 \code{psMutex} simply wraps a POSIX thread mutex (this is necessary in 879 order to use the PS memory management system). 880 881 \code{psMutexAlloc} shall allocate memory for a \code{psMutex}, and 882 initialise the mutex. \code{psMutexLock} shall lock the mutex in 883 \code{thread}, and \code{psMutexUnlock} shall unlock the mutex in 884 \code{thread}. 885 886 These functions, in the interests of speed, should be implemented as 887 preprocessor macros. 888 889 These functions and the \code{void *lock} in the collection structures 890 and \code{psImage} should only be defined if \code{_REENTRANT} is 891 defined; otherwise the functions should be poisoned. 892 893 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 894 895 \subsection{Tracing and Logging} 896 897 This section defines the \PS{} Tracing and Logging APIs; the former 898 refers to debug information that we wish to be able to turn on and off 899 without recompiling (it will \emph{not} be available in production 900 code); the latter means information about the processing that must be 901 collected and saved, even in the production system. We envision that 902 extensive use will be made of \code{psTrace} throughout the \PS{} 903 code. 904 905 \subsubsection{Tracing APIs} 906 \hlabel{psTrace} 907 908 A code-tracing facility should allow the programmer to place messages 909 in the code which, when called, will print some useful information 910 about the containing block of code. Ideally, different messages may 911 be specified to have different levels (of severity or interest). For 912 a given run of the program, the level of interest should be set to 913 provide more or less feedback, depending on the needs of the 914 programmer. In a typical situation, low-level messages would be 915 placed generously throughout the code, indicating the flow of the 916 program. Higher-level messages would be placed in a limited number of 917 special locations, such as the start of major code segments or where a 918 particularly unusual condition is met. Top-level messages would be 919 placed in code triggered under serious error conditions. A normal run 920 of the program would have the trace messages printed only for the 921 top-level. If the user needs to dig deeper into the code, the trace 922 level should be set lower, and the more detailed messages could be 923 examined. In a case of a serious, poorly-understood problem with the 924 code, the trace threshold would be placed to the bottom and the 925 lowest-level step-by-step messages would be printed. 926 927 The PSLib tracing facility provides the above functionality, along 928 with the ability to assign different trace levels to messages from 929 different software components. Each trace message, when placed in the 930 code, is assigned to be part of a specific tracing 'facility', defined 931 in more detail below. The trace level for that specific message is 932 also set when the message is placed. Each facility may have its trace 933 level set independently. Thus, it is possible to request detailed 934 trace output for one facility while minimizing the verbosity of the 935 trace output from the rest of the program. 936 937 The trace facilities consist of a hierarchy of names. A trace 938 facility is defined by a string consisting of words separated by dots, 939 with a hierarchy equivalent to that of UNIX directory names. The 940 top-level facility is simply \code{'.'} (one dot). The next level 941 would be \code{'.A'}, followed by \code{.A.B}, and so on. The 942 relationship is seen in two ways. First, a facility inherits the 943 trace level of its parent unless explicitly specified. Second, the 944 hierarchy is used to format the listing of the trace facilities so 945 that they are easy to read. The first of these rules provides a 946 mechanism to define the default trace levels for any facility even if 947 it has not been registered explicitly since all named facilities are 948 implicitly children of the top level facility (\code{.}). The second 949 rule is simply an organizational technique to make the listing of 950 facility information clear. In specifying a facility, the leading 951 dot shall be optional, as a convenience to the user. 952 953 The API to place a trace message in the code, and simultaneously set 954 its trace level and facility, is: 955 % 956 \begin{prototype} 957 void psTrace(const char *facil, int level, const char *fmt,...); 958 void psTraceV(const char *facil, int level, const char *fmt, va_list ap); 959 \end{prototype} 960 % 961 where the \code{fmt} argument is a printf-style formatting code 962 followed by possible arguments to that formatting statement, to be 963 implemented using the \code{vprintf} functions. This command 964 specifies the name of the facility to which the message belongs 965 (\code{facil}), the trace level for this message in that facility 966 (\code{level}) and the message itself. The \code{psTraceV} version of 967 the command accepts a \code{va_list} argument list rather than a 968 variable number of arguments. 969 970 The trace level for any facility may be set at any time with the 971 following function: 972 % 973 \begin{prototype} 974 int psTraceSetLevel(const char *facil, int level); 975 \end{prototype} 976 % 977 where \code{level} specifies the current trace level for the facility 978 named by \code{facil}. The currently defined trace level for a given 979 facility may be determined by the function: 980 % 981 \begin{prototype} 982 int psTraceGetLevel(const char *facil); 983 \end{prototype} 984 % 985 which returns the trace level of the named facility following the 986 rules specified above. A specified trace message (identified by 987 \code{psTrace}) must be printed if and only if 988 \code{psTraceGetLevel(facil)} returns a value greater than or equal to 989 the value of \code{level} for that message. That is, a larger 990 number for the trace level corresponds to lower-level statements, and 991 hence is more verbose. 992 993 PSLib includes a utility function for examining the current tracing 994 levels of all facilities: 995 % 996 \begin{prototype} 997 void psTracePrintLevels(void); 998 \end{prototype} 999 % 1000 This function prints the hierarchy of trace facilities along with the 1001 current trace level for each facility. For example, a particular 1002 program may have a few facilities defined, along with their trace 1003 levels. A call to \code{psTracePrintLevels} may produce a listing 1004 which appears as: 1005 \begin{verbatim} 1006 . 0 1007 .IPP 0 1008 .IPP.debias 1 1009 .IPP.flatten 1 1010 .IPP.flatten.divide 2 1011 .IPP.object.findpeak 1 1012 .IPP.object.getsky 1 1013 \end{verbatim} 1014 1015 Considering the same program, the programmer might place a variety of 1016 trace messages throughout the \code{flatten} portion of the code with 1017 different types of messages, such as: 1018 % 1019 \begin{verbatim} 1020 psTrace("IPP.flatten", 2, "starting flatten function\n"); 1021 psTrace("IPP.flatten", 0, "flat-field image is \%s\n", filename); 1022 psTrace("IPP.flatten.divide", 2, "doing the divide\n"); 1023 psTrace("IPP.flatten.divide", 3, "trying the loop, i = \%d\n", i); 1024 psTrace("IPP.flatten.divide", 1, "got an invalid pixel value (NaN) at \%d,\%d\n"); 1025 psTrace("IPP.flatten.divide", 2, "divide is done\n"); 1026 \end{verbatim} 1027 % 1028 Under the trace levels set above, if the code actually reached each of 1029 these trace messages, the following messages would be printed: 1030 % 1031 \begin{verbatim} 1032 flat-field image is foo.fits 1033 doing the divide 1034 got an invalid pixel value (NaN) at 500,20 1035 divide is done 1036 \end{verbatim} 1037 % 1038 while these two would not be printed because their facility level was 1039 too low: 1040 % 1041 \begin{verbatim} 1042 starting flatten function 1043 trying the loop, i = 0 1044 trying the loop, i = 1 1045 trying the loop, i = 2 1046 ... 1047 \end{verbatim} 1048 % 1049 1050 The availability of the tracing facility at run-time, must be decided 1051 at compilation: If the C pre-processor macro \code{PS_NO_TRACE} is 1052 defined, all trace code must be replaced by empty space so that none 1053 of the code is compiled. This can be implemented via macro front-ends 1054 to private versions of the user APIs. In addition, a function 1055 \code{bool psTraceReset(void)} will free memory used by \code{psTrace} 1056 functions, effectively resetting all trace levels to 0. 1057 1058 The trace may optionally be written to a file or other output 1059 destination with \code{psTraceSetDestination}: 1060 \begin{prototype} 1061 void psTraceSetDestination(int fd); 1062 \end{prototype} 1063 If the \code{fd} is 0, then the trace is sent to standard output, 1064 otherwise it is sent to the specified file descriptor. A call to 1065 \code{psTraceSetDestination} automatically closes the file descriptor. 1066 1067 The corresponding function 1068 \begin{prototype} 1069 int psTraceGetDestination(); 1070 \end{prototype} 1071 returns the current trace destination file descriptor. If the 1072 destination has not been defined by the user, the descriptor for 1073 \code{stdout} is returned. 1074 1075 The trace output format is controlled with the function: 1076 % 1077 \begin{prototype} 1078 bool psTraceSetFormat(const char *fmt); 1079 \end{prototype} 1080 % 1081 which expects a string consisting of the letters \code{H} (host), 1082 \code{L} (level), \code{M} (message), \code{N} (name), and \code{T} 1083 (time). The default is \code{THLNM}, which produces trace messages in 1084 the form: 1085 \begin{verbatim} 1086 YYYY-MM-DD hh:mm:ssZ | hostname | L | name 1087 The message goes here 1088 and is indented by 4 spaces. 1089 \end{verbatim} 1090 where \code{YYYY}, \code{MM}, \code{DD}, \code{hh}, \code{mm}, and 1091 \code{ss} are the year, month (Jan is 01), day of the month, hours 1092 (0--23), minutes, and seconds when the trace message was received. Note 1093 that the timestamp is in ISO order, and that the timezone is GMT 1094 (hence the \code{Z}). The \code{hostname} is returned by 1095 \code{gethostname}, \code{L} is a character associated with the level 1096 (\code{A}, \code{E}, \code{W}, and \code{I} for \code{PS_LOG_ABORT}, 1097 \code{PS_LOG_ERROR}, \code{PS_LOG_WARN}, and \code{PS_LOG_INFO} 1098 respectively. Other levels are represented numerically (\code{5} 1099 etc.). The other two fields, \code{facil} and \code{msg}, are the 1100 arguments to \code{psTrace}. The \code{msg} is placed on a new line 1101 (allowing the \code{name} to fill the rest of the previous line), 1102 with each line indented by 4 spaces. An example message is: 1103 % 1104 \begin{verbatim} 1105 2004:02:24 20:14:18Z | alibaba.IfA.Hawaii.Edu | I | example.utils.helloWorld 1106 Hello world, 1107 it's me calling. 1108 \end{verbatim} 1109 % 1110 The possible order of the format entries is fixed and not determined 1111 by the order of the letters used in \code{psTraceSetFormat}. Selecting 1112 an output format with fewer than the complete set of 5 entries simply 1113 removes those entries from the output messages. 1114 1115 Specifying a \code{fmt} of \code{NULL} turns off logging (equivalent 1116 to calling \code{psLogSetDestination(PS_LOG_TO_NONE)}, whereas if the 1117 \code{fmt} is \code{""}, then the format reverts to the default. 1118 1119 \subsubsection{Message Logging} 1120 \hlabel{psLogMsg} 1121 1122 Message logging is similar in some respects to tracing. Like trace 1123 messages, log messages are placed in the code at various locations to 1124 provide output describing the current state of the program. Like 1125 the PSLib trace facility, a good log facility should have the 1126 capability of associating each message with an importance or severity 1127 level, and at any point, the level for which messages are actually 1128 printed should be set in a flexible manner. Unlike trace messages, 1129 however, log messages are always part of the code and are available in 1130 the production version as well as in test versions. 1131 1132 The PSLib logging facility does not include the extensive facility 1133 levels which are provided by the trace facility. Less control over 1134 the granularity is needed for the log messages than for the trace 1135 messages. 1136 1137 A log message is placed in the code with the command: 1138 % 1139 \begin{prototype} 1140 void psLogMsg(const char *name, int level, const char *fmt, ...); 1141 void psLogMsgV(const char *name, int level, const char *fmt, va_list ap); 1142 \end{prototype} 1143 where \code{name} is a word to describe the source of the message, 1144 \code{level} is the severity level of this message, and \code{fmt} 1145 is a printf-style formatting statement defining the actual message, 1146 and is followed by the arguments to the formatting code. The second 1147 form, \code{psLogMsgV} is an equivalent command which takes a 1148 \code{va_list} argument. 1149 1150 A log message may have any level specified in the range 0-9, though 1151 the first 4 levels are associated with symbolic names: 1152 % 1153 \begin{datatype} 1154 enum { PS_LOG_ABORT = 0, PS_LOG_ERROR, PS_LOG_WARN, PS_LOG_INFO }; 1155 \end{datatype} 1156 % 1157 1158 At any time, the program may set the current log level, the level 1159 above which log messages are ignored, using the function: 1160 % 1161 \begin{prototype} 1162 int psLogSetLevel(int level); 1163 \end{prototype} 1164 % 1165 This function returns the previous log level. A specific message 1166 invoked with \code{psLogMsg} is only printed if its value of 1167 \code{level} is less than the current value set by 1168 \code{psLogSetLevel}. The default log level is set to 1169 \code{PS_LOG_INFO}. 1170 1171 Log messages are sent to the destination most recently set using: 1172 % 1173 \begin{prototype} 1174 bool psLogSetDestination(int fd); 1175 \end{prototype} 1176 % 1177 If the \code{fd} is 0, then the log is sent to standard output, 1178 otherwise it is sent to the specified file descriptor. A call to 1179 \code{psLogSetDestination} automatically closes an open file 1180 descriptor. 1181 1182 The corresponding function 1183 \begin{prototype} 1184 int psLogGetDestination(); 1185 \end{prototype} 1186 returns the current log destination file descriptor. If the 1187 destination has not been defined by the user, the descriptor for 1188 \code{stdout} is returned. 1189 1190 The output format is controlled with the function: 1191 % 1192 \begin{prototype} 1193 bool psLogSetFormat(const char *fmt); 1194 \end{prototype} 1195 % 1196 which expects a string consisting of the letters \code{H} (host), 1197 \code{L} (level), \code{M} (message), \code{N} (name), and \code{T} 1198 (time). The default is \code{THLNM}, which produces log messages in 1199 the form: 1200 \begin{verbatim} 1201 YYYY-MM-DD hh:mm:ssZ | hostname | L | name 1202 The message goes here 1203 and is indented by 4 spaces. 1204 \end{verbatim} 1205 where \code{YYYY}, \code{MM}, \code{DD}, \code{hh}, \code{mm}, and 1206 \code{ss} are the year, month (Jan is 01), day of the month, hours 1207 (0--23), minutes, and seconds when the log message was received. Note 1208 that the timestamp is in ISO order, and that the timezone is GMT 1209 (hence the \code{Z}). The \code{hostname} is returned by 1210 \code{gethostname}, \code{L} is a character associated with the level 1211 (\code{A}, \code{E}, \code{W}, and \code{I} for \code{PS_LOG_ABORT}, 1212 \code{PS_LOG_ERROR}, \code{PS_LOG_WARN}, and \code{PS_LOG_INFO} 1213 respectively. Other levels are represented numerically (\code{5} 1214 etc.). The other two fields, \code{name} and \code{msg}, are the 1215 arguments to \code{psLogMsg}. The \code{msg} is placed on a new line 1216 (allowing the \code{name} to fill the rest of the previous line), 1217 with each line indented by 4 spaces. An example message is: 1218 % 1219 \begin{verbatim} 1220 2004:02:24 20:14:18Z | alibaba.IfA.Hawaii.Edu | I | example.utils.helloWorld 1221 Hello world, 1222 it's me calling. 1223 \end{verbatim} 1224 % 1225 The possible order of the format entries is fixed and not determined 1226 by the order of the letters used in \code{psLogSetFormat}. Selecting 1227 an output format with fewer than the complete set of 5 entries simply 1228 removes those entries from the output messages. 1229 1230 Specifying a \code{fmt} of \code{NULL} turns off logging (equivalent 1231 to calling \code{psLogSetDestination(PS_LOG_TO_NONE)}, whereas if the 1232 \code{fmt} is \code{""}, then the format reverts to the default. 1233 1234 The following utility opens an output file descriptor for use by the 1235 trace and log facilities. 1236 \begin{prototype} 1237 int psMessageDestination (const char *dest); 1238 \end{prototype} 1239 % 1240 The destination string consists of a URL in the form 1241 \code{protocol:location}. The \code{protocol} value may be 1242 \code{file}, to send the log to a local file named by the value of 1243 \code{location}. Future expansion may allow the logger to send 1244 messages to an IP logger, with a protocol to be defined later. Three 1245 other special values are allowed for the \code{dest} parameter 1246 (without specifying a protocol): \code{stderr} and \code{stdout}, 1247 which return the file descriptors for \code{stderr} and \code{stdout} 1248 respectively, and \code{none} which returns the special descriptor to 1249 turn off logging. 1250 1251 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1252 1253 \subsection{Error Handling} 1254 \hlabel{errorStack} 1255 1256 \PS{} errors shall be raised using a function, \code{psError}, with the 1257 caller supplying a component name and error message. It is desireable 1258 to be able to trace an error through the program so that the events 1259 that led to the error may be quickly and clearly identified. 1260 \code{psError} prints an error message and doesn't abort, but instead 1261 returns the error code. 1262 \begin{prototype} 1263 psErrorCode p_psError(const char *filename, unsigned int lineno, const char *func, psErrorCode code, 1264 bool new, const char *fmt, ...); 1265 \end{prototype} 1266 \begin{datatype} 1267 #define psError(code, new, fmt, ...) psError(__FILE__, __LINE__, __func__, code, new, fmt, __VA_ARGS__) 1268 \end{datatype} 1269 1270 \code{psError} is a macro definition that allows the filename, line 1271 number and function name to be inputted to a private function, 1272 \code{p_psError}. The \code{code} is an enumerated type which lists 1273 the possible \textit{classes} of errors (e.g. \code{PS_ERR_IO}) that 1274 \PS{} code can generate (see section \ref{psErrorCodes}). The 1275 \code{new} argument takes a boolean which, if \code{true} specifies 1276 that the error was set initially at this location, and if \code{false} 1277 specifies that an error was passed to this location. Raising new 1278 error should clear the error stack. The final required argument, 1279 \code{fmt}, is a \code{printf}-style format that is passed to 1280 \code{psLogMsgV} with code \code{PS_LOG_ERROR}, and component equal to 1281 the concatenation of the file name and the line number, separated by a 1282 colon. The result of a call to \code{psError} shall be to push an 1283 error onto a stack; this stack is cleared if \code{new} is true, or by 1284 a call to \code{psErrorClear}. 1285 1286 The errors on the error stack are defined as the following: 1287 \begin{datatype} 1288 typedef struct { 1289 char *name; ///< category of code that caused the error 1290 psErrorCode code; ///< class of error (equivalent to errno) 1291 char *msg; ///< the message associated with the error 1292 } psErr; 1293 \end{datatype} 1294 1295 The last error reported is available from \code{psErrorLast}; if no 1296 errors are current, a non-\code{NULL} \code{psErr} shall be returned 1297 with code \code{PS_ERR_NONE}. Previous errors on the stack shall be 1298 returned by \code{psErrorGet} (a value of \code{0} passed to 1299 \code{psErrorGet} is equivalent to a call to \code{psErrorLast}). 1300 The error stack may be completely cleared with \code{psErrorClear}. 1301 % 1302 \begin{prototype} 1303 unsigned int psErrorGetStackSize(void); 1304 const psErr *psErrorGet(int which); 1305 const psErr *psErrorLast(void); 1306 void psErrorClear(void); 1307 \end{prototype} 1308 1309 \code{psErrorGetStackSize} shall return the number of errors on the 1310 stack. The entire error stack may be printed to an open file 1311 descriptor by calling \code{psErrorStackPrint} (or 1312 \code{psErrorStackPrintV}); if and only if there are current errors, 1313 the printf-style string \code{fmt} is first printed to the file 1314 descriptor \code{fd}. In this printout, error codes shall be replaced 1315 by their string equivalents as defined in the next section. Note that 1316 these are also available in the \code{psErr} structure. The successive 1317 lines of the traceback should be indented by an additional space. 1318 \code{psErrorStackPrintV} must not invoke \code{va_end}. 1319 % 1320 \begin{prototype} 1321 void psErrorStackPrint(FILE *fd, const char *fmt, ...); 1322 void psErrorStackPrintV(FILE *fd, const char *fmt, va_list va); 1323 \end{prototype} 1324 1325 Any error \code{code}s less then or equal to \code{PS_ERR_BASE} (see 1326 next section) must be taken to be valid values of \code{errno}, and 1327 \code{psErrorStackPrint} must print the value returned by 1328 \code{strerror} if such error codes are encountered. 1329 1330 The routine \code{psErrorCodeString} returns the string associated 1331 with an error code: 1332 \begin{prototype} 1333 const char *psErrorCodeString(psErrorCode code); 1334 \end{prototype} 1335 1336 \subsubsection{Error Codes} 1337 \hlabel{psErrorCodes} 1338 1339 Both error codes for PSLib and error codes for projects that use PSLib 1340 may be registered. In the former case, the error codes must be 1341 registered on initialisation (see \code{psLibInit}), whereas in the 1342 latter case, they must be explicitly registered by the programmer. 1343 1344 \paragraph{Registering error codes} 1345 1346 PSLib and any project needed to use PSLib must define the necessary 1347 error codes and associated message strings. An array of error codes 1348 may be registered with the PSLib error handler using the function: 1349 \begin{prototype} 1350 void psErrorRegister(const psErrorDescription *errors, psS32 nerror); 1351 \end{prototype} 1352 where the errors are represented internally as follows: 1353 \begin{datatype} 1354 typedef struct { 1355 psErrorCode code; ///< An error code 1356 const char *descrip; ///< the associated description 1357 } psErrorDescription; 1358 \end{datatype} 1359 PSLib internal errors must be registered with the function 1360 \code{psErrorRegister}, which should be called as part of the 1361 program initialization to set up the error codes. It is left to the 1362 external project to produce their own error registration functions 1363 which must also be called during initialization. There is a clear need 1364 to coordinate the choice of error numbers. It is expected that error 1365 code ranges for different projects must be managed by the Project 1366 Office within Pan-STARRS. 1367 1368 \paragraph{Error Codes for PSLib} 1369 1370 For ease of maintenance, error codes for PSLib must be defined by an 1371 auxiliary file, conventionally named \file{psErrorCodes.dat}. The 1372 format of this file must consist of a number of lines, each of the 1373 form: 1374 \begin{verbatim} 1375 NAME [ = value ][,] STRING 1376 \end{verbatim} 1377 where \code{[ = value]} and the comma are optional, and no spaces are 1378 significant except in the STRING. Comments extend from \code{#} to 1379 the end of the line (except that a \code{\#} must be replaced by 1380 \code{#} and not taken to start a comment). For example, 1381 \begin{verbatim} 1382 # 1383 # This file is used to generate psErrorClasses.h 1384 # 1385 NONE = 0, not an error; must be 0 1386 BASE = 256, first value we use; should avoid errno conflicts 1387 UNKNOWN, unknown error 1388 # This is a comment, and is ignored. 1389 IO, I/O error 1390 BADFREE, bad argument to psFree() 1391 MEMORY_CORRUPTION, memory corruption detected 1392 \end{verbatim} 1393 The values \code{NONE = 0} and {UNKNOWN} must be present. 1394 1395 A script, called from the Makefiles, must generate two files, 1396 \file{psErrorCodes.h} and \file{psErrorCodes.c} from the input file 1397 \file{psErrorCodes.dat}. \file{psErrorCodes.h} must define an 1398 enumerated type \code{psErrorCode} with elements \code{PS_ERR_NAME} 1399 and values as specified in \file{psErrorCodes.dat}, e.g. 1400 \begin{datatype} 1401 #if !defined(PS_ERROR_CODES_H) 1402 #define PS_ERROR_CODES_H 1403 1404 typedef enum { 1405 PS_ERR_NONE = 0, 1406 PS_ERR_BASE = 256, 1407 PS_ERR_UNKNOWN, 1408 PS_ERR_IO, 1409 PS_ERR_BADFREE, 1410 PS_ERR_MEMORY_CORRUPTION, 1411 PS_ERR_N_ERR_CLASSES, 1412 } psErrorCode; 1413 #endif 1414 \end{datatype} 1415 1416 \file{psErrorCodes.c} must define the necessary functions to register 1417 the error codes. 1418 1419 This script will likely be of use to the user, and so it shall be 1420 installed as part of PSLib. 1421 1422 1423 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1424 1425 \subsection{Abort} 1426 1427 \code{psAbort}, must call \code{psLogMsgV} with a level of 1428 \code{PS_LOG_ABORT}, and then call \code{abort}. 1429 1430 \begin{prototype} 1431 void psAbort(const char *name, const char *fmt,...); 1432 \end{prototype} 1433 1434 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1435 1436 \pagebreak 1437 \section{Containers} 1438 1439 We require general data containers, so that associated values (e.g.\ 1440 the elements of an array) may be connected as a whole. We require the 1441 following types of containers: 1442 \begin{itemize} 1443 \item Arrays; 1444 \item Doubly-linked lists; 1445 \item Hashes; 1446 \item Pixel lists; 1447 \item Bit sets; 1448 \item Metadata; and 1449 \item Lookup tables. 1450 \end{itemize} 1451 1452 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1453 1454 \subsection{Arrays} 1455 1456 We require an order collection of unspecified data elements. We 1457 define \code{psArray} to carry such a collection: 1458 % 1459 \begin{datatype} 1460 typedef struct { 1461 const long n; ///< size of array 1462 const long nalloc; ///< allocated data block 1463 void **data; ///< pointer to data block 1464 void *lock; ///< Optional lock for thread safety 1465 }} psArray; 1466 \end{datatype} 1467 % 1468 In this structure, the argument \code{n} is the length of the array 1469 (the number of elements); \code{nalloc} is the number of elements 1470 allocated ($nalloc \ge n$). The allocated memory is pointed to by 1471 \code{data}. The structure is associated with a constructor and a 1472 destructor: 1473 % 1474 \begin{prototype} 1475 psArray *psArrayAlloc(long nalloc); 1476 psArray *psArrayRealloc(psArray *array, long nalloc); 1477 \end{prototype} 1478 % 1479 In these functions, \code{nalloc} is the number of elements to 1480 allocate. For \code{psArrayAlloc}, the value of \code{psArray.n} is 1481 set to \code{nalloc}. Users may choose to restrict the data range 1482 after the \code{psArrayAlloc} function is called. For 1483 \code{psArrayRealloc}, if the value of \code{nalloc} is smaller than 1484 the current value of \code{psArray.n}, then \code{psArray.n} is set to 1485 \code{nalloc}, the array is adjusted down to match \code{nalloc}, and 1486 the extra elements are dropped and freed if necesitated by the 1487 reference counter. If \code{nalloc} is larger than the current value 1488 of \code{psArray.n}, \code{psArray.n} is left intact. If the value of 1489 \code{array} is \code{NULL}, then \code{psArrayRealloc} must return an 1490 error. 1491 1492 \begin{prototype} 1493 psArray *psArrayAdd(psArray *array, long delta, psPtr data); 1494 \end{prototype} 1495 1496 This function adds a value to the end of an array. If the current 1497 length of the array (\code{psArray.n}) is at the limit of the 1498 allocated space, additional space is allocated. The value of 1499 \code{delta} defines how many elements to add on each pass (if this 1500 value is less than 1, 10 shall be used). 1501 1502 \begin{prototype} 1503 bool psArrayRemove(psArray *array, const psPtr data); 1504 \end{prototype} 1505 1506 This function removes all entries of \code{value} in the \code{array}, 1507 reducing the total number of elements of \code{array} as needed. 1508 Returns \code{TRUE} if any elements were removed, otherwise 1509 const int x0, y0; ///< data region relative to parent 1510 \code{FALSE}. 1511 1512 \begin{prototype} 1513 bool psArraySet(psArray *array, long position, psPtr data); 1514 psPtr psArrayGet(const psArray *array, long position); 1515 \end{prototype} 1516 1517 These accessor functions are provided as a convenience to the user. 1518 \code{psArraySet} sets the value of the \code{in} array at the specified 1519 \code{position} to \code{value}, returning \code{true} if successful. 1520 \code{psArrayGet} returns the value of the \code{in} array at the 1521 specified \code{position}. 1522 1523 \begin{datatype} 1524 typedef int (*psComparePtrFunc) ( 1525 const void **a, ///< first comparison target 1526 const void **b ///< second comparison target 1527 ); 1528 \end{datatype} 1529 1530 \begin{prototype} 1531 psArray *psArraySort(psArray *array, psComparePtrFunc func); 1532 \end{prototype} 1533 An array may be sorted using \code{psArraySort}, which requires the 1534 specification of a comparison function to specify how the objects on 1535 the list should be sorted. The motivation is primarily to be able to 1536 iterate on a sorted list of keys from a hash. The \code{array} is 1537 sorted in-place. 1538 1539 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1540 1541 \subsection{Doubly-linked lists} 1542 \label{sec:psList} 1543 1544 \PS{} shall support doubly linked lists through a type \code{psList}: 1545 % 1546 \begin{datatype} 1547 typedef struct { 1548 long n; ///< number of elements on list 1549 psListElem *head; ///< first element on list (may be NULL) 1550 psListElem *tail; ///< last element on list (may be NULL) 1551 psArray *iterators; ///< array of psListIterator: iteration cursors 1552 void *lock; ///< Optional lock for thread safety 1553 } psList; 1554 \end{datatype} 1555 % 1556 The type \code{psList} represents the container of the list. It has a 1557 pointer to the first element in the linked list (\code{head}), a 1558 pointer to the last element in the list (\code{tail}), an array of 1559 iteration cursors, (\code{iterators}), and an entry to define the 1560 number of elements in the list (\code{n}). 1561 1562 The elements of the list are defined by the type \code{psListElem}: 1563 % 1564 \begin{datatype} 1565 typedef struct psListElem { 1566 struct psListElem *prev; ///< previous link in list 1567 struct psListElem *next; ///< next link in list 1568 void *data; ///< real data item 1569 } psListElem; 1570 \end{datatype} 1571 % 1572 which includes a pointer to the next element in the list 1573 (\code{next}), the previous element in the list (\code{prev}), and a 1574 \code{void} pointer to whatever data is represented by this list 1575 element. The following supporting functions are required: 1576 1577 \begin{prototype} 1578 psList *psListAlloc(psPtr data); 1579 \end{prototype} 1580 Create a list. This function may take a pointer to a data item, or it 1581 may take \code{NULL}. The allocator creates both the \code{psList} 1582 and the first element in the list, pointed to by both 1583 \code{psList.head} and \code{psList.tail}. If the data entry is 1584 \code{NULL}, then an empty list, with both pointers set to \code{NULL} 1585 should be created. 1586 1587 The destructor function for \code{psList} must call \code{psFree} for 1588 all the the data associated with the list. 1589 1590 All data items placed onto lists must have their reference counters 1591 (section \ref{secMemRefcounter}) incremented. When elements are 1592 removed from a list, they must have their reference counters 1593 decremented. The action of retrieving data from a list (with one of 1594 the three \code{psListGet} functions) is considered ``borrowing'' the 1595 reference, so no action is performed on the reference counter. 1596 1597 Iteration on the list shall be achieved by means of a list iterator 1598 type: 1599 \begin{datatype} 1600 typedef struct { 1601 psList *list; ///< List iterator works on 1602 psListElem *cursor; ///< The current iterator cursor 1603 bool offEnd; ///< Is the iterator off the end? 1604 long index; ///< Index of iterator, to assist performance 1605 bool mutable; ///< Is it permissible to modify the list? 1606 } psListIterator; 1607 \end{datatype} 1608 The \code{psListIterator} keeps track of which list element the 1609 iterator \code{cursor} is currently pointing at. \code{index} is the 1610 index of the list iterator, which is used to assist performance when 1611 using numerical locations. The boolean member, \code{offEnd}, 1612 indicates whether the iterator has progressed off the end of the list 1613 (i.e., beyond the last item). The boolean \code{mutable} specifies 1614 whether it is permissible to modify the list pointed to by the 1615 iterator. \code{psListAddBefore} and \code{psListAddAfter} are not 1616 permitted to modify a list that is not \code{mutable} (i.e., only the 1617 \code{psListGetAndIncrement} and \code{psListGetAndDecrement} 1618 operations are permissible for a non-\code{mutable} list). 1619 1620 The corresponding constructor shall be: 1621 \begin{prototype} 1622 psListIterator *psListIteratorAlloc(const psList *list, long location, bool mutable); 1623 \end{prototype} 1624 Here, \code{list} is the \code{psList} on which the iterator will 1625 iterate, and \code{location} is the initial starting point, and may be 1626 a numerical index or it may be one of the special values: 1627 \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, which are defined as 0 and 1628 -1, respectively; a negative index is interpreted as relative to the 1629 end of the list. The boolean \code{mutable} specifies whether it is 1630 permissible to modify the list pointed to by the iterator. 1631 1632 The destructor for \code{psListIterator} shall, after freeing the 1633 \code{psListIterator}, also reorganise the \code{iter} array 1634 (replacing the element being removed with the last element) and 1635 resizing the array appropriately. 1636 1637 A list \code{iterator} shall be set to a specific \code{location} on 1638 the list upon calling \code{psListIteratorSet}: 1639 \begin{prototype} 1640 bool psListIteratorSet(psListIterator *iterator, int location); 1641 \end{prototype} 1642 Again, the \code{location} may be a numerical index or it may be one 1643 of the special values: \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, 1644 which are defined as 0 and -1, respectively; a negative index is 1645 interpreted as relative to the end of the list. The function shall 1646 return \code{true} if the reset was successful, or \code{false} 1647 otherwise. 1648 1649 \begin{prototype} 1650 bool psListAdd(psList *list, long location, psPtr data); 1651 bool psListAddAfter(psListIterator *iterator, psPtr data); 1652 bool psListAddBefore(psListIterator *iterator, psPtr data); 1653 \end{prototype} 1654 the first function, \code{psListAdd}, adds an entry to the \code{list} 1655 and returns a boolean giving the success or failure of the 1656 operation. The value of \code{location} may be a numerical index the 1657 \code{data} is to inhabit (if \code{location} is greater than the 1658 number of items on the list, then the function shall generate a 1659 warning and add the \code{data} to the tail) or it may be one of the 1660 special values: \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, which are 1661 defined as 0 and -1, respectively; a negative index is interpreted as 1662 relative to the end of the list. The other two functions, 1663 \code{psListAddAfter} and \code{psListAddBefore} specify that the 1664 \code{data} shall be added after or before (respectively) the current 1665 cursor position of the \code{iterator}. 1666 1667 \begin{prototype} 1668 psPtr psListGet(psList *list, long location); 1669 psPtr psListGetAndIncrement(psListIterator *iterator); 1670 psPtr psListGetAndDecrement(psListIterator *iterator); 1671 \end{prototype} 1672 A data item may be retrieved from the list with these functions. The 1673 first function, \code{psListGet} simply returns the value specified by 1674 its \code{location}, which may be a numerical index or it may be one 1675 of the special values: \code{PS_LIST_HEAD = 0} or \code{PS_LIST_TAIL = 1676 -1}; negative indices are interpreted as relative to the end of the 1677 list. The other two functions, \code{psListGetAndIncrement} and 1678 \code{psListGetAndDecrement} return the item under the iteration 1679 cursor before advancing to the next or previous item, respectively. 1680 1681 In the event that the iteration cursor is at the tail of the list, 1682 \code{psListGetAndIncrement} shall return the tail item and then set 1683 the \code{cursor} to \code{NULL} and \code{offEnd} to \code{true}. In 1684 the event that the iteration cursor is at the head of the list, 1685 \code{psListGetAndDecrement} shall return the head item and then set 1686 the \code{cursor} to \code{NULL} (and \code{offEnd} should already be 1687 \code{false}). In the event that the iteration \code{cursor} is 1688 \code{NULL}, \code{psListGetAndIncrement} and 1689 \code{psListGetAndDecrement} shall return \code{NULL}, and advance the 1690 iteration \code{cursor} only if the intended direction places the 1691 cursor back on the list; otherwise a warning shall be generated, and 1692 no change shall be made. If \code{psListGetAndDecrement} was called 1693 with \code{offEnd} as \code{true}, then \code{offEnd} shall also be 1694 toggled back to \code{false} to indicate that the \code{cursor} is no 1695 longer off the end of the list. 1696 1697 \begin{prototype} 1698 bool psListRemove(psList *list, long location) 1699 bool psListRemoveData(psList *list, psPtr data); 1700 \end{prototype} 1701 A data item may be removed from the list with these functions. For 1702 \code{psListRemove}, the value of \code{location} may be the numerical 1703 index or it may be one of the special values: \code{PS_LIST_HEAD} or 1704 \code{PS_LIST_TAIL}, which are defined as 0 and -1, respectively; a 1705 negative index is interpreted as relative to the end of the list. For 1706 \code{psListRemoveData}, the data item to be removed is identified by 1707 matching the pointer value with \code{psPtr data}. The functions 1708 return a value of \code{true} if the operation was successful, and 1709 \code{false} otherwise. In both cases, if any iterators are currently 1710 pointing at the item to be removed, the item shall be removed and 1711 those iterators pointing at it shall be moved to the next, and the 1712 function shall return \code{true}. If the item to be removed is not 1713 on the list, an error shall be generated and the function shall return 1714 \code{false}. 1715 1716 \begin{prototype} 1717 psArray *psListToArray(const psList *list); 1718 psList *psArrayToList(const psArray *array); 1719 \end{prototype} 1720 These two functions are available to convert between the 1721 \code{psList} and \code{psArray} containers. These functions do not 1722 free the elements or destroy the input collection. Rather, they 1723 increment the reference counter for each of the elements. 1724 1725 \begin{prototype} 1726 psList *psListSort(psList *list, psComparePtrFunc func); 1727 \end{prototype} 1728 A list may be sorted using \code{psListSort}, which requires the 1729 specification of a comparison function to specify how the objects on 1730 the list should be sorted. The motivation is primarily to be able to 1731 iterate on a sorted list of keys from a hash. The \code{list} is 1732 sorted in-place. 1733 1734 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1735 1736 \subsection{Hash Tables} 1737 \hlabel{psHash} 1738 1739 Hash tables are critical for quick retrieval of text-based data. The 1740 concept is as follows: Given a large collection of text strings, it is 1741 inefficient to search for a particular entry by performing a basic 1742 string comparison on all entries until a match is found. Even if a 1743 single list is sorted, we will still spend a substantial amount of 1744 time iterating across the entries in the list. In a hash table, we 1745 define an operation, the hash function, which uses the bytes of the 1746 string to construct a numerical value, the hash value. The hash value 1747 is defined to have a limited range of $N$ values. The hash table 1748 consists of $N$ buckets, each of which contains a list of the strings 1749 whose hash value corresponds to the bucket number. Searching for a 1750 specific string involves calculating the hash value for the string, 1751 going to the appropriate bucket, and searching through the 1752 corresponding list until the string is matched. 1753 1754 For PSLib, we define a hash table and hash buckets as follows: 1755 \footnote{ We choose not to use the POSIX function \code{hcreate}, 1756 \code{hdestroy}, and \code{hsearch} as they only support a single hash 1757 table at any one time.} 1758 % 1759 \begin{datatype} 1760 typedef struct { 1761 long n; ///< number of buckets 1762 psHashBucket **buckets; ///< the buckets themselves 1763 void *lock; ///< Optional lock for thread safety 1764 }} psHash; 1765 \end{datatype} 1766 % 1767 where \code{n} is the number of buckets defined for the hash functions, and 1768 \code{buckets} is an array of pointers to the individual buckets, each of which 1769 is defined by: 1770 % 1771 \begin{datatype} 1772 typedef struct psHashBucket { 1773 char *key; ///< key for this item of data 1774 void *data; ///< the data itself 1775 struct psHashBucket *next; ///< list of other possible keys 1776 } psHashBucket; 1777 \end{datatype} 1778 where each bucket contains the value of the \code{key}, a pointer to 1779 the \code{data}, and a pointer to the \code{next} list entry in the 1780 bucket (in the event that two or more keys have the same hash value). 1781 1782 A hash table is created with the following function: 1783 \begin{prototype} 1784 psHash *psHashAlloc(long nalloc); 1785 \end{prototype} 1786 which allocates the space for the hash table, creating and 1787 initializing \code{n} hash buckets. 1788 1789 The destructor for \code{psHash} must free all data associated with a complete hash table. 1790 1791 A data item may be added to the hash table with the function: 1792 \begin{prototype} 1793 bool psHashAdd(psHash *hash, const char *key, psPtr data); 1794 \end{prototype} 1795 In this function, the value of the string \code{key} is used to 1796 construct the hash value, find the appropriate bucket set, and add the 1797 new element \code{data} to the list. An existing element with the same 1798 value of \code{key} is destroyed using its registered destructor 1799 (\code{psMemBlock}). The return value of the function is a boolean 1800 defining the success or failure of the operation. 1801 1802 The data associated with a given key may be found with the function: 1803 \begin{prototype} 1804 psPtr psHashLookup(const psHash *hash, const char *key); 1805 \end{prototype} 1806 which returns the data value pointed to by the element associated with 1807 \code{key}, or the value \code{NULL} if no match is found. Similarly, 1808 a specific key may be removed (deleted) with the function: 1809 \begin{prototype} 1810 bool psHashRemove(psHash *hash, const char *key); 1811 \end{prototype} 1812 The function returns a value of \code{true} if the operation was 1813 successfull, and \code{false} otherwise. 1814 1815 The function 1816 \begin{prototype} 1817 psList *psHashKeyList(const psHash *hash); 1818 \end{prototype} 1819 returns the complete list of defined keys associated with the 1820 \code{psHash} table as a linked list. 1821 1822 \begin{prototype} 1823 psArray *psHashToArray(const psHash *hash); 1824 \end{prototype} 1825 This function places the data in a \code{psHash} into a \code{psArray} 1826 container. This function does not free the elements or destroy the 1827 input collection. Rather, it increments the reference counter for 1828 each of the elements. The resulting array does not have any 1829 information about the has key values, and the order is not 1830 significant. 1831 1832 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1833 1834 \subsection{Pixel Lists} 1835 1836 Usually an image mask is the best way to carry information about what 1837 pixels mean what. However, in the case where the number of pixels in 1838 which we are interested is limited, it is more efficient to simply 1839 carry a list of pixels. An example of this is in the image 1840 combination code, where we want to perform an operation on a 1841 relatively small fraction of pixels, and it is inefficient to go 1842 through an entire mask image checking each pixel. 1843 1844 \begin{datatype} 1845 typedef struct { 1846 int x; // x coordinate 1847 int y; // y coordinate 1848 } psPixelCoord; 1849 1850 typedef struct { 1851 psU32 n; // Number in use 1852 const psU32 nalloc; // Number allocated 1853 psPixelCoord *data; // The pixel coordinates 1854 void *lock; ///< Lock for thread safety 1855 } psPixels; 1856 \end{datatype} 1857 1858 \begin{prototype} 1859 psPixels *psPixelsAlloc(psU32 nalloc); 1860 psPixels *psPixelsRealloc(psPixels *pixels, psU32 nalloc); 1861 \end{prototype} 1862 1863 \code{psPixelsAlloc} and \code{psPixelsRealloc} provide dynamic 1864 allocation and reallocation in a manner analogous to those provided 1865 by \code{psVectorAlloc} and \code{psVectorRealloc}. 1866 1867 \begin{prototype} 1868 psPixels *psPixelsCopy(psPixels *out, const psPixels *pixels); 1869 psPixels *psPixelsConcatenate(psPixels *out, const psPixels *pixels); 1870 \end{prototype} 1871 1872 \code{psPixelsCopy} shall copy the contents of \code{pixels} to the 1873 \code{out}. In the event that \code{out} is \code{NULL}, a new 1874 \code{psPixels} shall be allocated, and the contents of \code{pixels} 1875 simply copied in. If \code{pixels} is \code{NULL}, the function shall 1876 generate an error and return \code{NULL}. 1877 1878 \code{psPixelsConcatenate} shall concatenate the \code{pixels} onto 1879 \code{out}. In the event that \code{out} is \code{NULL}, the function 1880 performs a \code{psPixelsCopy}, returning the copy. If \code{pixels} 1881 is \code{NULL}, the function shall generate an error and return 1882 \code{NULL}. The function shall take care to ensure that there are no 1883 duplicate pixels in \code{out} (since the order in which the pixels 1884 are stored is not important, the values may be sorted, allowing the 1885 use of a faster algorithm than a linear scan). 1886 1887 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1888 1889 \subsection{BitSets} 1890 1891 BitSets are required in order to turn options on and off. We require 1892 the capability to have a bitset of arbitrary length (i.e., not limited 1893 by the length of a \code{long}, say). The \code{psBitSet} structure 1894 is defined below. Note that the entry \code{bits} is an array of type 1895 \code{char} storing the bits as bits of each byte in the array, with 8 1896 bits available for each byte in the array. Also note that the 1897 constructor is passed the number of required bits, which implies that 1898 \code{ceil(n/8)} bytes must be allocated. The bitset structure is 1899 define by: 1900 \begin{datatype} 1901 typedef struct { 1902 long n; ///< Number of chars that form the bitset 1903 char *bits; ///< The bits 1904 void *lock; ///< Optional lock for thread safety 1905 }} psBitSet; 1906 \end{datatype} 1907 1908 We also require the corresponding constructor and destructor: 1909 \begin{prototype} 1910 psBitSet *psBitSetAlloc(long nalloc); 1911 \end{prototype} 1912 where \code{n} is the requested number of bits. 1913 1914 Several basic operations on bitsets are required: 1915 \begin{itemize} 1916 \item Set a bit; 1917 \item Check if a bit is set; and 1918 \item \code{OR}, \code{AND} and \code{XOR} two bitsets. 1919 \item \code{NOT} a bitset. 1920 \end{itemize} 1921 The corresponding APIs are defined below: 1922 1923 \begin{prototype} 1924 psBitSet *psBitSetSet(psBitSet *bitSet, long bit); 1925 psBitSet* psBitSetClear(psBitSet *bitSet, long bit); 1926 psBitSet *psBitSetOp(psBitSet *outBitSet, const psBitSet *inBitSet1, const char *operator, const psBitSet *inBitSet2); 1927 psBitSet *psBitSetNot(psBitSet *outBitSet, const psBitSet *inBitSet); 1928 bool psBitSetTest(const psBitSet *bitSet, long bit); 1929 char *psBitSetToString(const psBitSet* bitSet); 1930 \end{prototype} 1931 1932 \code{psBitSetSet} sets the specified \code{bit} in the 1933 \code{psBitSet}, and returns the updated bitset. The input bitset 1934 will be modified. 1935 1936 \code{psBitSetClear} clears the specified \code{bit} in the \code{bitSet} 1937 and returns the updated bitset. The input bitset will be modified. 1938 1939 \code{psBitSetOp} returns the \code{psBitSet} that is the result of 1940 performing the specified \code{operator} (one of \code{"AND"}, 1941 \code{"OR"}, or \code{"XOR"}) on \code{inBitSet1} and \code{inBitSet2}. 1942 If the output bitset \code{outBitSet} is \code{NULL}, it is created by 1943 the function. 1944 1945 \code{psBitSetNot} applies a unary \code{NOT} to a bitset, placing the 1946 answer in the bitset \code{out}, or creating a new bitset if 1947 \code{out} is \code{NULL}. 1948 1949 \code{psBitSetTest} returns a true value if the specified \code{bit} 1950 is set; otherwise, it returns a false value. 1951 1952 Finally, \code{psBitSetToString} returns a string representation of 1953 the specified \code{bits}. 1954 1955 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1956 1957 \subsection{Metadata} 1958 \label{sec:metadata} 1959 1960 \subsubsection{Conceptual Overview} 1961 1962 Within PSLib, we provide a data structure to carry metadata and 1963 mechanisms to manipulate the metadata. Metadata is a general concept 1964 that requires some discussion. In any data analysis task, the 1965 ensemble of all possible data may be divided into two or three 1966 classes: there is the specific data of interest, there is data which 1967 is related or critical but not the primary data of interest, and there 1968 is all of the other data which may or may not be interesting. For 1969 example, consider a simple 2D image obtained of a galaxy from a CCD 1970 camera on a telescope. If you want to study the galaxy, the specific 1971 data of interest is the collection of pixels. There are a variety of 1972 other pieces of data which are closely related and crucial to 1973 understanding the data in those pixels, such as the dimensions of the 1974 image, the coordinate system, the time of the image, the exposure 1975 time, and so forth. Other data may be known which may be less 1976 critical to understanding the image, but which may be interesting or 1977 desired at a later date. For example, the observer who took the 1978 image, the filter manufacturer, the humidity at the telescope, etc. 1979 1980 Formally, all of the related data which describe the principal data of 1981 interest are metadata. Note that which piece is the metadata and 1982 which is the data may depend on the context. If you are examining the 1983 pixels in an image, the coordinate and flux of an object may be part 1984 of the metadata. However, if you are analyzing a collection of 1985 objects extracted from an image, you may consider then pixel data 1986 simply part of the metadata associated with the list of objects. 1987 1988 There are various ways to handle metadata vs data within a programming 1989 environment. In C, it is convenient to use structures to group 1990 associated data together. One possibility is to define the metadata 1991 as part of the associated data structure. For example, the image data 1992 structure would have elements for all possible associated measurement. 1993 This approach is both cumbersome (because of the large number metadata 1994 types), impractical (because the full range of necessary metadata is 1995 difficult to know in advance) and inflexible (because any change in 1996 the collection of metadata requires addition of new structure elements 1997 and recompilation). 1998 1999 An alternative is to place the metadata in a generic container and use 2000 lookup mechanisms to extract the appropriate metadata when needed. An 2001 example of this is would be a text-based FITS header for an image read 2002 into a flat text buffer. In this implementation, metadata lookup 2003 functions could return the current value of, for example, NAXIS1 (the 2004 number of columns of the image) by scanning through the header buffer. 2005 This method has the benefits of flexibility and simplicity of 2006 programming interface, but it has the disadvantage that all metadata 2007 is accessed though this lookup mechanism. This may make the code less 2008 readable and it may slow down the access. 2009 2010 PSLib implements an intermediate solution to this problem. We specify 2011 a flexible, generic metadata container and access methods. Data types 2012 which require association with a general collection of metadata should 2013 include an entry of this metadata type. However, a subset of metadata 2014 concepts which are basic and frequently required may be placed in the 2015 coded structure elements. This approach allows the code to refer to 2016 the basic metadata concepts as part of the data structure (ie, 2017 \code{image.nx}), but also allows us to provide access to any 2018 arbitrary metadata which may be generated. As a practical matter, the 2019 choice of which entries are only in the metadata and which are part of 2020 the explicit structure elements is rather subjective. Any data 2021 elements which are frequently used should be put in the structure; 2022 those which are only infrequently needed should be left in the generic 2023 metadata. 2024 2025 There are some points of caution which must be noted. Any 2026 manipulation of the data should be reflected in the metadata where 2027 appropriate. This is always an issue of concern. For example, 2028 consider an image of dimensions \code{nx, ny}. If a function extracts 2029 a subraster, it must change the values of \code{nx, ny} to match the 2030 new dimensions. What should it do to the corresponding metadata? 2031 Clearly, it should change the corresponding value which defines 2032 \code{nX, nY}. However, it is not quite so simple: there may be other 2033 metadata values which depend on those values. These must also be 2034 changed appropriately. What if the metadata element points to a 2035 copy of the metadata which may be shared by other representations of 2036 the image? These must be treated differently because the change would 2037 invalidate those other references. Care must be taken, therefore, 2038 when writing functions which operate on the data to consider all of 2039 the relevant metadata entries which must also be updated. 2040 2041 A related issue is the definition of metadata names. Entries in a 2042 structure have the advantage of being hardwired: every instance of 2043 that structure will have the same name for the same entry. This is 2044 not necessarily the case with a more flexible metadata container. The 2045 image exposure time is a notorious example in astronomy. Different 2046 observatories use different header keywords (ie, metadata names) for 2047 the same concept of the exposure time (\code{EXPTIME}, 2048 \code{EXPOSURE}, \code{OPENTIME}, \code{INTTIME}, etc). Any system 2049 which operates on these metadata needs to address the issue of 2050 identifying these names. This issue seems like an argument for 2051 hardwiring metadata in the structure, but in fact it does not present 2052 such a strong case. If the metadata are hardwired, some function will 2053 still have to know how to interpret the various names to populate the 2054 structure. The concept can still be localized with generic metadata 2055 containers by including abstract metadata names within the code which 2056 are tied to the various implementations-specific metadata names. 2057 2058 \subsubsection{Metadata Representation} 2059 2060 \begin{figure} 2061 \psfig{file=Metadata,width=6.5in} 2062 \caption{Metadata Structures\label{fig:metadata}} 2063 \end{figure} 2064 2065 This section addresses the question of how \PS{} metadata should be 2066 represented in memory, not how it should be represented on disk. 2067 2068 We define an item of metadata with the following structure: 2069 \filbreak 2070 \begin{datatype} 2071 typedef struct { 2072 const psS32 id; ///< unique ID for this item 2073 char *name; ///< Name of item 2074 psMetadataType type; ///< type of this item 2075 const union { 2076 psS32 S32; ///< integer data 2077 psF32 F32; ///< floating-point data 2078 psF64 F64; ///< double-precision data 2079 psList *list; ///< psList entry 2080 psMetadata *md; ///< psMetadata entry 2081 psPtr V; ///< other type 2082 } data; ///< value of metadata 2083 char *comment; ///< optional comment ("", not NULL) 2084 } psMetadataItem; 2085 \end{datatype} 2086 2087 The \code{id} is a unique identifier for this item of metadata; 2088 experience shows that such tags are useful. The entry \code{name} 2089 specifies the name of the metadata item. The value of the metadata is 2090 given by the union \code{data}, and may be of type \code{psS32}, 2091 \code{psF32}, \code{psF64}, or an arbitrary rich structure pointed at 2092 by the \code{void} pointer \code{V}. A character string comment 2093 associated with this metadata item may be stored in the element 2094 \code{comment}. The \code{type} entry specifies how to interpret the 2095 type of the data being represented, given by the enumerated type 2096 \code{psMetadataType}: 2097 % 2098 \filbreak 2099 \begin{datatype} 2100 typedef enum { ///< type of item.data is: 2101 PS_META_S32 = PS_TYPE_S32, ///< psS32 primitive data. 2102 PS_META_F32 = PS_TYPE_F32, ///< psF32 primitive data. 2103 PS_META_F64 = PS_TYPE_F64, ///< psF64 primitive data. 2104 PS_META_BOOL = PS_TYPE_BOOL, ///< psBool primitive data. 2105 PS_META_LIST = 0x10000, ///< List data (Stored as item.data.list). 2106 PS_META_STR, ///< String data (Stored as item.data.V). 2107 PS_META_META, ///< Metadata (Stored as item.data.md). 2108 PS_META_VEC, ///< Vector data (Stored as item.data.V). 2109 PS_META_IMG, ///< Image data (Stored as item.data.V). 2110 PS_META_HASH, ///< Hash data (Stored as item.data.V). 2111 PS_META_LOOKUPTABLE, ///< Lookup table data (Stored as item.data.V). 2112 PS_META_JPEG, ///< JPEG data (Stored as item.data.V). 2113 PS_META_PNG, ///< PNG data (Stored as item.data.V). 2114 PS_META_ASTROM, ///< Astrometric coefficients (Stored as item.data.V). 2115 PS_META_TIME, ///< psTime object (Stored as item.data.V). 2116 PS_META_UNKNOWN, ///< Other data (Stored as item.data.V). 2117 PS_META_MULTI ///< Used internally, do not create a metadata item of this type. 2118 } psMetadataType; 2119 \end{datatype} 2120 The macro \code{PS_META_IS_PRIMITIVE(psMetadataType.type)} returns 2121 true if the type is one of the primitive data types (S32, F64, etc). 2122 In such a case, the data value is directly available. Otherwise, a 2123 pointer to the data is available. 2124 2125 A collection of metadata is represented by the \code{psMetadata} structure: 2126 \begin{datatype} 2127 typedef struct { 2128 psList *list; ///< list of psMetadataItem 2129 psHash *hash; ///< hash table of the same metadata 2130 void *lock; ///< Optional lock for thread safety 2131 }} psMetadata; 2132 \end{datatype} 2133 The type \code{psMetadata} is a container class for metadata. Note 2134 that there are in fact \emph{two} representations of the metadata 2135 (each \code{psMetadataItem} appears on both). The first 2136 representation employs a doubly-linked list that allows the order of 2137 the metadata to be preserved (e.g., if FITS headers are read in a 2138 particular order, they should be written in the same order). The 2139 second representation employs a hash table which allows fast look-up 2140 given a specific metadata keyword. 2141 2142 Certain metadata names (such as the FITS keywords \code{COMMENT} and 2143 \code{HISTORY} in a FITS header) may be repeated with different 2144 values. In such a case, the \code{psMetadata.list} structure contains 2145 the entries in their original sequence with duplicate keys. The 2146 \code{psMetadata.hash} entries, which are required to have unique 2147 keys, would have a single entry with the keyword of the repeated key, 2148 with the value of \code{psMetadataType} set to \code{PS_META_MULTI}, 2149 and the \code{psMetadataItem.data} element pointing to a \code{psList} 2150 containing the actual entries. If \code{psMetadataItemAlloc} is 2151 called with the type set to \code{PS_META_MULTI}, such a repeated key 2152 is created. In this case, the data value passed to 2153 \code{psMetadataItemAlloc} (the quantity in ellipsis) must be 2154 \code{NULL}. An empty \code{psMetadataItem} with the given keyword is 2155 created to hold future entries of that keyword. 2156 2157 As a convenience to the user, the following type-specific functions are 2158 also defined: 2159 \begin{prototype} 2160 psMetadataItem* psMetadataItemAllocStr(const char* name, const char* comment, const char* value); 2161 psMetadataItem* psMetadataItemAllocF32(const char* name, const char* comment, psF32 value); 2162 psMetadataItem* psMetadataItemAllocF64(const char* name, const char* comment, psF64 value); 2163 psMetadataItem* psMetadataItemAllocS32(const char* name, const char* comment, psS32 value); 2164 psMetadataItem* psMetadataItemAllocBool(const char* name, const char* comment, bool value); 2165 psMetadataItem* psMetadataItemAllocPtr(const char* name, psMetadataType type, const char* comment, psPtr value); 2166 \end{prototype} 2167 2168 \subsubsection{Metadata APIs} 2169 2170 \begin{prototype} 2171 psMetadata *psMetadataAlloc(void); 2172 \end{prototype} 2173 2174 The constructor for the collection of metadata, \code{psMetadata}, 2175 simply returns an empty metadata container (employing the constructors 2176 for the doubly-linked list and hash table). The destructor needs to 2177 free each of the \code{psMetadataItem}s. 2178 2179 \begin{prototype} 2180 psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...); 2181 psMetadataItem *psMetadataItemAllocV(const char *name, psMetadataType type, const char *comment, va_list list); 2182 \end{prototype} 2183 2184 The allocator for \code{psMetadataItem} returns a full 2185 \code{psMetadataItem} ready for insertion into the \code{psMetadata}. 2186 The \code{name} entry specifies the name to use for this metadata 2187 item, and may include \code{sprintf}-type formating codes. The 2188 \code{comment} entry is a fixed string which is used for the comment 2189 associated with this metadata item. The metadata data and the 2190 arguments to the \code{name} formatting codes are passed, in that 2191 order (metadata pointer first), to \code{psMetadataItemAlloc} as 2192 arguments following the comment string. The data must be a pointer 2193 for any data types which are stored in the element \code{data.void}, 2194 while other data types are passed as numeric values. The argument 2195 list must be interpreted appropriately by the \code{va_list} operators 2196 in the function. 2197 2198 \begin{prototype} 2199 bool psMetadataAddItem(psMetadata *md, const psMetadataItem *item, psS32 location, psS32 flags); 2200 bool psMetadataAdd(psMetadata *md, int location, const char *name, int format, const char *comment, ...); 2201 bool psMetadataAddV(psMetadata *md, int location, const char *name, int format, const char *comment, 2202 va_list list); 2203 \end{prototype} 2204 2205 Items may be added to the metadata in one of two ways --- firstly, an 2206 item may be added by appending a \code{psMetadataItem} which has 2207 already been created; and secondly by directly providing the data to 2208 be appended. In both cases, the return value defines the success 2209 (\code{true}) or failure of the operation. The second function, 2210 \code{psMetadataAdd} takes a pointer or value which is interpreted by 2211 the function using variadic argument interpretation. The third 2212 version is the \code{va_list} version of the second function. All 2213 three functions take a parameter, \code{location}, which specifies 2214 where in the list to place the element, following the conventions for 2215 the \code{psList}. The entry \code{mode} for \code{psMetadataAddItem} 2216 is a bit mask constructed by OR-ing the allowed option flags (eg, 2217 \code{PS_META_REPLACE}) which specify minor variations on the 2218 behavior. The \code{format} entry, which specifies both the metadata 2219 type and the optional flags, is constructed by bit-wise OR-ing the 2220 appropriate \code{psMetadataType} and allowed option flags. Care 2221 should be taken not to leak memory when appending an item for which 2222 the key already exists in the metadata (and is not 2223 \code{PS_META_MULTI}). 2224 % 2225 2226 \begin{datatype} 2227 typedef enum { ///< option flags for psMetadata functions 2228 PS_META_DEFAULT = 0, ///< default behavior (0x0000) for use in mode above 2229 PS_META_REPLACE = 0x1000000 ///< allow entry to be replaced 2230 PS_META_DUPLICATE_OK = 0x2000000 ///< allow duplicate entries 2231 PS_META_NULL = 0x4000000 ///< psMetadataItem.data is a NULL value 2232 } psMetadataFlags; 2233 \end{datatype} 2234 2235 The functions above take option flags which modify the behavior when 2236 metadata items are added to the metadata list. These flags must be 2237 bit-exclusive of those used above for the \code{psMetadataTypes}. The 2238 flags have the following meanings: 2239 2240 \code{PS_META_DEFAULT}: This is the zero bit mask, to allow the 2241 default behavior for \code{psMetadataAddItem} above. If this is OR-ed 2242 with a \code{psMetadataType}, the result is as if no OR-ing took 2243 place. 2244 2245 \code{PS_META_REPLACE}: Replace an existing, unique entry. If the 2246 given metadata item exists in the metadata collection, and is not of 2247 type \code{PS_META_MULTI}, then the item replaces the existing entry. 2248 2249 \code{PS_META_DUPLICATE_OK}: Allow the new metadata item key to be a 2250 duplicate (ie, \code{PS_META_MULTI}). If an existing item with the 2251 same key is already \code{PS_META_MULTI}, the new item is added to the 2252 \code{PS_META_MULTI} list. If the existing item is not 2253 \code{PS_META_MULTI}, a \code{PS_META_MULTI} list is created to 2254 contain both the existing item and the new item. The original entry's 2255 location on the psMetadata.list must be maintained. 2256 2257 \code{PS_META_NULL}: Indicates that \code{psMetadataItem.data} should be 2258 ignored and that the the current value is ``NULL'' or undefined. The 2259 \code{psMetadataItem} must have a proper \code{type} set and it's \code{data} 2260 field shall have a valid value. e.g. A \code{type} of \code{PS_META_STR} would 2261 require that 's \code{data} is set to \code{NULL}. 2262 2263 There are several of cases to handle for duplication of an existing 2264 key by a new key, some identified above. The following situations 2265 must also be handled: 2266 2267 If the new key already exists, but is not \code{PS_META_MULTI}, and 2268 the new item is not flagged as either \code{PS_META_DUPLICATE_OK} or 2269 \code{PS_META_REPLACE}, an error is raised. 2270 2271 If the new key already exists, and the existing item is 2272 \code{PS_META_MULTI}, the new item is added to the MULTI list. Note 2273 that if the new item is also of type \code{PS_META_MULTI}, no action 2274 is taken, but a successful exit status is returned (the action of 2275 adding a \code{PS_META_MULTI} item to the metadata is equivalent to 2276 setting that key to be tagged as \code{PS_META_MULTI}. If it is 2277 {\em already} \code{PS_META_MULTI}, this effect has already been 2278 achieved). 2279 2280 An example of code to use these metadata APIs to generate the 2281 structure seen in Figure~\ref{fig:metadata} is given below. 2282 2283 \begin{verbatim} 2284 md = psMetadataAlloc(); 2285 2286 psMetadataAdd(md, PS_LIST_TAIL, "SIMPLE", PS_META_BOOL, "basic fits", TRUE); 2287 psMetadataAdd(md, PS_LIST_TAIL, "BLANK", PS_META_S32, "invalid pixel data", -32768); 2288 psMetadataAdd(md, PS_LIST_TAIL, "DATE-OBS", PS_META_STR, "observing date UT", " 2004-6-16"); 2289 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_LIST, "head of comment block", NULL); 2290 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "DATA"); 2291 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "PARAMS"); 2292 psMetadataAdd(md, PS_LIST_TAIL, "EXPTIME", PS_META_F32, "exposure time (sec)", 1.05); 2293 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "FOO"); 2294 2295 cell = psMetadataAlloc(); 2296 psMetadataAdd(cell, PS_LIST_TAIL, "EXTNAME", PS_META_STR, "", "CCD00"); 2297 psMetadataAdd(cell, PS_LIST_TAIL, "BIASNAME", PS_META_STR, "", "BSEC-00"); 2298 psMetadataAdd(cell, PS_LIST_TAIL, "CHIP", PS_META_STR, "", "CHIP.00"); 2299 psMetadataAdd(md, PS_LIST_TAIL, "CELL.00", PS_META_META, "", cell); 2300 2301 cell = psMetadataAlloc(); 2302 psMetadataAdd(cell, PS_LIST_TAIL, "EXTNAME", PS_META_STR, "", "CCD01"); 2303 psMetadataAdd(cell, PS_LIST_TAIL, "BIASNAME", PS_META_STR, "", "BSEC-01"); 2304 psMetadataAdd(cell, PS_LIST_TAIL, "CHIP", PS_META_STR, "", "CHIP.01"); 2305 psMetadataAdd(md, PS_LIST_TAIL, "CELL.01", PS_META_META, "", cell); 2306 \end{verbatim} 2307 2308 The following code shows how to use the APIs to replace one of these values: 2309 \begin{verbatim} 2310 psMetadataAdd(md, PS_LIST_TAIL, "EXPTIME", PS_META_F32 | PS_REPLACE, "new exposure time (sec)", 2.05); 2311 \end{verbatim} 2312 2313 As a convenience to the user, the following type-specific functions 2314 are specified: 2315 \begin{prototype} 2316 bool psMetadataAddStr(psMetadata* md, psS32 location, const char* name, const char* comment, 2317 const char* value); 2318 bool psMetadataAddS32(psMetadata* md, psS32 location, const char* name, const char* comment, psS32 value); 2319 bool psMetadataAddF32(psMetadata* md, psS32 location, const char* name, const char* comment, psF32 value); 2320 bool psMetadataAddF64(psMetadata* md, psS32 location, const char* name, const char* comment, psF64 value); 2321 bool psMetadataAddBool(psMetadata* md, psS32 location, const char* name, const char* comment, bool value); 2322 bool psMetadataAddPtr(psMetadata* md, psS32 location, const char* name, psMetadataType type, 2323 const char* comment, psPtr value); 2324 \end{prototype} 2325 2326 2327 Items may be removed from the metadata by specifying a key or a 2328 location in the list. If the value of \code{name} is \code{NULL}, the 2329 value of \code{location} is used. If the value of \code{name} is not 2330 \code{NULL}, then \code{location} must be set to 2331 \code{PS_LIST_UNKNOWN}. If the key matches a metadata item, the item 2332 is removed from the metadata and \code{true} is returned; otherwise, 2333 \code{false} is returned. If the key is not unique, then \emph{all} 2334 items corresponding to the key are removed, and \code{true} is 2335 returned. 2336 % 2337 \begin{prototype} 2338 bool psMetadataRemove(psMetadata *md, int location, const char *key); 2339 \end{prototype} 2340 2341 Items may be found within the metadata by providing a key. In the 2342 event that the key is non-unique, the first item is returned. 2343 \begin{prototype} 2344 psMetadataItem *psMetadataLookup(const psMetadata *md, const char *key); 2345 \end{prototype} 2346 2347 Several utility functions are provided for simple cases. These 2348 functions perform the effort of casting the data to the appropriate 2349 type. The numerical functions shall return 0.0 if their key is not 2350 found. If the pointer value of \code{status} is not \code{NULL}, it 2351 is set to reflect the success or failure of the lookup. 2352 \begin{prototype} 2353 psPtr psMetadataLookupStr(bool *status, const psMetadata *md, const char *key); 2354 psS32 psMetadataLookupS32(bool *status, const psMetadata *md, const char *key); 2355 psF32 psMetadataLookupF32(bool *status, const psMetadata *md, const char *key); 2356 psF64 psMetadataLookupF64(bool *status, const psMetadata *md, const char *key); 2357 bool psMetadataLookupBool(bool *status, const psMetadata *md, const char *key); 2358 psPtr psMetadataLookupPtr(bool *status, const psMetadata *md, const char *key); 2359 \end{prototype} 2360 2361 Items may be retrieved from the metadata by their entry position. The 2362 value of which specifies the desired entry in the fashion of 2363 \code{psList}. 2364 \begin{prototype} 2365 psMetadataItem *psMetadataGet(const psMetadata *md, int location); 2366 \end{prototype} 2367 2368 The metadata list component may be iterated over by using a 2369 \code{psMetadataIterator} in a fashion equivalent to the 2370 \code{psListIterator}: 2371 \begin{datatype} 2372 typedef struct { 2373 psListIterator* iter; ///< iterator for the psMetadata's psList 2374 regex_t* regex; ///< the subsetting regular expression 2375 } psMetadataIterator; 2376 \end{datatype} 2377 2378 The iterator may be set to a location in the \code{psMetadata} list, 2379 and the user may get the previous or next item in the list relative to 2380 that location. \code{psMetadataGetNext} has the ability to match the 2381 key using a POSIX \code{regex}, e.g., if the user only wants to 2382 iterate through \code{IPP.machines.sky} and doesn't want to bother 2383 with \code{IPP.machines.detector}. The iterator should iterate over 2384 every item in the metadata list, even those that are contained in a 2385 \code{PS_META_LIST}. The value \code{iterator} specifies the iterator 2386 to be used. In setting the iterator, the position of the iterator is 2387 defined by \code{location}, which follows the conventions of the 2388 \code{psList} iterators. 2389 \begin{prototype} 2390 psMetadataIterator *psMetadataIteratorAlloc(psMetadata *md, int location, const char *regex); 2391 bool psMetadataIteratorSet(psMetadataIterator *iterator, int location); 2392 psMetadataItem *psMetadataGetAndIncrement(psMetadataIterator *iterator); 2393 psMetadataItem *psMetadataGetAndDecrement(psMetadataIterator *iterator); 2394 \end{prototype} 2395 2396 Metadata items may be printed to an open file descriptor based on a 2397 provided format. The format string is an sprintf format statement 2398 with exactly one \% formatting command. If the metadata item type is 2399 a numeric type, this formatting command must also be numeric, and type 2400 conversion performed to the value to match the format type. If the 2401 metadata item type is a string, the formatting command must also be 2402 for a string (\%s type of command). If the metadata type is any other 2403 data type, printing is not allowed. 2404 \begin{prototype} 2405 bool psMetadataItemPrint(FILE *fd, const char *format, const psMetadataItem *item); 2406 \end{prototype} 2407 2408 \subsubsection{Configuration files} 2409 \label{sec:configspec} 2410 2411 It will be necessary for the \PS{} system, in order to load 2412 pre-defined settings, to parse a configuration file into a 2413 \code{psMetadata} structure. This shall be performed by the 2414 function \code{psMetadataConfigParse}, as described below. 2415 2416 \begin{prototype} 2417 psMetadata *psMetadataConfigParse(psMetadata *md, int *nFail, const char *filename, bool overwrite); 2418 \end{prototype} 2419 2420 Given a metadata container, \code{md}, and the name of a configuration 2421 file, \code{filename}, \code{psMetadataConfigParse} shall parse the 2422 configuration file, placing the contained key/type/value/comment quads 2423 into the metadata, and returning a pointer to the metadata structure. 2424 The number of lines that failed to parse is returned in \code{nFail}. 2425 Multiple specifications of a key that haven't been declared (see 2426 below) are overwritten if and only if \code{overwrite} is \code{true}. 2427 If the metadata container is \code{NULL}, it shall be allocated. 2428 2429 On error, the function shall return \code{NULL}. 2430 2431 It is also useful to be able to convert a \code{psMetadata} structure into the 2432 Configuration File format for debugging purposes and to enable persistent 2433 configuration. 2434 2435 \begin{prototype} 2436 char *psMetadataConfigFormat(psMetadata *md); 2437 bool psMetadataConfigWrite(psMetadata *md, const char *filename); 2438 \end{prototype} 2439 2440 The \code{psMetadataConfigFormat} function converts a \code{psMetadata} 2441 structure (including any nested \code{psMetadata}) into a Configuration File 2442 formatted string. A \code{NULL} shall be returned on error. The 2443 \code{psMetadataConfigWrite} behaves the same as \code{psMetadataConfigFormat} 2444 except that the string is written out to \code{filename}. \code{false} is 2445 returned on failure. 2446 2447 \paragraph{Comments} 2448 2449 The configuration file shall consist of plain text with 2450 key/type/value/comment quads on separate lines. Blank lines, 2451 including those consisting solely of whitespace (both spaces and 2452 tabs), shall be ignored, as shall lines that commence with the comment 2453 character (a hash mark, \code{#}), either immediately at the start of 2454 the line, or preceded by whitespace. The key/type/value/comment quads 2455 shall all lie on a single line, separated by whitespace. 2456 2457 The key shall be first, possibly preceded on the line by whitespace 2458 which should not form part of the key. 2459 2460 \paragraph{NULL values} 2461 2462 The ``value'' of a quad may be declare to be undefined with the \code{NULL} 2463 keyword. \code{NULL} is allowed to co-exist with a ``comment'' and may be 2464 surrounded by whitespace. Any non-whitespace character will cause of the 2465 ``value'' to be interpreted as a string. 2466 2467 \begin{verbatim} 2468 foo STR NULL # string with a NULL value 2469 bar STR NULL a # string with a value of "NULL a" 2470 \end{verbatim} 2471 2472 \paragraph{Types} 2473 \subparagraph{Scalar \& Vector} 2474 2475 Next, to assist the casting of the value, shall be a string identifying the 2476 type of the value, which shall correspond to one of the simple types supported 2477 in \code{psMetadata}: \code{STRING,BOOL,S32,F32,F64}; \code{STR} may be used to 2478 abbreviate \code{STRING}; valid time types are \code{UTC,UT1,TAI,TT}. 2479 2480 \tbd{May, in the future, require more types, including U8,S16,C64, 2481 which will also necessitate updating the definition of psMetadata.} 2482 2483 The value shall follow the type: strings may consist of multiple words, and 2484 shall have all leading and trailing whitespace removed; booleans shall simply 2485 be either \code{T} or \code{F}. Time type values will be in the ISO8601 2486 compatible format of "YYYY-MM-DDTHH:MM:SS,sZ". When parsed, time types shall 2487 be represented as a \code{psTime} object. 2488 2489 Following the value may be an optional comment, preceded by a comment 2490 character (a hash mark, \code{#}), which in the case of a string 2491 value, serves to mark the end of the value, and for other types serves 2492 to identify the comment to the reader. Only one comment character may 2493 be present on any single line (i.e., neither strings nor comments are 2494 permitted to contain the comment character). The comment may consist 2495 of multiple words, and shall have leading and trailing whitespace 2496 removed. 2497 2498 One wrinkle is the specification of vectors. Keys for which the value 2499 is to be parsed as a vector shall be preceded immediately by a 2500 ``vector symbol'', which we choose to be the ``at'' sign, \code{@}. 2501 In this case, the type shall be interpreted as the type for the 2502 vector, which may be any of the signed or unsigned integer or floating 2503 point types (\code{U8,U16,U32,U64,S8,S16,S32,S32,S64,F32,F64}) but not 2504 the complex floating point types; and the value shall consist of 2505 multiple numbers, separated either by a comma or whitespace. These 2506 values shall populate a \code{psVector} of the appropriate type in the 2507 order in which they appear in the configuration file. 2508 2509 \tbd{May add complex types, likely to be specified with values such as 2510 1.23+4.56i in the future.} 2511 2512 \tbd{May add null, Not-a-Number (NaN), de-normalized, underflow, overflow, 2513 and/or +/-infinity values for selected types.} 2514 2515 \subparagraph{MULTI} 2516 2517 An additional hurdle is the specification of keys that may be non-unique (such 2518 as the \code{COMMENT} keyword in a FITS header). These keys shall be specified 2519 in the configuration file as non-unique with a \code{MULTI} declaration. In 2520 the form \code{[keyword] MULTI}. No other data may be provided on this line, 2521 though a comment, preceded by the comment marker, is valid. A warning shall 2522 be produced when a key which has not been specified to be non-unique is 2523 repeated; in this case, the former value shall be overwritten if 2524 \code{overwrite} is \code{true}, otherwise the line shall be ignored and 2525 counted as one that could not be parsed. It should be noted that non-unique 2526 keys may be of mixed type (even the \code{TYPE} and \code{METADATA} complex 2527 types). For example: 2528 \begin{verbatim} 2529 comment MULTI # a comment 2530 comment STR some string 2531 comment F32 1.23456 2532 comment BOOL T 2533 \end{verbatim} 2534 2535 If a line does not conform to the rules laid out here, a warning shall 2536 be generated, it shall be ignored and counted as a line that could not 2537 be parsed. The total number of lines that were not able to be parsed 2538 (including those that were ignored because \code{overwrite} is 2539 \code{false}, and any other parsing problems, but not including blank 2540 lines and comment lines) shall be returned by the function in the 2541 argument \code{nFail}. 2542 2543 Here are some examples of lines of a valid configuration file: 2544 \filbreak 2545 \begin{verbatim} 2546 Double F64 1.23456789 # This is a comment 2547 Float F32 0.98765 # This is a comment too 2548 String STR This is the string that forms the value #comment 2549 2550 # This is a comment line and is to be ignored 2551 boolean BOOL T # The value of `boolean' is `true' 2552 2553 @primes U8 2,3 5 7,11,13 17 # These are prime numbers 2554 2555 comment MULTI # The rest of this line is ignored, but `comment' is set to be non-unique 2556 comment STR This 2557 comment STR is 2558 comment STR a 2559 comment STR non-unique 2560 comment STR key 2561 Float F64 1.23456 # This generates a warning, and, if `overwrite' is `false', is ignored 2562 \end{verbatim} 2563 2564 Of course, a real configuration file should look much nicer to humans 2565 than the above example, but PSLib must be able to parse such ugly 2566 files. 2567 2568 \paragraph{Complex Types} 2569 \subparagraph{TYPE} 2570 2571 We support a modest tree structure by defining a reserved keyword \code{TYPE}. 2572 Any line in the config file which starts with the word \code{TYPE} shall be 2573 interpreted as defining a new valid type. The defined type name follows the 2574 word \code{TYPE}, and is in turn followed by an arbitrary number of words. 2575 These words are to be interpreted as the names of an embedded \code{psMetadata} 2576 entry, where the values are given on any line which (following the \code{TYPE} 2577 definition) employs the new type name. For example, a new type may be defined 2578 as: 2579 \begin{verbatim} 2580 TYPE CELL EXTNAME BIASSEC CHIP 2581 CELL.00 CELL CCD00 BSEC-00 CHIP.00 2582 CELL.01 CELL CCD01 BSEC-01 CHIP.00 2583 \end{verbatim} 2584 2585 When \code{psMetadataConfigParse} encounters the \code{TYPE} line, it 2586 should construct a \code{psMetadata} container and fill it with 2587 \code{psMetadataItems} having the names \code{EXTNAME, BIASSEC, CHIP}, 2588 with type \code{PS_META_STR}, but data allocated. When it next 2589 encounters an entry of type \code{CELL}, it should then use the given 2590 name (e.g., \code{CELL.00}) for the \code{psMetadataItem}, and copy 2591 the \code{psMetadata} data onto the \code{psMetadataItem.data.md} 2592 entry, filling in the values from the rest of the line (\code{CCD00, 2593 BSEC-00, CHIP.00}). This hierarchical structure is illustrated in 2594 Figure~\ref{fig:metadata}. 2595 2596 \subparagraph{METADATA} 2597 2598 Another way to form a tree-like structure is to directly define a 2599 \code{psMetadata} entry using a sequence of successive lines to define the 2600 values of the \code{psMetadataItem} entries. The initial line defines the new 2601 \code{psMetadata} entry and its name. The following lines have the same format 2602 as the other metadata config file entries. The sequence is terminated with a 2603 line with a single word \code{END}. For example, a metadata entry may be 2604 defined as: 2605 \begin{verbatim} 2606 CELL METADATA 2607 EXTNAME STR CCD00 2608 BIASSEC STR BSEC-00 2609 CHIP STR CHIP.00 2610 NCELL S32 24 2611 END 2612 \end{verbatim} 2613 2614 \paragraph{Scoping Rules} 2615 2616 A simple set of ``Scoping Rules'' are required to properly parse a 2617 configuration file. ``Scope'' refers to the current ``level'' of 2618 \code{METADATA} that a statement appears in. Statements that are not contained 2619 in a nested \code{METADATA} are said to be in the ``Top level scope''. Each 2620 level of nested \code{METADATA} statements create a new ``lower level scope''. 2621 2622 \begin{itemize} 2623 \item 2624 Variable names are unique only to the current level of scope. 2625 2626 \item 2627 non-unique keywords (\code{MULTI}) apply only to the current scope. i.e. They 2628 are invalid in ``higher'' or ``lower'' level scopes. 2629 2630 \item 2631 \code{TYPE} declarations apply only to the current scope. 2632 2633 \item 2634 \code{METADATA} declarations must begin and end in the same scope. i.e. They 2635 may not be declared and end in two different nested METADATA and the same 2636 depth. 2637 \end{itemize} 2638 2639 A series of test inputs is contained in 2640 \S\ref{sec:configtest}. 2641 2642 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2643 2644 \subsubsection{Lookup Tables} 2645 2646 Lookup tables store a variety of values indexed on a certain column. 2647 An example is for storing the difference between UT1 and UTC, and the 2648 polar motion vector as a function of date. 2649 2650 One of the key functionalities of a lookup table is to read data from 2651 an ordinary text file into an array of vectors. This functionality is 2652 generally useful, and so we specify a separate function that may be 2653 called independently: 2654 \begin{prototype} 2655 psArray *psVectorsReadFromFile(const char *filename, const char *format); 2656 \end{prototype} 2657 \code{psVectorsReadFromFile} shall return an array of 2658 \code{psVector}s, read from the specified \code{filename}. The file 2659 shall be plain text, consisting of an identical number of columns on 2660 each line, with the values separated by whitespace. Lines commencing 2661 with a comment character (the pound sign, \code{#}) and blank lines 2662 shall be ignored. The \code{format} is a \code{scanf}-like format 2663 which specifies the number of columns in the file, as well as their 2664 types. The following formats shall be defined: \code{\%d} for psS32, 2665 \code{\%ld} for psS64, \code{\%f} for psF32, and \code{\%lf} for 2666 psF64. A star (\code{*}) in the format shall indicate that the column 2667 is to be skipped. 2668 2669 \begin{datatype} 2670 typedef struct { 2671 const char *filename; ///< File from which data is to be read 2672 const char *format; ///< scanf-like format string for file 2673 long indexCol; ///< Column of the index vector (starting at zero) 2674 psVector *index; ///< Index values 2675 psArray *values; ///< Corresponding values: an array of vectors 2676 const psF64 validFrom, validTo; ///< Range of validity 2677 } psLookupTable; 2678 \end{datatype} 2679 2680 \code{filename} shall specify the file from which the lookup table 2681 data is to be read. \code{format} shall contain a \code{scanf}-like 2682 format string specifying how the columns are to be interpreted (see 2683 \code{psVectorsReadFromFile}). \code{indexCol} shall specify the 2684 index of the column (with the first column having an index of zero) 2685 that will form the index values. \code{index} shall contain the index 2686 values, which shall be sorted in increasing order. The \code{values} 2687 shall consist of an array of vectors, each of the same length as the 2688 \code{index} vector. The vectors (including the \code{index} and all 2689 vectors in the \code{values} array) may be any numerical type except 2690 complex types. The \code{validFrom} and \code{validTo} shall specify 2691 the range of valid values for the index; in most cases, these will 2692 simply be the first and last indices. 2693 2694 The constructor shall be: 2695 \begin{prototype} 2696 psLookupTable *psLookupTableAlloc(const char *filename, ///< File from which to read 2697 const char *format, ///< scanf-like format string 2698 long indexCol ///< Column of the index vector (starting at zero) 2699 ); 2700 \end{prototype} 2701 This function shall allocate a \code{psLookupTable}, and set the 2702 appropriate values, but it shall not read the lookup table. This is 2703 so that the lookup table can be specified at the initialisation of a 2704 program, but not read unless required. 2705 2706 The destructor shall free all the components. 2707 2708 \begin{prototype} 2709 psLookupTable *psLookupTableImport(psLookupTable *table, ///< Lookup table into which to import 2710 const psArray *vectors, ///< Array of vectors 2711 long indexCol ///< Index of the index vector in the array of vectors 2712 ); 2713 \end{prototype} 2714 \code{psLookupTableImport} shall import an array of vectors into a 2715 \code{table}. If \code{table} is \code{NULL}, a new 2716 \code{psLookupTable} shall be allocated and returned. The array of 2717 \code{vectors}, which was likely generated by 2718 \code{psVectorsReadFromFile}, are imported by setting the 2719 \code{table->index} to the vector specified by the \code{indexCol}, 2720 and pointing the \code{table->values} array data to the remaining 2721 vectors in \code{vectors}. Reference counters for the vectors shall 2722 be incremented as appropriate. The \code{validFrom} and 2723 \code{validTo} members of the \code{table} shall be set to the first 2724 and last values in the index vector. If the \code{index} vector is 2725 not sorted in the file, the lookup table shall be sorted prior to the 2726 function returning. 2727 2728 \begin{prototype} 2729 long psLookupTableRead(psLookupTable *table); 2730 \end{prototype} 2731 \code{psLookupTableRead} combines \code{psVectorsReadFromFile} and 2732 \code{psLookupTableImport} to read the appropriate file and import the 2733 data into the extant \code{table}. If the input \code{table} has 2734 already been read from a file, the file shall be re-read, and the 2735 contents replaced. The function shall return the number of lines read 2736 (not including ignored lines). 2737 2738 Interpolation on a lookup table is performed by the following 2739 functions: 2740 \begin{datatype} 2741 typedef enum { 2742 PS_LOOKUP_SUCCESS, ///< Table lookup succeeded 2743 PS_LOOKUP_PAST_TOP, ///< Lookup off top of table 2744 PS_LOOKUP_PAST_BOTTOM, ///< Lookup off bottom of table 2745 PS_LOOKUP_ERROR ///< Any other type of lookup error 2746 } psLookupStatusType; 2747 \end{datatype} 2748 2749 \begin{prototype} 2750 double psLookupTableInterpolate(const psLookupTable *table, double index, long column, psLookupStatusType *status); 2751 psVector *psLookupTableInterpolateAll(const psLookupTable *table, double index, psVector *stats); 2752 \end{prototype} 2753 Both functions shall interpolate the \code{table} at the provided 2754 \code{index}. For \code{psLookupTableInterpolate}, only the value in 2755 the specified \code{column} shall be calculated and returned. For 2756 \code{psLookupTableInterpolateAll}, all the values shall be calculated 2757 and returned as a \code{psVector}, the type of which shall be 2758 \code{PS_TYPE_F64}. 2759 2760 If the \code{index} is beyond the range of the \code{table}, 2761 \code{psLookupTableInterpolate} shall return \code{NaN}, and 2762 \code{psLookupTableInterpolateAll} shall return \code{NULL} --- that 2763 is, no attempt is made at extrapolation. 2764 2765 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2766 2767 \section{Mathematical Structures} 2768 2769 Throughout PSLib, we require a variety of structures which correspond 2770 to different mathematical data concepts. For example, we have a data 2771 structure which corresponds to one-dimensional arrays (vectors) of 2772 different data types (\code{int}, \code{float}, etc). We also have a 2773 data structure which corresponds to two-dimensional arrays (images or 2774 matrices), again with different data types for the individual 2775 elements. 2776 2777 A variety of functions perform operations which are equivalent for 2778 different data types of the same dimension, or may even be defined for 2779 different data types of different dimensions. For example, if we 2780 write the operation $x + y$, the operation is clearly defined 2781 regardless of whether the operands $x$ and $y$ are both zero 2782 dimensional (single numbers), one dimensional (vectors), two 2783 dimensional (images), etc. It is even reasonable to define the meaning 2784 of such an operation if the data dimensions do not match: if $x$ is a 2785 scalar and $y$ is an image, the natural operation is to add the value 2786 of $x$ to every element of $y$; we can also define the meaning of the 2787 operation if $x$ is a vector and $y$ is a matrix. Nor does it matter 2788 mathematically that the element data types match; the sum of a float 2789 and an integer is a well-defined quantity. One constraint should be 2790 noted: the size of the elements in each dimension must match. For 2791 example, if $x$ were a vector of 100 elements, but $y$ were a vector 2792 of 1000 elements, the meaning of the operation $x + y$ is unclear. 2793 This type of operation should be invalid and should generate an error. 2794 2795 Given that some functions should be able to operate equivalently (or 2796 identically) on a wide range of data types, we define a mechanism 2797 which allows the C functions to accept a generic data type, and 2798 determine the type of the data on the basis of the data. 2799 Supported data types must be defined by a structure in which 2800 the first element is always of type \code{psType}: 2801 \begin{datatype} 2802 typedef struct { 2803 psDimen dimen; ///< The dimensionality 2804 psElemType type; ///< The type 2805 } psType; 2806 \end{datatype} 2807 where \code{psDimen dimen} defines the dimensionality of the data and 2808 \code{psElemType type} defines the data type of each element. These 2809 two variable types are defined as: 2810 \begin{datatype} 2811 typedef enum { 2812 PS_DIMEN_SCALAR, ///< Scalar 2813 PS_DIMEN_VECTOR, ///< A vector 2814 PS_DIMEN_TRANSV, ///< A transposed vector 2815 PS_DIMEN_IMAGE, ///< An image (matrix) 2816 PS_DIMEN_OTHER ///< Not supported for arithmetic 2817 } psDimen; 2818 \end{datatype} 2819 and 2820 \begin{datatype} 2821 typedef enum { 2822 PS_TYPE_S8, ///< Character 2823 PS_TYPE_S16, ///< Short integer 2824 PS_TYPE_S32, ///< Integer 2825 PS_TYPE_S64, ///< Long integer 2826 PS_TYPE_U8, ///< Unsigned character 2827 PS_TYPE_U16, ///< Unsigned short integer 2828 PS_TYPE_U32, ///< Unsigned integer 2829 PS_TYPE_U64, ///< Unsigned long integer 2830 PS_TYPE_F32, ///< Floating point 2831 PS_TYPE_F64, ///< Double-precision floating point 2832 PS_TYPE_C32, ///< Complex numbers consisting of floats 2833 PS_TYPE_C64, ///< Complex numbers consisting of doubles 2834 PS_TYPE_BOOL ///< Boolean value 2835 } psElemType; 2836 \end{datatype} 2837 We discuss the application of \code{psType} in more detail in 2838 section~\ref{sec:arithmetic}. 2839 2840 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2841 2842 \subsection{Math Casting} 2843 2844 We define a basic data type which only contains the type information. 2845 This structure should be used to cast an unknown \code{psMath} data 2846 structure (\code{psImage}, \code{psVector}, \code{psScalar}) so the 2847 data type testing may be safely performed. 2848 2849 \begin{datatype} 2850 typedef struct { 2851 psType type; ///< data type information 2852 } psMath; 2853 \end{datatype} 2854 2855 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2856 2857 \subsection{Scalars} 1547 2858 1548 2859 We define a basic scalar data type which includes the type … … 1578 2889 \code{psScalar} data (see \S\ref{sec:arithmetic}). 1579 2890 1580 \subsection{Simple Vectors} 2891 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2892 2893 \subsection{Vectors} 1581 2894 1582 2895 We require several related types of basic one-dimensional arrays: … … 1689 3002 integers to be preserved. 1690 3003 1691 \subsection{Simple Images} 3004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3005 3006 \subsection{Images} 1692 3007 1693 3008 The most important data product produced by the telescope is an image. … … 1788 3103 \begin{datatype} 1789 3104 typedef struct { 1790 float x0;1791 float x1;1792 float y0;1793 float y1;3105 float x0; 3106 float x1; 3107 float y0; 3108 float y1; 1794 3109 } psRegion; 1795 3110 \end{datatype} … … 1823 3138 1824 3139 \begin{prototype} 1825 psRegion psRegionForImage (psImage *image, psRegion in);3140 psRegion psRegionForImage(psImage *image, psRegion in); 1826 3141 \end{prototype} 1827 3142 … … 1831 3146 replaced by their corrected value appropriate to the given image. 1832 3147 1833 \subsubsection{Image Pixel Lists} 1834 1835 Usually an image mask is the best way to carry information about what 1836 pixels mean what. However, in the case where the number of pixels in 1837 which we are interested is limited, it is more efficient to simply 1838 carry a list of pixels. An example of this is in the image 1839 combination code, where we want to perform an operation on a 1840 relatively small fraction of pixels, and it is inefficient to go 1841 through an entire mask image checking each pixel. 1842 1843 \begin{datatype} 1844 typedef struct { 1845 int x; // x coordinate 1846 int y; // y coordinate 1847 } psPixelCoord; 1848 1849 typedef struct { 1850 psU32 n; // Number in use 1851 const psU32 nalloc; // Number allocated 1852 psPixelCoord *data; // The pixel coordinates 1853 void *lock; ///< Lock for thread safety 1854 } psPixels; 1855 \end{datatype} 1856 1857 \begin{prototype} 1858 psPixels *psPixelsAlloc(psU32 nalloc); 1859 psPixels *psPixelsRealloc(psPixels *pixels, psU32 nalloc); 1860 \end{prototype} 1861 1862 \code{psPixelsAlloc} and \code{psPixelsRealloc} provide dynamic 1863 allocation and reallocation in a manner analogous to those provided 1864 by \code{psVectorAlloc} and \code{psVectorRealloc}. 1865 1866 \begin{prototype} 1867 psImage *psPixelsToMask(psImage *out, const psPixels *pixels, psRegion region, unsigned int maskVal); 1868 psPixels *psPixelsFromMask(psPixels *out, const psImage *mask, unsigned int maskVal); 1869 \end{prototype} 1870 1871 \code{psPixelsToMask} shall return an image of type U8 with the 1872 \code{pixels} lying within the specified \code{region} set to the 1873 \code{maskVal}. The \code{out} image shall be modified if supplied, 1874 or allocated and returned if \code{NULL}. The size of the output 1875 image shall be \code{region.x1 - region.x0} by \code{region.y1 - 1876 region.y0}, with \code{out->x0 = region.x0} and \code{out->y0 = 1877 region.y0}. In the event that either of \code{pixels} or 1878 \code{region} are \code{NULL}, the function shall generate an error 1879 and return \code{NULL}. 1880 1881 \code{psMaskToPixels} shall return a \code{psPixels} containing the 1882 coordinates in the \code{mask} that match the \code{maskVal}. The 1883 \code{out} pixel list shall be modified if supplied, or allocated and 1884 returned if \code{NULL}. In the event that \code{mask} is 1885 \code{NULL}, the function shall generate an error and return 1886 \code{NULL}. 1887 1888 \begin{prototype} 1889 psPixels *psPixelsCopy(psPixels *out, const psPixels *pixels); 1890 psPixels *psPixelsConcatenate(psPixels *out, const psPixels *pixels); 1891 \end{prototype} 1892 1893 \code{psPixelsCopy} shall copy the contents of \code{pixels} to the 1894 \code{out}. In the event that \code{out} is \code{NULL}, a new 1895 \code{psPixels} shall be allocated, and the contents of \code{pixels} 1896 simply copied in. If \code{pixels} is \code{NULL}, the function shall 1897 generate an error and return \code{NULL}. 1898 1899 \code{psPixelsConcatenate} shall concatenate the \code{pixels} onto 1900 \code{out}. In the event that \code{out} is \code{NULL}, the function 1901 performs a \code{psPixelsCopy}, returning the copy. If \code{pixels} 1902 is \code{NULL}, the function shall generate an error and return 1903 \code{NULL}. The function shall take care to ensure that there are no 1904 duplicate pixels in \code{out} (since the order in which the pixels 1905 are stored is not important, the values may be sorted, allowing the 1906 use of a faster algorithm than a linear scan). 1907 1908 \subsection{Math Casting} 1909 1910 We define a basic data type which only contains the type information. 1911 This structure should be used to cast an unknown \code{psMath} data 1912 structure (\code{psImage}, \code{psVector}, \code{psScalar}) so the 1913 data type testing may be safely performed. 1914 1915 \begin{datatype} 1916 typedef struct { 1917 psType type; ///< data type information 1918 } psMath; 1919 \end{datatype} 1920 1921 \subsection{Simple Arrays} 1922 1923 We require an order collection of unspecified data elements. We 1924 define \code{psArray} to carry such a collection: 1925 % 1926 \begin{datatype} 1927 typedef struct { 1928 const long n; ///< size of array 1929 const long nalloc; ///< allocated data block 1930 void **data; ///< pointer to data block 1931 void *lock; ///< Optional lock for thread safety 1932 }} psArray; 1933 \end{datatype} 1934 % 1935 In this structure, the argument \code{n} is the length of the array 1936 (the number of elements); \code{nalloc} is the number of elements 1937 allocated ($nalloc \ge n$). The allocated memory is pointed to by 1938 \code{data}. The structure is associated with a constructor and a 1939 destructor: 1940 % 1941 \begin{prototype} 1942 psArray *psArrayAlloc(long nalloc); 1943 psArray *psArrayRealloc(psArray *array, long nalloc); 1944 \end{prototype} 1945 % 1946 In these functions, \code{nalloc} is the number of elements to 1947 allocate. For \code{psArrayAlloc}, the value of \code{psArray.n} is 1948 set to \code{nalloc}. Users may choose to restrict the data range 1949 after the \code{psArrayAlloc} function is called. For 1950 \code{psArrayRealloc}, if the value of \code{nalloc} is smaller than 1951 the current value of \code{psArray.n}, then \code{psArray.n} is set to 1952 \code{nalloc}, the array is adjusted down to match \code{nalloc}, and 1953 the extra elements are dropped and freed if necesitated by the 1954 reference counter. If \code{nalloc} is larger than the current value 1955 of \code{psArray.n}, \code{psArray.n} is left intact. If the value of 1956 \code{array} is \code{NULL}, then \code{psArrayRealloc} must return an 1957 error. 1958 1959 \begin{prototype} 1960 psArray *psArrayAdd(psArray *array, long delta, psPtr data); 1961 \end{prototype} 1962 1963 This function adds a value to the end of an array. If the current 1964 length of the array (\code{psArray.n}) is at the limit of the 1965 allocated space, additional space is allocated. The value of 1966 \code{delta} defines how many elements to add on each pass (if this 1967 value is less than 1, 10 shall be used). 1968 1969 \begin{prototype} 1970 bool psArrayRemove(psArray *array, const psPtr data); 1971 \end{prototype} 1972 1973 This function removes all entries of \code{value} in the \code{array}, 1974 reducing the total number of elements of \code{array} as needed. 1975 Returns \code{TRUE} if any elements were removed, otherwise 1976 const int x0, y0; ///< data region relative to parent 1977 \code{FALSE}. 1978 1979 \begin{prototype} 1980 bool psArraySet(psArray *array, long position, psPtr data); 1981 psPtr psArrayGet(const psArray *array, long position); 1982 \end{prototype} 1983 1984 These accessor functions are provided as a convenience to the user. 1985 \code{psArraySet} sets the value of the \code{in} array at the specified 1986 \code{position} to \code{value}, returning \code{true} if successful. 1987 \code{psArrayGet} returns the value of the \code{in} array at the 1988 specified \code{position}. 1989 1990 \begin{datatype} 1991 typedef int (*psComparePtrFunc) ( 1992 const void **a, ///< first comparison target 1993 const void **b ///< second comparison target 1994 ); 1995 \end{datatype} 1996 1997 \begin{prototype} 1998 psArray *psArraySort(psArray *array, psComparePtrFunc func); 1999 \end{prototype} 2000 An array may be sorted using \code{psArraySort}, which requires the 2001 specification of a comparison function to specify how the objects on 2002 the list should be sorted. The motivation is primarily to be able to 2003 iterate on a sorted list of keys from a hash. The \code{array} is 2004 sorted in-place. 2005 2006 \subsection{Doubly-linked lists} 2007 \label{sec:psList} 2008 2009 \PS{} shall support doubly linked lists through a type \code{psList}: 2010 % 2011 \begin{datatype} 2012 typedef struct { 2013 long n; ///< number of elements on list 2014 psListElem *head; ///< first element on list (may be NULL) 2015 psListElem *tail; ///< last element on list (may be NULL) 2016 psArray *iterators; ///< array of psListIterator: iteration cursors 2017 void *lock; ///< Optional lock for thread safety 2018 } psList; 2019 \end{datatype} 2020 % 2021 The type \code{psList} represents the container of the list. It has a 2022 pointer to the first element in the linked list (\code{head}), a 2023 pointer to the last element in the list (\code{tail}), an array of 2024 iteration cursors, (\code{iterators}), and an entry to define the 2025 number of elements in the list (\code{n}). 2026 2027 The elements of the list are defined by the type \code{psListElem}: 2028 % 2029 \begin{datatype} 2030 typedef struct psListElem { 2031 struct psListElem *prev; ///< previous link in list 2032 struct psListElem *next; ///< next link in list 2033 void *data; ///< real data item 2034 } psListElem; 2035 \end{datatype} 2036 % 2037 which includes a pointer to the next element in the list 2038 (\code{next}), the previous element in the list (\code{prev}), and a 2039 \code{void} pointer to whatever data is represented by this list 2040 element. The following supporting functions are required: 2041 2042 \begin{prototype} 2043 psList *psListAlloc(psPtr data); 2044 \end{prototype} 2045 Create a list. This function may take a pointer to a data item, or it 2046 may take \code{NULL}. The allocator creates both the \code{psList} 2047 and the first element in the list, pointed to by both 2048 \code{psList.head} and \code{psList.tail}. If the data entry is 2049 \code{NULL}, then an empty list, with both pointers set to \code{NULL} 2050 should be created. 2051 2052 The destructor function for \code{psList} must call \code{psFree} for 2053 all the the data associated with the list. 2054 2055 All data items placed onto lists must have their reference counters 2056 (section \ref{secMemRefcounter}) incremented. When elements are 2057 removed from a list, they must have their reference counters 2058 decremented. The action of retrieving data from a list (with one of 2059 the three \code{psListGet} functions) is considered ``borrowing'' the 2060 reference, so no action is performed on the reference counter. 2061 2062 Iteration on the list shall be achieved by means of a list iterator 2063 type: 2064 \begin{datatype} 2065 typedef struct { 2066 psList *list; ///< List iterator works on 2067 psListElem *cursor; ///< The current iterator cursor 2068 bool offEnd; ///< Is the iterator off the end? 2069 long index; ///< Index of iterator, to assist performance 2070 bool mutable; ///< Is it permissible to modify the list? 2071 } psListIterator; 2072 \end{datatype} 2073 The \code{psListIterator} keeps track of which list element the 2074 iterator \code{cursor} is currently pointing at. \code{index} is the 2075 index of the list iterator, which is used to assist performance when 2076 using numerical locations. The boolean member, \code{offEnd}, 2077 indicates whether the iterator has progressed off the end of the list 2078 (i.e., beyond the last item). The boolean \code{mutable} specifies 2079 whether it is permissible to modify the list pointed to by the 2080 iterator. \code{psListAddBefore} and \code{psListAddAfter} are not 2081 permitted to modify a list that is not \code{mutable} (i.e., only the 2082 \code{psListGetAndIncrement} and \code{psListGetAndDecrement} 2083 operations are permissible for a non-\code{mutable} list). 2084 2085 The corresponding constructor shall be: 2086 \begin{prototype} 2087 psListIterator *psListIteratorAlloc(const psList *list, long location, bool mutable); 2088 \end{prototype} 2089 Here, \code{list} is the \code{psList} on which the iterator will 2090 iterate, and \code{location} is the initial starting point, and may be 2091 a numerical index or it may be one of the special values: 2092 \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, which are defined as 0 and 2093 -1, respectively; a negative index is interpreted as relative to the 2094 end of the list. The boolean \code{mutable} specifies whether it is 2095 permissible to modify the list pointed to by the iterator. 2096 2097 The destructor for \code{psListIterator} shall, after freeing the 2098 \code{psListIterator}, also reorganise the \code{iter} array 2099 (replacing the element being removed with the last element) and 2100 resizing the array appropriately. 2101 2102 A list \code{iterator} shall be set to a specific \code{location} on 2103 the list upon calling \code{psListIteratorSet}: 2104 \begin{prototype} 2105 bool psListIteratorSet(psListIterator *iterator, int location); 2106 \end{prototype} 2107 Again, the \code{location} may be a numerical index or it may be one 2108 of the special values: \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, 2109 which are defined as 0 and -1, respectively; a negative index is 2110 interpreted as relative to the end of the list. The function shall 2111 return \code{true} if the reset was successful, or \code{false} 2112 otherwise. 2113 2114 \begin{prototype} 2115 bool psListAdd(psList *list, long location, psPtr data); 2116 bool psListAddAfter(psListIterator *iterator, psPtr data); 2117 bool psListAddBefore(psListIterator *iterator, psPtr data); 2118 \end{prototype} 2119 the first function, \code{psListAdd}, adds an entry to the \code{list} 2120 and returns a boolean giving the success or failure of the 2121 operation. The value of \code{location} may be a numerical index the 2122 \code{data} is to inhabit (if \code{location} is greater than the 2123 number of items on the list, then the function shall generate a 2124 warning and add the \code{data} to the tail) or it may be one of the 2125 special values: \code{PS_LIST_HEAD} or \code{PS_LIST_TAIL}, which are 2126 defined as 0 and -1, respectively; a negative index is interpreted as 2127 relative to the end of the list. The other two functions, 2128 \code{psListAddAfter} and \code{psListAddBefore} specify that the 2129 \code{data} shall be added after or before (respectively) the current 2130 cursor position of the \code{iterator}. 2131 2132 \begin{prototype} 2133 psPtr psListGet(psList *list, long location); 2134 psPtr psListGetAndIncrement(psListIterator *iterator); 2135 psPtr psListGetAndDecrement(psListIterator *iterator); 2136 \end{prototype} 2137 A data item may be retrieved from the list with these functions. The 2138 first function, \code{psListGet} simply returns the value specified by 2139 its \code{location}, which may be a numerical index or it may be one 2140 of the special values: \code{PS_LIST_HEAD = 0} or \code{PS_LIST_TAIL = 2141 -1}; negative indices are interpreted as relative to the end of the 2142 list. The other two functions, \code{psListGetAndIncrement} and 2143 \code{psListGetAndDecrement} return the item under the iteration 2144 cursor before advancing to the next or previous item, respectively. 2145 2146 In the event that the iteration cursor is at the tail of the list, 2147 \code{psListGetAndIncrement} shall return the tail item and then set 2148 the \code{cursor} to \code{NULL} and \code{offEnd} to \code{true}. In 2149 the event that the iteration cursor is at the head of the list, 2150 \code{psListGetAndDecrement} shall return the head item and then set 2151 the \code{cursor} to \code{NULL} (and \code{offEnd} should already be 2152 \code{false}). In the event that the iteration \code{cursor} is 2153 \code{NULL}, \code{psListGetAndIncrement} and 2154 \code{psListGetAndDecrement} shall return \code{NULL}, and advance the 2155 iteration \code{cursor} only if the intended direction places the 2156 cursor back on the list; otherwise a warning shall be generated, and 2157 no change shall be made. If \code{psListGetAndDecrement} was called 2158 with \code{offEnd} as \code{true}, then \code{offEnd} shall also be 2159 toggled back to \code{false} to indicate that the \code{cursor} is no 2160 longer off the end of the list. 2161 2162 \begin{prototype} 2163 bool psListRemove(psList *list, long location) 2164 bool psListRemoveData(psList *list, psPtr data); 2165 \end{prototype} 2166 A data item may be removed from the list with these functions. For 2167 \code{psListRemove}, the value of \code{location} may be the numerical 2168 index or it may be one of the special values: \code{PS_LIST_HEAD} or 2169 \code{PS_LIST_TAIL}, which are defined as 0 and -1, respectively; a 2170 negative index is interpreted as relative to the end of the list. For 2171 \code{psListRemoveData}, the data item to be removed is identified by 2172 matching the pointer value with \code{psPtr data}. The functions 2173 return a value of \code{true} if the operation was successful, and 2174 \code{false} otherwise. In both cases, if any iterators are currently 2175 pointing at the item to be removed, the item shall be removed and 2176 those iterators pointing at it shall be moved to the next, and the 2177 function shall return \code{true}. If the item to be removed is not 2178 on the list, an error shall be generated and the function shall return 2179 \code{false}. 2180 2181 \begin{prototype} 2182 psArray *psListToArray(const psList *list); 2183 psList *psArrayToList(const psArray *array); 2184 \end{prototype} 2185 These two functions are available to convert between the 2186 \code{psList} and \code{psArray} containers. These functions do not 2187 free the elements or destroy the input collection. Rather, they 2188 increment the reference counter for each of the elements. 2189 2190 \begin{prototype} 2191 psList *psListSort(psList *list, psComparePtrFunc func); 2192 \end{prototype} 2193 A list may be sorted using \code{psListSort}, which requires the 2194 specification of a comparison function to specify how the objects on 2195 the list should be sorted. The motivation is primarily to be able to 2196 iterate on a sorted list of keys from a hash. The \code{list} is 2197 sorted in-place. 2198 2199 \subsection{Hash Tables} 2200 \hlabel{psHash} 2201 2202 Hash tables are critical for quick retrieval of text-based data. The 2203 concept is as follows: Given a large collection of text strings, it is 2204 inefficient to search for a particular entry by performing a basic 2205 string comparison on all entries until a match is found. Even if a 2206 single list is sorted, we will still spend a substantial amount of 2207 time iterating across the entries in the list. In a hash table, we 2208 define an operation, the hash function, which uses the bytes of the 2209 string to construct a numerical value, the hash value. The hash value 2210 is defined to have a limited range of $N$ values. The hash table 2211 consists of $N$ buckets, each of which contains a list of the strings 2212 whose hash value corresponds to the bucket number. Searching for a 2213 specific string involves calculating the hash value for the string, 2214 going to the appropriate bucket, and searching through the 2215 corresponding list until the string is matched. 2216 2217 For PSLib, we define a hash table and hash buckets as follows: 2218 \footnote{ We choose not to use the POSIX function \code{hcreate}, 2219 \code{hdestroy}, and \code{hsearch} as they only support a single hash 2220 table at any one time.} 2221 % 2222 \begin{datatype} 2223 typedef struct { 2224 long n; ///< number of buckets 2225 psHashBucket **buckets; ///< the buckets themselves 2226 void *lock; ///< Optional lock for thread safety 2227 }} psHash; 2228 \end{datatype} 2229 % 2230 where \code{n} is the number of buckets defined for the hash functions, and 2231 \code{buckets} is an array of pointers to the individual buckets, each of which 2232 is defined by: 2233 % 2234 \begin{datatype} 2235 typedef struct psHashBucket { 2236 char *key; ///< key for this item of data 2237 void *data; ///< the data itself 2238 struct psHashBucket *next; ///< list of other possible keys 2239 } psHashBucket; 2240 \end{datatype} 2241 where each bucket contains the value of the \code{key}, a pointer to 2242 the \code{data}, and a pointer to the \code{next} list entry in the 2243 bucket (in the event that two or more keys have the same hash value). 2244 2245 A hash table is created with the following function: 2246 \begin{prototype} 2247 psHash *psHashAlloc(long nalloc); 2248 \end{prototype} 2249 which allocates the space for the hash table, creating and 2250 initializing \code{n} hash buckets. 2251 2252 The destructor for \code{psHash} must free all data associated with a complete hash table. 2253 2254 A data item may be added to the hash table with the function: 2255 \begin{prototype} 2256 bool psHashAdd(psHash *hash, const char *key, psPtr data); 2257 \end{prototype} 2258 In this function, the value of the string \code{key} is used to 2259 construct the hash value, find the appropriate bucket set, and add the 2260 new element \code{data} to the list. An existing element with the same 2261 value of \code{key} is destroyed using its registered destructor 2262 (\code{psMemBlock}). The return value of the function is a boolean 2263 defining the success or failure of the operation. 2264 2265 The data associated with a given key may be found with the function: 2266 \begin{prototype} 2267 psPtr psHashLookup(const psHash *hash, const char *key); 2268 \end{prototype} 2269 which returns the data value pointed to by the element associated with 2270 \code{key}, or the value \code{NULL} if no match is found. Similarly, 2271 a specific key may be removed (deleted) with the function: 2272 \begin{prototype} 2273 bool psHashRemove(psHash *hash, const char *key); 2274 \end{prototype} 2275 The function returns a value of \code{true} if the operation was 2276 successfull, and \code{false} otherwise. 2277 2278 The function 2279 \begin{prototype} 2280 psList *psHashKeyList(const psHash *hash); 2281 \end{prototype} 2282 returns the complete list of defined keys associated with the 2283 \code{psHash} table as a linked list. 2284 2285 \begin{prototype} 2286 psArray *psHashToArray(const psHash *hash); 2287 \end{prototype} 2288 This function places the data in a \code{psHash} into a \code{psArray} 2289 container. This function does not free the elements or destroy the 2290 input collection. Rather, it increments the reference counter for 2291 each of the elements. The resulting array does not have any 2292 information about the has key values, and the order is not 2293 significant. 2294 2295 \subsection{Lookup Tables} 2296 2297 Lookup tables store a variety of values indexed on a certain column. 2298 An example is for storing the difference between UT1 and UTC, and the 2299 polar motion vector as a function of date. 2300 2301 One of the key functionalities of a lookup table is to read data from 2302 an ordinary text file into an array of vectors. This functionality is 2303 generally useful, and so we specify a separate function that may be 2304 called independently: 2305 \begin{prototype} 2306 psArray *psVectorsReadFromFile(const char *filename, const char *format); 2307 \end{prototype} 2308 \code{psVectorsReadFromFile} shall return an array of 2309 \code{psVector}s, read from the specified \code{filename}. The file 2310 shall be plain text, consisting of an identical number of columns on 2311 each line, with the values separated by whitespace. Lines commencing 2312 with a comment character (the pound sign, \code{#}) and blank lines 2313 shall be ignored. The \code{format} is a \code{scanf}-like format 2314 which specifies the number of columns in the file, as well as their 2315 types. The following formats shall be defined: \code{\%d} for psS32, 2316 \code{\%ld} for psS64, \code{\%f} for psF32, and \code{\%lf} for 2317 psF64. A star (\code{*}) in the format shall indicate that the column 2318 is to be skipped. 2319 2320 \begin{datatype} 2321 typedef struct { 2322 const char *filename; ///< File from which data is to be read 2323 const char *format; ///< scanf-like format string for file 2324 long indexCol; ///< Column of the index vector (starting at zero) 2325 psVector *index; ///< Index values 2326 psArray *values; ///< Corresponding values: an array of vectors 2327 const psF64 validFrom, validTo; ///< Range of validity 2328 } psLookupTable; 2329 \end{datatype} 2330 2331 \code{filename} shall specify the file from which the lookup table 2332 data is to be read. \code{format} shall contain a \code{scanf}-like 2333 format string specifying how the columns are to be interpreted (see 2334 \code{psVectorsReadFromFile}). \code{indexCol} shall specify the 2335 index of the column (with the first column having an index of zero) 2336 that will form the index values. \code{index} shall contain the index 2337 values, which shall be sorted in increasing order. The \code{values} 2338 shall consist of an array of vectors, each of the same length as the 2339 \code{index} vector. The vectors (including the \code{index} and all 2340 vectors in the \code{values} array) may be any numerical type except 2341 complex types. The \code{validFrom} and \code{validTo} shall specify 2342 the range of valid values for the index; in most cases, these will 2343 simply be the first and last indices. 2344 2345 The constructor shall be: 2346 \begin{prototype} 2347 psLookupTable *psLookupTableAlloc(const char *filename, ///< File from which to read 2348 const char *format, ///< scanf-like format string 2349 long indexCol ///< Column of the index vector (starting at zero) 2350 ); 2351 \end{prototype} 2352 This function shall allocate a \code{psLookupTable}, and set the 2353 appropriate values, but it shall not read the lookup table. This is 2354 so that the lookup table can be specified at the initialisation of a 2355 program, but not read unless required. 2356 2357 The destructor shall free all the components. 2358 2359 \begin{prototype} 2360 psLookupTable *psLookupTableImport(psLookupTable *table, ///< Lookup table into which to import 2361 const psArray *vectors, ///< Array of vectors 2362 long indexCol ///< Index of the index vector in the array of vectors 2363 ); 2364 \end{prototype} 2365 \code{psLookupTableImport} shall import an array of vectors into a 2366 \code{table}. If \code{table} is \code{NULL}, a new 2367 \code{psLookupTable} shall be allocated and returned. The array of 2368 \code{vectors}, which was likely generated by 2369 \code{psVectorsReadFromFile}, are imported by setting the 2370 \code{table->index} to the vector specified by the \code{indexCol}, 2371 and pointing the \code{table->values} array data to the remaining 2372 vectors in \code{vectors}. Reference counters for the vectors shall 2373 be incremented as appropriate. The \code{validFrom} and 2374 \code{validTo} members of the \code{table} shall be set to the first 2375 and last values in the index vector. If the \code{index} vector is 2376 not sorted in the file, the lookup table shall be sorted prior to the 2377 function returning. 2378 2379 \begin{prototype} 2380 long psLookupTableRead(psLookupTable *table); 2381 \end{prototype} 2382 \code{psLookupTableRead} combines \code{psVectorsReadFromFile} and 2383 \code{psLookupTableImport} to read the appropriate file and import the 2384 data into the extant \code{table}. If the input \code{table} has 2385 already been read from a file, the file shall be re-read, and the 2386 contents replaced. The function shall return the number of lines read 2387 (not including ignored lines). 2388 2389 Interpolation on a lookup table is performed by the following 2390 functions: 2391 \begin{datatype} 2392 typedef enum { 2393 PS_LOOKUP_SUCCESS, ///< Table lookup succeeded 2394 PS_LOOKUP_PAST_TOP, ///< Lookup off top of table 2395 PS_LOOKUP_PAST_BOTTOM, ///< Lookup off bottom of table 2396 PS_LOOKUP_ERROR ///< Any other type of lookup error 2397 } psLookupStatusType; 2398 \end{datatype} 2399 2400 \begin{prototype} 2401 double psLookupTableInterpolate(const psLookupTable *table, double index, long column, psLookupStatusType *status); 2402 psVector *psLookupTableInterpolateAll(const psLookupTable *table, double index, psVector *stats); 2403 \end{prototype} 2404 Both functions shall interpolate the \code{table} at the provided 2405 \code{index}. For \code{psLookupTableInterpolate}, only the value in 2406 the specified \code{column} shall be calculated and returned. For 2407 \code{psLookupTableInterpolateAll}, all the values shall be calculated 2408 and returned as a \code{psVector}, the type of which shall be 2409 \code{PS_TYPE_F64}. 2410 2411 If the \code{index} is beyond the range of the \code{table}, 2412 \code{psLookupTableInterpolate} shall return \code{NaN}, and 2413 \code{psLookupTableInterpolateAll} shall return \code{NULL} --- that 2414 is, no attempt is made at extrapolation. 3148 \pagebreak 2415 3149 2416 3150 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2417 3151 2418 \pagebreak 2419 2420 \subsection{BitSets} 2421 2422 BitSets are required in order to turn options on and off. We require 2423 the capability to have a bitset of arbitrary length (i.e., not limited 2424 by the length of a \code{long}, say). The \code{psBitSet} structure 2425 is defined below. Note that the entry \code{bits} is an array of type 2426 \code{char} storing the bits as bits of each byte in the array, with 8 2427 bits available for each byte in the array. Also note that the 2428 constructor is passed the number of required bits, which implies that 2429 \code{ceil(n/8)} bytes must be allocated. The bitset structure is 2430 define by: 2431 \begin{datatype} 2432 typedef struct { 2433 long n; ///< Number of chars that form the bitset 2434 char *bits; ///< The bits 2435 void *lock; ///< Optional lock for thread safety 2436 }} psBitSet; 2437 \end{datatype} 2438 2439 We also require the corresponding constructor and destructor: 2440 \begin{prototype} 2441 psBitSet *psBitSetAlloc(long nalloc); 2442 \end{prototype} 2443 where \code{n} is the requested number of bits. 2444 2445 Several basic operations on bitsets are required: 2446 \begin{itemize} 2447 \item Set a bit; 2448 \item Check if a bit is set; and 2449 \item \code{OR}, \code{AND} and \code{XOR} two bitsets. 2450 \item \code{NOT} a bitset. 2451 \end{itemize} 2452 The corresponding APIs are defined below: 2453 2454 \begin{prototype} 2455 psBitSet *psBitSetSet(psBitSet *bitSet, long bit); 2456 psBitSet* psBitSetClear(psBitSet *bitSet, long bit); 2457 psBitSet *psBitSetOp(psBitSet *outBitSet, const psBitSet *inBitSet1, const char *operator, const psBitSet *inBitSet2); 2458 psBitSet *psBitSetNot(psBitSet *outBitSet, const psBitSet *inBitSet); 2459 bool psBitSetTest(const psBitSet *bitSet, long bit); 2460 char *psBitSetToString(const psBitSet* bitSet); 2461 \end{prototype} 2462 2463 \code{psBitSetSet} sets the specified \code{bit} in the 2464 \code{psBitSet}, and returns the updated bitset. The input bitset 2465 will be modified. 2466 2467 \code{psBitSetClear} clears the specified \code{bit} in the \code{bitSet} 2468 and returns the updated bitset. The input bitset will be modified. 2469 2470 \code{psBitSetOp} returns the \code{psBitSet} that is the result of 2471 performing the specified \code{operator} (one of \code{"AND"}, 2472 \code{"OR"}, or \code{"XOR"}) on \code{inBitSet1} and \code{inBitSet2}. 2473 If the output bitset \code{outBitSet} is \code{NULL}, it is created by 2474 the function. 2475 2476 \code{psBitSetNot} applies a unary \code{NOT} to a bitset, placing the 2477 answer in the bitset \code{out}, or creating a new bitset if 2478 \code{out} is \code{NULL}. 2479 2480 \code{psBitSetTest} returns a true value if the specified \code{bit} 2481 is set; otherwise, it returns a false value. 2482 2483 Finally, \code{psBitSetToString} returns a string representation of 2484 the specified \code{bits}. 2485 2486 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2487 2488 \section{Rich Data Structures and I/O} 2489 2490 \subsection{Metadata} 2491 \label{sec:metadata} 2492 2493 \subsubsection{Conceptual Overview} 2494 2495 Within PSLib, we provide a data structure to carry metadata and 2496 mechanisms to manipulate the metadata. Metadata is a general concept 2497 that requires some discussion. In any data analysis task, the 2498 ensemble of all possible data may be divided into two or three 2499 classes: there is the specific data of interest, there is data which 2500 is related or critical but not the primary data of interest, and there 2501 is all of the other data which may or may not be interesting. For 2502 example, consider a simple 2D image obtained of a galaxy from a CCD 2503 camera on a telescope. If you want to study the galaxy, the specific 2504 data of interest is the collection of pixels. There are a variety of 2505 other pieces of data which are closely related and crucial to 2506 understanding the data in those pixels, such as the dimensions of the 2507 image, the coordinate system, the time of the image, the exposure 2508 time, and so forth. Other data may be known which may be less 2509 critical to understanding the image, but which may be interesting or 2510 desired at a later date. For example, the observer who took the 2511 image, the filter manufacturer, the humidity at the telescope, etc. 2512 2513 Formally, all of the related data which describe the principal data of 2514 interest are metadata. Note that which piece is the metadata and 2515 which is the data may depend on the context. If you are examining the 2516 pixels in an image, the coordinate and flux of an object may be part 2517 of the metadata. However, if you are analyzing a collection of 2518 objects extracted from an image, you may consider then pixel data 2519 simply part of the metadata associated with the list of objects. 2520 2521 There are various ways to handle metadata vs data within a programming 2522 environment. In C, it is convenient to use structures to group 2523 associated data together. One possibility is to define the metadata 2524 as part of the associated data structure. For example, the image data 2525 structure would have elements for all possible associated measurement. 2526 This approach is both cumbersome (because of the large number metadata 2527 types), impractical (because the full range of necessary metadata is 2528 difficult to know in advance) and inflexible (because any change in 2529 the collection of metadata requires addition of new structure elements 2530 and recompilation). 2531 2532 An alternative is to place the metadata in a generic container and use 2533 lookup mechanisms to extract the appropriate metadata when needed. An 2534 example of this is would be a text-based FITS header for an image read 2535 into a flat text buffer. In this implementation, metadata lookup 2536 functions could return the current value of, for example, NAXIS1 (the 2537 number of columns of the image) by scanning through the header buffer. 2538 This method has the benefits of flexibility and simplicity of 2539 programming interface, but it has the disadvantage that all metadata 2540 is accessed though this lookup mechanism. This may make the code less 2541 readable and it may slow down the access. 2542 2543 PSLib implements an intermediate solution to this problem. We specify 2544 a flexible, generic metadata container and access methods. Data types 2545 which require association with a general collection of metadata should 2546 include an entry of this metadata type. However, a subset of metadata 2547 concepts which are basic and frequently required may be placed in the 2548 coded structure elements. This approach allows the code to refer to 2549 the basic metadata concepts as part of the data structure (ie, 2550 \code{image.nx}), but also allows us to provide access to any 2551 arbitrary metadata which may be generated. As a practical matter, the 2552 choice of which entries are only in the metadata and which are part of 2553 the explicit structure elements is rather subjective. Any data 2554 elements which are frequently used should be put in the structure; 2555 those which are only infrequently needed should be left in the generic 2556 metadata. 2557 2558 There are some points of caution which must be noted. Any 2559 manipulation of the data should be reflected in the metadata where 2560 appropriate. This is always an issue of concern. For example, 2561 consider an image of dimensions \code{nx, ny}. If a function extracts 2562 a subraster, it must change the values of \code{nx, ny} to match the 2563 new dimensions. What should it do to the corresponding metadata? 2564 Clearly, it should change the corresponding value which defines 2565 \code{nX, nY}. However, it is not quite so simple: there may be other 2566 metadata values which depend on those values. These must also be 2567 changed appropriately. What if the metadata element points to a 2568 copy of the metadata which may be shared by other representations of 2569 the image? These must be treated differently because the change would 2570 invalidate those other references. Care must be taken, therefore, 2571 when writing functions which operate on the data to consider all of 2572 the relevant metadata entries which must also be updated. 2573 2574 A related issue is the definition of metadata names. Entries in a 2575 structure have the advantage of being hardwired: every instance of 2576 that structure will have the same name for the same entry. This is 2577 not necessarily the case with a more flexible metadata container. The 2578 image exposure time is a notorious example in astronomy. Different 2579 observatories use different header keywords (ie, metadata names) for 2580 the same concept of the exposure time (\code{EXPTIME}, 2581 \code{EXPOSURE}, \code{OPENTIME}, \code{INTTIME}, etc). Any system 2582 which operates on these metadata needs to address the issue of 2583 identifying these names. This issue seems like an argument for 2584 hardwiring metadata in the structure, but in fact it does not present 2585 such a strong case. If the metadata are hardwired, some function will 2586 still have to know how to interpret the various names to populate the 2587 structure. The concept can still be localized with generic metadata 2588 containers by including abstract metadata names within the code which 2589 are tied to the various implementations-specific metadata names. 2590 2591 \subsubsection{Metadata Representation} 2592 2593 \begin{figure} 2594 \psfig{file=Metadata,width=6.5in} 2595 \caption{Metadata Structures\label{fig:metadata}} 2596 \end{figure} 2597 2598 This section addresses the question of how \PS{} metadata should be 2599 represented in memory, not how it should be represented on disk. 2600 2601 We define an item of metadata with the following structure: 2602 \filbreak 2603 \begin{datatype} 2604 typedef struct { 2605 const psS32 id; ///< unique ID for this item 2606 char *name; ///< Name of item 2607 psMetadataType type; ///< type of this item 2608 const union { 2609 psS32 S32; ///< integer data 2610 psF32 F32; ///< floating-point data 2611 psF64 F64; ///< double-precision data 2612 psList *list; ///< psList entry 2613 psMetadata *md; ///< psMetadata entry 2614 psPtr V; ///< other type 2615 } data; ///< value of metadata 2616 char *comment; ///< optional comment ("", not NULL) 2617 } psMetadataItem; 2618 \end{datatype} 2619 2620 The \code{id} is a unique identifier for this item of metadata; 2621 experience shows that such tags are useful. The entry \code{name} 2622 specifies the name of the metadata item. The value of the metadata is 2623 given by the union \code{data}, and may be of type \code{psS32}, 2624 \code{psF32}, \code{psF64}, or an arbitrary rich structure pointed at 2625 by the \code{void} pointer \code{V}. A character string comment 2626 associated with this metadata item may be stored in the element 2627 \code{comment}. The \code{type} entry specifies how to interpret the 2628 type of the data being represented, given by the enumerated type 2629 \code{psMetadataType}: 2630 % 2631 \filbreak 2632 \begin{datatype} 2633 typedef enum { ///< type of item.data is: 2634 PS_META_S32 = PS_TYPE_S32, ///< psS32 primitive data. 2635 PS_META_F32 = PS_TYPE_F32, ///< psF32 primitive data. 2636 PS_META_F64 = PS_TYPE_F64, ///< psF64 primitive data. 2637 PS_META_BOOL = PS_TYPE_BOOL, ///< psBool primitive data. 2638 PS_META_LIST = 0x10000, ///< List data (Stored as item.data.list). 2639 PS_META_STR, ///< String data (Stored as item.data.V). 2640 PS_META_META, ///< Metadata (Stored as item.data.md). 2641 PS_META_VEC, ///< Vector data (Stored as item.data.V). 2642 PS_META_IMG, ///< Image data (Stored as item.data.V). 2643 PS_META_HASH, ///< Hash data (Stored as item.data.V). 2644 PS_META_LOOKUPTABLE, ///< Lookup table data (Stored as item.data.V). 2645 PS_META_JPEG, ///< JPEG data (Stored as item.data.V). 2646 PS_META_PNG, ///< PNG data (Stored as item.data.V). 2647 PS_META_ASTROM, ///< Astrometric coefficients (Stored as item.data.V). 2648 PS_META_TIME, ///< psTime object (Stored as item.data.V). 2649 PS_META_UNKNOWN, ///< Other data (Stored as item.data.V). 2650 PS_META_MULTI ///< Used internally, do not create a metadata item of this type. 2651 } psMetadataType; 2652 \end{datatype} 2653 The macro \code{PS_META_IS_PRIMITIVE(psMetadataType.type)} returns 2654 true if the type is one of the primitive data types (S32, F64, etc). 2655 In such a case, the data value is directly available. Otherwise, a 2656 pointer to the data is available. 2657 2658 A collection of metadata is represented by the \code{psMetadata} structure: 2659 \begin{datatype} 2660 typedef struct { 2661 psList *list; ///< list of psMetadataItem 2662 psHash *hash; ///< hash table of the same metadata 2663 void *lock; ///< Optional lock for thread safety 2664 }} psMetadata; 2665 \end{datatype} 2666 The type \code{psMetadata} is a container class for metadata. Note 2667 that there are in fact \emph{two} representations of the metadata 2668 (each \code{psMetadataItem} appears on both). The first 2669 representation employs a doubly-linked list that allows the order of 2670 the metadata to be preserved (e.g., if FITS headers are read in a 2671 particular order, they should be written in the same order). The 2672 second representation employs a hash table which allows fast look-up 2673 given a specific metadata keyword. 2674 2675 Certain metadata names (such as the FITS keywords \code{COMMENT} and 2676 \code{HISTORY} in a FITS header) may be repeated with different 2677 values. In such a case, the \code{psMetadata.list} structure contains 2678 the entries in their original sequence with duplicate keys. The 2679 \code{psMetadata.hash} entries, which are required to have unique 2680 keys, would have a single entry with the keyword of the repeated key, 2681 with the value of \code{psMetadataType} set to \code{PS_META_MULTI}, 2682 and the \code{psMetadataItem.data} element pointing to a \code{psList} 2683 containing the actual entries. If \code{psMetadataItemAlloc} is 2684 called with the type set to \code{PS_META_MULTI}, such a repeated key 2685 is created. In this case, the data value passed to 2686 \code{psMetadataItemAlloc} (the quantity in ellipsis) must be 2687 \code{NULL}. An empty \code{psMetadataItem} with the given keyword is 2688 created to hold future entries of that keyword. 2689 2690 As a convenience to the user, the following type-specific functions are 2691 also defined: 2692 \begin{prototype} 2693 psMetadataItem* psMetadataItemAllocStr(const char* name, const char* comment, const char* value); 2694 psMetadataItem* psMetadataItemAllocF32(const char* name, const char* comment, psF32 value); 2695 psMetadataItem* psMetadataItemAllocF64(const char* name, const char* comment, psF64 value); 2696 psMetadataItem* psMetadataItemAllocS32(const char* name, const char* comment, psS32 value); 2697 psMetadataItem* psMetadataItemAllocBool(const char* name, const char* comment, bool value); 2698 psMetadataItem* psMetadataItemAllocPtr(const char* name, psMetadataType type, const char* comment, psPtr value); 2699 \end{prototype} 2700 2701 \subsubsection{Metadata APIs} 2702 2703 \begin{prototype} 2704 psMetadata *psMetadataAlloc(void); 2705 \end{prototype} 2706 2707 The constructor for the collection of metadata, \code{psMetadata}, 2708 simply returns an empty metadata container (employing the constructors 2709 for the doubly-linked list and hash table). The destructor needs to 2710 free each of the \code{psMetadataItem}s. 2711 2712 \begin{prototype} 2713 psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...); 2714 psMetadataItem *psMetadataItemAllocV(const char *name, psMetadataType type, const char *comment, va_list list); 2715 \end{prototype} 2716 2717 The allocator for \code{psMetadataItem} returns a full 2718 \code{psMetadataItem} ready for insertion into the \code{psMetadata}. 2719 The \code{name} entry specifies the name to use for this metadata 2720 item, and may include \code{sprintf}-type formating codes. The 2721 \code{comment} entry is a fixed string which is used for the comment 2722 associated with this metadata item. The metadata data and the 2723 arguments to the \code{name} formatting codes are passed, in that 2724 order (metadata pointer first), to \code{psMetadataItemAlloc} as 2725 arguments following the comment string. The data must be a pointer 2726 for any data types which are stored in the element \code{data.void}, 2727 while other data types are passed as numeric values. The argument 2728 list must be interpreted appropriately by the \code{va_list} operators 2729 in the function. 2730 2731 \begin{prototype} 2732 bool psMetadataAddItem(psMetadata *md, const psMetadataItem *item, psS32 location, psS32 flags); 2733 bool psMetadataAdd(psMetadata *md, int location, const char *name, int format, const char *comment, ...); 2734 bool psMetadataAddV(psMetadata *md, int location, const char *name, int format, const char *comment, 2735 va_list list); 2736 \end{prototype} 2737 2738 Items may be added to the metadata in one of two ways --- firstly, an 2739 item may be added by appending a \code{psMetadataItem} which has 2740 already been created; and secondly by directly providing the data to 2741 be appended. In both cases, the return value defines the success 2742 (\code{true}) or failure of the operation. The second function, 2743 \code{psMetadataAdd} takes a pointer or value which is interpreted by 2744 the function using variadic argument interpretation. The third 2745 version is the \code{va_list} version of the second function. All 2746 three functions take a parameter, \code{location}, which specifies 2747 where in the list to place the element, following the conventions for 2748 the \code{psList}. The entry \code{mode} for \code{psMetadataAddItem} 2749 is a bit mask constructed by OR-ing the allowed option flags (eg, 2750 \code{PS_META_REPLACE}) which specify minor variations on the 2751 behavior. The \code{format} entry, which specifies both the metadata 2752 type and the optional flags, is constructed by bit-wise OR-ing the 2753 appropriate \code{psMetadataType} and allowed option flags. Care 2754 should be taken not to leak memory when appending an item for which 2755 the key already exists in the metadata (and is not 2756 \code{PS_META_MULTI}). 2757 % 2758 2759 \begin{datatype} 2760 typedef enum { ///< option flags for psMetadata functions 2761 PS_META_DEFAULT = 0, ///< default behavior (0x0000) for use in mode above 2762 PS_META_REPLACE = 0x1000000 ///< allow entry to be replaced 2763 PS_META_DUPLICATE_OK = 0x2000000 ///< allow duplicate entries 2764 PS_META_NULL = 0x4000000 ///< psMetadataItem.data is a NULL value 2765 } psMetadataFlags; 2766 \end{datatype} 2767 2768 The functions above take option flags which modify the behavior when 2769 metadata items are added to the metadata list. These flags must be 2770 bit-exclusive of those used above for the \code{psMetadataTypes}. The 2771 flags have the following meanings: 2772 2773 \code{PS_META_DEFAULT}: This is the zero bit mask, to allow the 2774 default behavior for \code{psMetadataAddItem} above. If this is OR-ed 2775 with a \code{psMetadataType}, the result is as if no OR-ing took 2776 place. 2777 2778 \code{PS_META_REPLACE}: Replace an existing, unique entry. If the 2779 given metadata item exists in the metadata collection, and is not of 2780 type \code{PS_META_MULTI}, then the item replaces the existing entry. 2781 2782 \code{PS_META_DUPLICATE_OK}: Allow the new metadata item key to be a 2783 duplicate (ie, \code{PS_META_MULTI}). If an existing item with the 2784 same key is already \code{PS_META_MULTI}, the new item is added to the 2785 \code{PS_META_MULTI} list. If the existing item is not 2786 \code{PS_META_MULTI}, a \code{PS_META_MULTI} list is created to 2787 contain both the existing item and the new item. The original entry's 2788 location on the psMetadata.list must be maintained. 2789 2790 \code{PS_META_NULL}: Indicates that \code{psMetadataItem.data} should be 2791 ignored and that the the current value is ``NULL'' or undefined. The 2792 \code{psMetadataItem} must have a proper \code{type} set and it's \code{data} 2793 field shall have a valid value. e.g. A \code{type} of \code{PS_META_STR} would 2794 require that 's \code{data} is set to \code{NULL}. 2795 2796 There are several of cases to handle for duplication of an existing 2797 key by a new key, some identified above. The following situations 2798 must also be handled: 2799 2800 If the new key already exists, but is not \code{PS_META_MULTI}, and 2801 the new item is not flagged as either \code{PS_META_DUPLICATE_OK} or 2802 \code{PS_META_REPLACE}, an error is raised. 2803 2804 If the new key already exists, and the existing item is 2805 \code{PS_META_MULTI}, the new item is added to the MULTI list. Note 2806 that if the new item is also of type \code{PS_META_MULTI}, no action 2807 is taken, but a successful exit status is returned (the action of 2808 adding a \code{PS_META_MULTI} item to the metadata is equivalent to 2809 setting that key to be tagged as \code{PS_META_MULTI}. If it is 2810 {\em already} \code{PS_META_MULTI}, this effect has already been 2811 achieved). 2812 2813 An example of code to use these metadata APIs to generate the 2814 structure seen in Figure~\ref{fig:metadata} is given below. 2815 2816 \begin{verbatim} 2817 md = psMetadataAlloc(); 2818 2819 psMetadataAdd(md, PS_LIST_TAIL, "SIMPLE", PS_META_BOOL, "basic fits", TRUE); 2820 psMetadataAdd(md, PS_LIST_TAIL, "BLANK", PS_META_S32, "invalid pixel data", -32768); 2821 psMetadataAdd(md, PS_LIST_TAIL, "DATE-OBS", PS_META_STR, "observing date UT", " 2004-6-16"); 2822 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_LIST, "head of comment block", NULL); 2823 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "DATA"); 2824 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "PARAMS"); 2825 psMetadataAdd(md, PS_LIST_TAIL, "EXPTIME", PS_META_F32, "exposure time (sec)", 1.05); 2826 psMetadataAdd(md, PS_LIST_TAIL, "COMMENT", PS_META_STR, "", "FOO"); 2827 2828 cell = psMetadataAlloc(); 2829 psMetadataAdd(cell, PS_LIST_TAIL, "EXTNAME", PS_META_STR, "", "CCD00"); 2830 psMetadataAdd(cell, PS_LIST_TAIL, "BIASNAME", PS_META_STR, "", "BSEC-00"); 2831 psMetadataAdd(cell, PS_LIST_TAIL, "CHIP", PS_META_STR, "", "CHIP.00"); 2832 psMetadataAdd(md, PS_LIST_TAIL, "CELL.00", PS_META_META, "", cell); 2833 2834 cell = psMetadataAlloc(); 2835 psMetadataAdd(cell, PS_LIST_TAIL, "EXTNAME", PS_META_STR, "", "CCD01"); 2836 psMetadataAdd(cell, PS_LIST_TAIL, "BIASNAME", PS_META_STR, "", "BSEC-01"); 2837 psMetadataAdd(cell, PS_LIST_TAIL, "CHIP", PS_META_STR, "", "CHIP.01"); 2838 psMetadataAdd(md, PS_LIST_TAIL, "CELL.01", PS_META_META, "", cell); 2839 \end{verbatim} 2840 2841 The following code shows how to use the APIs to replace one of these values: 2842 \begin{verbatim} 2843 psMetadataAdd(md, PS_LIST_TAIL, "EXPTIME", PS_META_F32 | PS_REPLACE, "new exposure time (sec)", 2.05); 2844 \end{verbatim} 2845 2846 As a convenience to the user, the following type-specific functions 2847 are specified: 2848 \begin{prototype} 2849 bool psMetadataAddStr(psMetadata* md, psS32 location, const char* name, const char* comment, 2850 const char* value); 2851 bool psMetadataAddS32(psMetadata* md, psS32 location, const char* name, const char* comment, psS32 value); 2852 bool psMetadataAddF32(psMetadata* md, psS32 location, const char* name, const char* comment, psF32 value); 2853 bool psMetadataAddF64(psMetadata* md, psS32 location, const char* name, const char* comment, psF64 value); 2854 bool psMetadataAddBool(psMetadata* md, psS32 location, const char* name, const char* comment, bool value); 2855 bool psMetadataAddPtr(psMetadata* md, psS32 location, const char* name, psMetadataType type, 2856 const char* comment, psPtr value); 2857 \end{prototype} 2858 2859 2860 Items may be removed from the metadata by specifying a key or a 2861 location in the list. If the value of \code{name} is \code{NULL}, the 2862 value of \code{location} is used. If the value of \code{name} is not 2863 \code{NULL}, then \code{location} must be set to 2864 \code{PS_LIST_UNKNOWN}. If the key matches a metadata item, the item 2865 is removed from the metadata and \code{true} is returned; otherwise, 2866 \code{false} is returned. If the key is not unique, then \emph{all} 2867 items corresponding to the key are removed, and \code{true} is 2868 returned. 2869 % 2870 \begin{prototype} 2871 bool psMetadataRemove(psMetadata *md, int location, const char *key); 2872 \end{prototype} 2873 2874 Items may be found within the metadata by providing a key. In the 2875 event that the key is non-unique, the first item is returned. 2876 \begin{prototype} 2877 psMetadataItem *psMetadataLookup(const psMetadata *md, const char *key); 2878 \end{prototype} 2879 2880 Several utility functions are provided for simple cases. These 2881 functions perform the effort of casting the data to the appropriate 2882 type. The numerical functions shall return 0.0 if their key is not 2883 found. If the pointer value of \code{status} is not \code{NULL}, it 2884 is set to reflect the success or failure of the lookup. 2885 \begin{prototype} 2886 psPtr psMetadataLookupStr(bool *status, const psMetadata *md, const char *key); 2887 psS32 psMetadataLookupS32(bool *status, const psMetadata *md, const char *key); 2888 psF32 psMetadataLookupF32(bool *status, const psMetadata *md, const char *key); 2889 psF64 psMetadataLookupF64(bool *status, const psMetadata *md, const char *key); 2890 bool psMetadataLookupBool(bool *status, const psMetadata *md, const char *key); 2891 psPtr psMetadataLookupPtr(bool *status, const psMetadata *md, const char *key); 2892 \end{prototype} 2893 2894 Items may be retrieved from the metadata by their entry position. The 2895 value of which specifies the desired entry in the fashion of 2896 \code{psList}. 2897 \begin{prototype} 2898 psMetadataItem *psMetadataGet(const psMetadata *md, int location); 2899 \end{prototype} 2900 2901 The metadata list component may be iterated over by using a 2902 \code{psMetadataIterator} in a fashion equivalent to the 2903 \code{psListIterator}: 2904 \begin{datatype} 2905 typedef struct { 2906 psListIterator* iter; ///< iterator for the psMetadata's psList 2907 regex_t* regex; ///< the subsetting regular expression 2908 } psMetadataIterator; 2909 \end{datatype} 2910 2911 The iterator may be set to a location in the \code{psMetadata} list, 2912 and the user may get the previous or next item in the list relative to 2913 that location. \code{psMetadataGetNext} has the ability to match the 2914 key using a POSIX \code{regex}, e.g., if the user only wants to 2915 iterate through \code{IPP.machines.sky} and doesn't want to bother 2916 with \code{IPP.machines.detector}. The iterator should iterate over 2917 every item in the metadata list, even those that are contained in a 2918 \code{PS_META_LIST}. The value \code{iterator} specifies the iterator 2919 to be used. In setting the iterator, the position of the iterator is 2920 defined by \code{location}, which follows the conventions of the 2921 \code{psList} iterators. 2922 \begin{prototype} 2923 psMetadataIterator *psMetadataIteratorAlloc(psMetadata *md, int location, const char *regex); 2924 bool psMetadataIteratorSet(psMetadataIterator *iterator, int location); 2925 psMetadataItem *psMetadataGetAndIncrement(psMetadataIterator *iterator); 2926 psMetadataItem *psMetadataGetAndDecrement(psMetadataIterator *iterator); 2927 \end{prototype} 2928 2929 Metadata items may be printed to an open file descriptor based on a 2930 provided format. The format string is an sprintf format statement 2931 with exactly one \% formatting command. If the metadata item type is 2932 a numeric type, this formatting command must also be numeric, and type 2933 conversion performed to the value to match the format type. If the 2934 metadata item type is a string, the formatting command must also be 2935 for a string (\%s type of command). If the metadata type is any other 2936 data type, printing is not allowed. 2937 \begin{prototype} 2938 bool psMetadataItemPrint(FILE *fd, const char *format, const psMetadataItem *item); 2939 \end{prototype} 2940 2941 \subsubsection{Configuration files} 2942 \label{sec:configspec} 2943 2944 It will be necessary for the \PS{} system, in order to load 2945 pre-defined settings, to parse a configuration file into a 2946 \code{psMetadata} structure. This shall be performed by the 2947 function \code{psMetadataConfigParse}, as described below. 2948 2949 \begin{prototype} 2950 psMetadata *psMetadataConfigParse(psMetadata *md, int *nFail, const char *filename, bool overwrite); 2951 \end{prototype} 2952 2953 Given a metadata container, \code{md}, and the name of a configuration 2954 file, \code{filename}, \code{psMetadataConfigParse} shall parse the 2955 configuration file, placing the contained key/type/value/comment quads 2956 into the metadata, and returning a pointer to the metadata structure. 2957 The number of lines that failed to parse is returned in \code{nFail}. 2958 Multiple specifications of a key that haven't been declared (see 2959 below) are overwritten if and only if \code{overwrite} is \code{true}. 2960 If the metadata container is \code{NULL}, it shall be allocated. 2961 2962 On error, the function shall return \code{NULL}. 2963 2964 It is also useful to be able to convert a \code{psMetadata} structure into the 2965 Configuration File format for debugging purposes and to enable persistent 2966 configuration. 2967 2968 \begin{prototype} 2969 char *psMetadataConfigFormat(psMetadata *md); 2970 bool psMetadataConfigWrite(psMetadata *md, const char *filename); 2971 \end{prototype} 2972 2973 The \code{psMetadataConfigFormat} function converts a \code{psMetadata} 2974 structure (including any nested \code{psMetadata}) into a Configuration File 2975 formatted string. A \code{NULL} shall be returned on error. The 2976 \code{psMetadataConfigWrite} behaves the same as \code{psMetadataConfigFormat} 2977 except that the string is written out to \code{filename}. \code{false} is 2978 returned on failure. 2979 2980 \paragraph{Comments} 2981 2982 The configuration file shall consist of plain text with 2983 key/type/value/comment quads on separate lines. Blank lines, 2984 including those consisting solely of whitespace (both spaces and 2985 tabs), shall be ignored, as shall lines that commence with the comment 2986 character (a hash mark, \code{#}), either immediately at the start of 2987 the line, or preceded by whitespace. The key/type/value/comment quads 2988 shall all lie on a single line, separated by whitespace. 2989 2990 The key shall be first, possibly preceded on the line by whitespace 2991 which should not form part of the key. 2992 2993 \paragraph{NULL values} 2994 2995 The ``value'' of a quad may be declare to be undefined with the \code{NULL} 2996 keyword. \code{NULL} is allowed to co-exist with a ``comment'' and may be 2997 surrounded by whitespace. Any non-whitespace character will cause of the 2998 ``value'' to be interpreted as a string. 2999 3000 \begin{verbatim} 3001 foo STR NULL # string with a NULL value 3002 bar STR NULL a # string with a value of "NULL a" 3003 \end{verbatim} 3004 3005 \paragraph{Types} 3006 \subparagraph{Scalar \& Vector} 3007 3008 Next, to assist the casting of the value, shall be a string identifying the 3009 type of the value, which shall correspond to one of the simple types supported 3010 in \code{psMetadata}: \code{STRING,BOOL,S32,F32,F64}; \code{STR} may be used to 3011 abbreviate \code{STRING}; valid time types are \code{UTC,UT1,TAI,TT}. 3012 3013 \tbd{May, in the future, require more types, including U8,S16,C64, 3014 which will also necessitate updating the definition of psMetadata.} 3015 3016 The value shall follow the type: strings may consist of multiple words, and 3017 shall have all leading and trailing whitespace removed; booleans shall simply 3018 be either \code{T} or \code{F}. Time type values will be in the ISO8601 3019 compatible format of "YYYY-MM-DDTHH:MM:SS,sZ". When parsed, time types shall 3020 be represented as a \code{psTime} object. 3021 3022 Following the value may be an optional comment, preceded by a comment 3023 character (a hash mark, \code{#}), which in the case of a string 3024 value, serves to mark the end of the value, and for other types serves 3025 to identify the comment to the reader. Only one comment character may 3026 be present on any single line (i.e., neither strings nor comments are 3027 permitted to contain the comment character). The comment may consist 3028 of multiple words, and shall have leading and trailing whitespace 3029 removed. 3030 3031 One wrinkle is the specification of vectors. Keys for which the value 3032 is to be parsed as a vector shall be preceded immediately by a 3033 ``vector symbol'', which we choose to be the ``at'' sign, \code{@}. 3034 In this case, the type shall be interpreted as the type for the 3035 vector, which may be any of the signed or unsigned integer or floating 3036 point types (\code{U8,U16,U32,U64,S8,S16,S32,S32,S64,F32,F64}) but not 3037 the complex floating point types; and the value shall consist of 3038 multiple numbers, separated either by a comma or whitespace. These 3039 values shall populate a \code{psVector} of the appropriate type in the 3040 order in which they appear in the configuration file. 3041 3042 \tbd{May add complex types, likely to be specified with values such as 3043 1.23+4.56i in the future.} 3044 3045 \tbd{May add null, Not-a-Number (NaN), de-normalized, underflow, overflow, 3046 and/or +/-infinity values for selected types.} 3047 3048 \subparagraph{MULTI} 3049 3050 An additional hurdle is the specification of keys that may be non-unique (such 3051 as the \code{COMMENT} keyword in a FITS header). These keys shall be specified 3052 in the configuration file as non-unique with a \code{MULTI} declaration. In 3053 the form \code{[keyword] MULTI}. No other data may be provided on this line, 3054 though a comment, preceded by the comment marker, is valid. A warning shall 3055 be produced when a key which has not been specified to be non-unique is 3056 repeated; in this case, the former value shall be overwritten if 3057 \code{overwrite} is \code{true}, otherwise the line shall be ignored and 3058 counted as one that could not be parsed. It should be noted that non-unique 3059 keys may be of mixed type (even the \code{TYPE} and \code{METADATA} complex 3060 types). For example: 3061 \begin{verbatim} 3062 comment MULTI # a comment 3063 comment STR some string 3064 comment F32 1.23456 3065 comment BOOL T 3066 \end{verbatim} 3067 3068 If a line does not conform to the rules laid out here, a warning shall 3069 be generated, it shall be ignored and counted as a line that could not 3070 be parsed. The total number of lines that were not able to be parsed 3071 (including those that were ignored because \code{overwrite} is 3072 \code{false}, and any other parsing problems, but not including blank 3073 lines and comment lines) shall be returned by the function in the 3074 argument \code{nFail}. 3075 3076 Here are some examples of lines of a valid configuration file: 3077 \filbreak 3078 \begin{verbatim} 3079 Double F64 1.23456789 # This is a comment 3080 Float F32 0.98765 # This is a comment too 3081 String STR This is the string that forms the value #comment 3082 3083 # This is a comment line and is to be ignored 3084 boolean BOOL T # The value of `boolean' is `true' 3085 3086 @primes U8 2,3 5 7,11,13 17 # These are prime numbers 3087 3088 comment MULTI # The rest of this line is ignored, but `comment' is set to be non-unique 3089 comment STR This 3090 comment STR is 3091 comment STR a 3092 comment STR non-unique 3093 comment STR key 3094 Float F64 1.23456 # This generates a warning, and, if `overwrite' is `false', is ignored 3095 \end{verbatim} 3096 3097 Of course, a real configuration file should look much nicer to humans 3098 than the above example, but PSLib must be able to parse such ugly 3099 files. 3100 3101 \paragraph{Complex Types} 3102 \subparagraph{TYPE} 3103 3104 We support a modest tree structure by defining a reserved keyword \code{TYPE}. 3105 Any line in the config file which starts with the word \code{TYPE} shall be 3106 interpreted as defining a new valid type. The defined type name follows the 3107 word \code{TYPE}, and is in turn followed by an arbitrary number of words. 3108 These words are to be interpreted as the names of an embedded \code{psMetadata} 3109 entry, where the values are given on any line which (following the \code{TYPE} 3110 definition) employs the new type name. For example, a new type may be defined 3111 as: 3112 \begin{verbatim} 3113 TYPE CELL EXTNAME BIASSEC CHIP 3114 CELL.00 CELL CCD00 BSEC-00 CHIP.00 3115 CELL.01 CELL CCD01 BSEC-01 CHIP.00 3116 \end{verbatim} 3117 3118 When \code{psMetadataConfigParse} encounters the \code{TYPE} line, it 3119 should construct a \code{psMetadata} container and fill it with 3120 \code{psMetadataItems} having the names \code{EXTNAME, BIASSEC, CHIP}, 3121 with type \code{PS_META_STR}, but data allocated. When it next 3122 encounters an entry of type \code{CELL}, it should then use the given 3123 name (e.g., \code{CELL.00}) for the \code{psMetadataItem}, and copy 3124 the \code{psMetadata} data onto the \code{psMetadataItem.data.md} 3125 entry, filling in the values from the rest of the line (\code{CCD00, 3126 BSEC-00, CHIP.00}). This hierarchical structure is illustrated in 3127 Figure~\ref{fig:metadata}. 3128 3129 \subparagraph{METADATA} 3130 3131 Another way to form a tree-like structure is to directly define a 3132 \code{psMetadata} entry using a sequence of successive lines to define the 3133 values of the \code{psMetadataItem} entries. The initial line defines the new 3134 \code{psMetadata} entry and its name. The following lines have the same format 3135 as the other metadata config file entries. The sequence is terminated with a 3136 line with a single word \code{END}. For example, a metadata entry may be 3137 defined as: 3138 \begin{verbatim} 3139 CELL METADATA 3140 EXTNAME STR CCD00 3141 BIASSEC STR BSEC-00 3142 CHIP STR CHIP.00 3143 NCELL S32 24 3144 END 3145 \end{verbatim} 3146 3147 \paragraph{Scoping Rules} 3148 3149 A simple set of ``Scoping Rules'' are required to properly parse a 3150 configuration file. ``Scope'' refers to the current ``level'' of 3151 \code{METADATA} that a statement appears in. Statements that are not contained 3152 in a nested \code{METADATA} are said to be in the ``Top level scope''. Each 3153 level of nested \code{METADATA} statements create a new ``lower level scope''. 3154 3155 \begin{itemize} 3156 \item 3157 Variable names are unique only to the current level of scope. 3158 3159 \item 3160 non-unique keywords (\code{MULTI}) apply only to the current scope. i.e. They 3161 are invalid in ``higher'' or ``lower'' level scopes. 3162 3163 \item 3164 \code{TYPE} declarations apply only to the current scope. 3165 3166 \item 3167 \code{METADATA} declarations must begin and end in the same scope. i.e. They 3168 may not be declared and end in two different nested METADATA and the same 3169 depth. 3170 \end{itemize} 3171 3172 A series of test inputs is contained in 3173 \S\ref{sec:configtest}. 3152 \section{Input/Output} 3174 3153 3175 3154 \subsection{XML Functions} … … 3676 3655 fail and return FALSE. 3677 3656 3657 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3658 3678 3659 \pagebreak 3679 3660 \section{Data manipulation} … … 3683 3664 following capabilities: 3684 3665 \begin{itemize} 3685 \item Bit masks;3686 3666 \item Vector and image arithmetic; 3687 3667 \item Sorting; … … 3689 3669 \item Matrix operations and linear algebra; 3690 3670 \item (Fast) Fourier Transforms; 3691 \item General functions; and3671 \item General mathematical functions; and 3692 3672 \item Minimization and fitting routines. 3693 3673 \end{itemize} … … 3732 3712 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3733 3713 3734 \subsection{Statistic sFunctions}3735 3736 \subsubsection{ Vector Statistics}3714 \subsection{Statistical Functions} 3715 3716 \subsubsection{Statistical measures} 3737 3717 3738 3718 We require a very general statistics function, which, given a vector … … 4246 4226 4247 4227 %% \subsubsubsection{Pre-defined Functions for LM} 4248 4228 %% 4249 4229 %% We define some commonly used functions for use with the LM 4250 4230 %% minimization, used for the purpose of performing $\chi^2$ fitting: 4251 4231 %% 4252 4232 %% \begin{prototype} 4253 4233 %% psMinimizeLMChi2Func psMinimizeLMChi2Gauss1D; 4254 4234 %% psMinimizeLMChi2Func psMinimizeLMChi2Gauss2D; 4255 4235 %% \end{prototype} 4256 4236 %% 4257 4237 %% \code{psMinimizeChi2LMGauss1D} shall take as \code{params}, the 4258 4238 %% normalization, center, and standard deviation of a Gaussian to be fit, … … 4260 4240 %% the value of the Gaussian at the value, and the derivatives 4261 4241 %% (\code{deriv}) with respect to each of the parameters. 4262 4242 %% 4263 4243 %% \code{psMinimizeChi2LMGauss2D} shall take, as \code{params}, the 4264 4244 %% normalization, center (two values), standard deviation (two values) … … 4873 4853 the following types: \code{psU8}, \code{psU16}. 4874 4854 4855 \begin{prototype} 4856 psImage *psPixelsToMask(psImage *out, const psPixels *pixels, psRegion region, unsigned int maskVal); 4857 psPixels *psPixelsFromMask(psPixels *out, const psImage *mask, unsigned int maskVal); 4858 \end{prototype} 4859 4860 \code{psPixelsToMask} shall return an image of type U8 with the 4861 \code{pixels} lying within the specified \code{region} set to the 4862 \code{maskVal}. The \code{out} image shall be modified if supplied, 4863 or allocated and returned if \code{NULL}. The size of the output 4864 image shall be \code{region.x1 - region.x0} by \code{region.y1 - 4865 region.y0}, with \code{out->x0 = region.x0} and \code{out->y0 = 4866 region.y0}. In the event that either of \code{pixels} or 4867 \code{region} are \code{NULL}, the function shall generate an error 4868 and return \code{NULL}. 4869 4870 \code{psMaskToPixels} shall return a \code{psPixels} containing the 4871 coordinates in the \code{mask} that match the \code{maskVal}. The 4872 \code{out} pixel list shall be modified if supplied, or allocated and 4873 returned if \code{NULL}. In the event that \code{mask} is 4874 \code{NULL}, the function shall generate an error and return 4875 \code{NULL}. 4875 4876 4876 4877 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% … … 4964 4965 4965 4966 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4967 4966 4968 4967 4969 \subsection{Matrix operations and linear algebra}
Note:
See TracChangeset
for help on using the changeset viewer.
