35 #include <sys/select.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
66 #define G_XML2STRING "gammalib::xml2string(std::string&)"
67 #define G_HTTP_QUERY "gammalib::http_query(str::string&, std::string&)"
70 #define G_PARFORMAT_LENGTH 29
71 #define G_CHAR_BUFFER 256
95 const std::string& chars)
104 std::string::size_type start = arg.find_first_not_of(chars);
105 std::string::size_type stop = arg.find_last_not_of(chars);
108 if (start != std::string::npos && stop != std::string::npos) {
112 result = arg.substr(start, stop-start+1);
132 const std::string& chars)
141 std::string::size_type stop = arg.find_last_not_of(chars);
144 if (stop != std::string::npos) {
145 result = arg.substr(0, stop+1);
169 const std::string& segment,
170 const std::string& replacement)
173 std::string result = arg;
176 std::string::size_type pos = 0;
177 std::string::size_type start = 0;
180 while (start != std::string::npos) {
181 start = result.find(segment, pos);
182 if (start != std::string::npos) {
183 result = result.replace(start, segment.length(), replacement);
184 pos = start + replacement.length();
217 static const char* begin_delim[] = {
"$ENV{",
"$ENV(",
"${",
"$(",
"$",
"~" };
218 static const char* end_delim[] = {
"}",
")",
"}",
")",
"/",
"/" };
219 static const int num_delim = 6;
222 std::string result = arg;
226 bool in_quote =
false;
229 while (index < result.length()) {
233 if (result[index] ==
'\\') {
239 if (result[index] ==
'\'') {
240 in_quote = !in_quote;
253 size_t begin_length = 0;
255 for (; delim_idx < num_delim; ++delim_idx) {
256 size_t len = std::strlen(begin_delim[delim_idx]);
257 if (result.compare(index, len, begin_delim[delim_idx]) == 0) {
264 if (begin_length > 0) {
272 size_t i_start = index + begin_length;
273 size_t i_end = i_start;
274 size_t end_length = 0;
275 if (delim_idx == 4 || delim_idx == 5) {
276 while (i_end < result.length() &&
277 result.compare(i_end, 1,
"/") != 0 &&
278 result.compare(i_end, 1,
" ") != 0) {
283 end_length = std::strlen(end_delim[delim_idx]);
284 while (i_end < result.length() &&
285 result.compare(i_end, end_length, end_delim[delim_idx]) != 0) {
292 if (i_end < result.length() || delim_idx == 4) {
295 std::string name = result.substr(i_start, i_end-i_start);
296 size_t name_length = name.length();
299 const char* env = NULL;
302 if (delim_idx == 5) {
303 if (name_length == 0) {
305 struct passwd *pw = getpwuid(getuid());
315 else if (name ==
"-") {
319 struct passwd *pw = getpwnam(name.c_str());
337 result.erase(index, begin_length+name_length+end_length);
340 std::string replace(env);
341 size_t replace_length = replace.length();
344 result.insert(index, replace);
347 index += replace_length;
394 const std::string& filename)
400 if (pathname.empty()) {
406 filepath = pathname +
"/" + filename;
424 char default_tmpdir[] =
"/tmp";
432 tmpdir = default_tmpdir;
442 strcat(filename, tmpdir);
443 strcat(filename,
"/gammalibXXXXXX");
446 int fd = mkstemp(filename);
447 std::string tmpname(filename);
475 env = std::string(ptr);
491 std::ostringstream s_value;
493 return s_value.str();
505 std::ostringstream s_value;
507 return s_value.str();
519 std::ostringstream s_value;
521 return s_value.str();
533 std::ostringstream s_value;
535 return s_value.str();
547 std::ostringstream s_value;
549 return s_value.str();
566 sprintf(buffer, fmt.c_str(), value);
569 std::string str_buffer(buffer);
584 std::ostringstream s_value;
586 return s_value.str();
598 std::ostringstream s_value;
600 return s_value.str();
618 std::ostringstream s_value;
623 s_value.precision(precision);
624 s_value.setf(std::ios::fixed, std::ios::floatfield);
627 s_value.precision(7);
634 std::string result = s_value.str();
655 std::ostringstream s_value;
660 s_value.precision(precision);
661 s_value.setf(std::ios::fixed, std::ios::floatfield);
664 s_value.precision(15);
671 std::string result = s_value.str();
689 const int& precision)
692 std::ostringstream s_value;
697 s_value.precision(precision);
698 s_value.setf(std::ios::fixed, std::ios::floatfield);
701 s_value.precision(15);
705 s_value << value.real();
706 if (value.imag() < 0.0) {
712 s_value <<
std::abs(value.imag()) <<
"j";
715 std::string result = s_value.str();
730 struct std::tm timeStruct;
735 now = std::time(NULL);
737 std::gmtime_r(&now, &timeStruct);
739 std::memcpy(&timeStruct, gmtime(&now),
sizeof(
struct tm));
743 std::sprintf(buffer,
"%04d-%02d-%02dT%02d:%02d:%02d",
744 timeStruct.tm_year + 1900,
745 timeStruct.tm_mon + 1,
752 std::string date = buffer;
770 char*
str =
new char[arg.length()+1];
773 for (std::size_t i = 0; i < arg.length(); ++i) {
778 str[arg.length()] =
'\0';
793 std::istringstream iss(arg);
795 iss >> std::dec >> result;
808 std::istringstream iss(arg);
809 unsigned short result;
810 iss >> std::dec >> result;
823 std::istringstream iss(arg);
825 iss >> std::dec >> result;
838 std::istringstream iss(arg);
840 iss >> std::dec >> result;
853 std::istringstream iss(arg);
855 iss >> std::dec >> result;
868 std::istringstream iss(arg);
869 unsigned long result;
870 iss >> std::dec >> result;
883 std::istringstream iss(arg);
885 iss >> std::dec >> result;
898 std::istringstream iss(arg);
899 unsigned long long result;
900 iss >> std::dec >> result;
913 std::istringstream iss(arg);
915 iss >> std::dec >> result;
928 std::istringstream iss(arg);
930 iss >> std::dec >> result;
944 std::transform(s.begin(), s.end(), s.begin(),
::toupper);
958 std::transform(s.begin(), s.end(), s.begin(),
::tolower);
984 const std::string& sep)
987 std::vector<std::string> result;
991 std::size_t len = s.length();
994 while (pos < len && pos != std::string::npos) {
998 std::size_t index = s.find_first_of(sep, pos);
999 std::size_t n = std::string::npos;
1003 if (index != std::string::npos) {
1011 if (sep !=
" " && n == 0) {
1012 result.push_back(
"");
1015 result.push_back(s.substr(pos, n));
1019 pos = (index != std::string::npos) ? index + 1 : std::string::npos;
1024 if (sep !=
" " && pos == len) {
1025 result.push_back(
"");
1047 std::string result =
"";
1050 for (
int i = 0; i < n; ++i) {
1073 int n_right = n - s.length();
1076 std::string result = s +
fill(std::string(1,c), n_right);
1097 int n_left = n - s.length();
1100 std::string result =
fill(std::string(1,c), n_left) + s;
1121 int n_right = (n-s.length()) / 2;
1122 int n_left = n - s.length() - n_right;
1125 std::string result =
fill(std::string(1,c), n_left) + s +
1126 fill(std::string(1,c), n_right);
1150 std::string result =
" " + s +
" " +
fill(
".", n_right) +
": ";
1170 std::string result(noun);
1201 const double& epivot,
const double& gamma)
1211 double exponent = gamma + 1.0;
1212 if (
std::abs(exponent) > 1.0e-11) {
1213 double xmin = emin / epivot;
1214 double xmax = emax / epivot;
1215 flux = epivot / exponent * (
std::pow(xmax, exponent) -
1219 double ratio = emax / emin;
1249 const double& epivot,
const double& gamma)
1259 double exponent = gamma + 2.0;
1260 double epivot2 = epivot * epivot;
1261 if (
std::abs(exponent) > 1.0e-11) {
1262 double xmin = emin / epivot;
1263 double xmax = emax / epivot;
1264 flux = epivot2 / exponent * (
std::pow(xmax, exponent) -
1268 double ratio = emax / emin;
1269 flux = epivot2 * (
std::log(ratio));
1296 elogmean.
MeV(
std::pow(10.0, 0.5 * (eloga + elogb)));
1315 bool result =
false;
1324 if (ret == 0 && S_ISDIR(info.st_mode)) {
1345 bool result =
false;
1348 if (str.find(substring) != std::string::npos) {
1367 const std::string&
string)
1370 bool result = std::find(strings.begin(), strings.end(), string) !=
1387 const std::string& message)
1390 #if defined(G_WARNINGS)
1393 std::string
warning =
"+++ WARNING in " + origin +
": " + message;
1396 std::cout << warning << std::endl;
1422 size_t length = arg.length();
1430 while (pos < length) {
1435 start = arg.find(
"&", pos);
1436 if (start != std::string::npos) {
1449 stop = arg.find(
";", pos);
1450 if (stop != std::string::npos) {
1454 result += arg.substr(start-len, len);
1458 std::string cref = arg.substr(start+1, stop-start-1);
1459 len = cref.length();
1464 if (len >= 2 && cref[0] ==
'#') {
1466 if (cref[1] ==
'x') {
1467 number = (int)std::strtol(cref.substr(2,len-2).c_str(), NULL, 16);
1470 number =
toint(cref.substr(1,len-1));
1473 result.push_back((
char)number);
1476 std::string msg =
"Could not extract number from "
1477 "numerical character reference &"+
1487 if (cref ==
"quot") {
1488 result.push_back((
char)34);
1490 else if (cref ==
"amp") {
1491 result.push_back((
char)38);
1493 else if (cref ==
"apos") {
1494 result.push_back((
char)39);
1496 else if (cref ==
"lt") {
1497 result.push_back((
char)60);
1499 else if (cref ==
"gt") {
1500 result.push_back((
char)62);
1503 std::string msg =
"Unknown character entity reference "
1504 "&"+cref+
"; encountered in XML string \""+
1519 std::string msg =
"Missing ; character at end of character "
1520 "reference in XML string \""+arg+
"\".";
1531 result += arg.substr(pos, len);
1555 for (
int i = 0; i < arg.length(); ++i) {
1558 std::string character = arg.substr(i, 1);
1561 if (character ==
"\"") {
1562 character =
""";
1564 else if (character ==
"&") {
1565 character =
"&";
1567 else if (character ==
"'") {
1568 character =
"'";
1570 else if (character ==
"<") {
1573 else if (character ==
">") {
1578 result += character;
1605 for (
int i = 0; i < n; ++i) {
1607 if (element->
attribute(
"name") == name) {
1639 const std::string& name)
1651 for (
int i = 0; i < n; ++i) {
1653 if (element->
attribute(
"name") == name) {
1691 const std::string& name)
1703 for (
int i = 0; i < n; ++i) {
1705 if (element->
attribute(
"name") == name) {
1740 const std::string& name,
1741 const std::string& attribute)
1744 std::string value =
"";
1751 std::string msg =
"Attribute \""+attribute+
"\" not found in XML "
1752 "parameter \""+name+
"\". Please verify the XML "
1785 " child elements in XML file does not correspond "
1787 " elements. Please verify the XML format.";
1793 int npars = xml.
elements(
"parameter");
1794 if (npars != number) {
1795 std::string msg =
"Number of "+
gammalib::str(npars)+
" \"parameter\" "
1796 "child elements in XML file does not correspond to "
1798 " elements. Please verify the XML format.";
1821 const std::string& type)
1830 std::string msg =
"Model type \""+xml.
attribute(
"type")+
"\" is not "
1831 "the expected type \""+type+
"\". Please verify "
1856 const std::string& name,
1861 std::string msg =
"Parameter \""+name+
"\" not found in XML element."
1862 " Please verify the XML format.";
1865 else if (number > 1) {
1866 std::string msg =
"Parameter \""+name+
"\" found "+
1868 " Please verify the XML format.";
1890 const std::string& filename)
1900 size_t access_length = fname.
path().length();
1905 if (access_length == 0) {
1906 if (xml_length > 0) {
1912 else if (fname.
path()[0] !=
'/') {
1916 if (access_length >= xml_length) {
1947 const std::string& filename)
1956 size_t access_length = fname.
path().length();
1958 if (xml_length > 0) {
1959 if (access_length == xml_length) {
1961 fname = fname.
file();
1964 else if (access_length > xml_length) {
1966 std::string relpath = fname.
path().substr(xml_length, access_length-xml_length);
2004 name = text->
text();
2009 ptr = node->
element(
"value", 0);
2013 value = text->
text();
2044 FD_SET(fd, &readset);
2048 if (timeout >= 1000) {
2049 tv.tv_sec = timeout/1000;
2054 tv.tv_usec = timeout*1000;
2058 int result = select(fd+1, &readset, NULL, NULL, &tv);
2064 else if (result > 0 && FD_ISSET(fd, &readset)) {
2070 if ((iof = fcntl(fd, F_GETFL, 0)) != -1) {
2071 fcntl(fd, F_SETFL, iof | O_NONBLOCK);
2075 result =
::recv(fd, buffer, len, flags);
2079 fcntl(fd, F_SETFL, iof);
2108 const double& cosdist,
const double& sindist,
2109 const double& roi,
const double& cosroi)
2116 if (rad > roi) arclength = 0.0;
2128 if (dist > roi) arclength = 0.0;
2134 double d = roi - dist;
2138 else if (rad <= d) {
2144 double cosang = (cosroi - cosdist*cosrad) / (sindist*sinrad);
2146 #if defined(G_CHECK_FOR_NAN)
2149 std::cout <<
"roi_arclength: NaN occured";
2150 std::cout <<
" rad=" << rad;
2151 std::cout <<
" sinrad=" << sinrad;
2152 std::cout <<
" cosrad=" << cosrad;
2153 std::cout <<
" sindist=" << sindist;
2154 std::cout <<
" cosdist=" << cosdist;
2155 std::cout <<
" cosang=" << cosang;
2156 std::cout << std::endl;
2193 bool identity =
false;
2201 else if (b != 0.0) {
2233 const int portno = 80;
2237 char response[4096];
2238 memset(message, 0,
sizeof(message));
2239 memset(response, 0,
sizeof(response));
2242 sprintf(message,
"GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", query.c_str(), host.c_str());
2245 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
2247 std::string msg =
"Unable to open socket.";
2252 struct hostent* server = gethostbyname(host.c_str());
2253 if (server == NULL) {
2254 std::string msg =
"Unable to find host \""+host+
"\".";
2259 struct sockaddr_in serveraddr;
2260 memset(&serveraddr, 0,
sizeof(serveraddr));
2261 serveraddr.sin_family = AF_INET;
2262 memcpy(&serveraddr.sin_addr.s_addr, server->h_addr, server->h_length);
2263 serveraddr.sin_port = htons(portno);
2266 if (connect(sockfd, (
struct sockaddr*)&serveraddr,
sizeof(serveraddr)) < 0) {
2267 std::string msg =
"Unable to connect to socket for host \""+host+
"\".";
2272 write(sockfd, message, strlen(message));
2275 read(sockfd, response,
sizeof(response)-1);
2281 return std::string(response);
2285 #if defined(G_USE_CURL)
2329 static std::string country;
2332 if (country.empty()) {
2338 if ((!force_query) && (access(filename.
url().c_str(), R_OK) == 0)) {
2341 #pragma omp critical(GammaLib_host_country)
2346 lock.l_type = F_RDLCK;
2347 lock.l_whence = SEEK_SET;
2350 lock.l_pid = getpid();
2351 int fd = open(filename.
url().c_str(), O_RDONLY);
2355 fcntl(fd, F_SETLKW, &lock);
2359 FILE* fptr = fopen(filename.
url().c_str(),
"r");
2367 fgets(line, n-1, fptr);
2378 lock.l_type = F_UNLCK;
2379 fcntl(fd, F_SETLK, &lock);
2395 #if defined(G_USE_CURL)
2396 #if defined(G_HAS_CURL)
2401 #if defined(G_HAS_PERL)
2402 sprintf(command,
"a=$(perl -e 'alarm shift; exec \"curl --silent"
2403 " http://ip-api.com/line/?fields=countryCode"
2404 " 2>/dev/null\"' \"1\";);echo $a");
2405 #elif defined(G_HAS_TIMEOUT)
2406 sprintf(command,
"timeout 1s curl --silent http://ip-api.com/line/"
2407 "?fields=countryCode 2>/dev/null");
2409 sprintf(command,
"curl --silent http://ip-api.com/line/?fields=countryCode"
2414 FILE* file = popen(command,
"r");
2418 if (fgets(output,
sizeof(output)-1, file) != NULL) {
2429 std::string response =
http_query(
"ip-api.com",
"line/?fields=countryCode");
2430 std::vector<std::string> lines =
split(response,
"\n");
2432 for (
int i = 0; i < lines.size(); ++i) {
2437 if ((lines[i] ==
"\n") || (lines[i] ==
"\r") || (lines[i] ==
" ")) {
2442 catch (
const std::exception& e) {
2449 if (country.length() == 2) {
2452 #pragma omp critical(GammaLib_host_country)
2457 FILE* fptr = fopen(filename.
url().c_str(),
"w");
2459 fprintf(fptr,
"%s\n", country.c_str());
2490 uid_t uid = geteuid();
2491 struct passwd* pw = getpwuid(uid);
2493 filename = std::string(pw->pw_dir) +
"/.gamma/" + name;
2501 if (home_ptr != NULL) {
2502 filename = std::string(home_ptr) +
"/.gamma/" + name;
2507 filename =
"~/.gamma/" + name;
Abstract XML node base class.
bool contains(const std::string &str, const std::string &substring)
Checks if a substring is in a string.
void xml_get_name_value_pair(const GXmlNode *node, std::string &name, std::string &value)
Extract name / value pair from XML node.
std::string file(void) const
Return name of file.
std::string replace_segment(const std::string &arg, const std::string &segment, const std::string &replacement)
Replace string segment in string.
std::string getenv(const std::string &arg)
Return value of environment variable.
double roi_arclength(const double &rad, const double &dist, const double &cosdist, const double &sindist, const double &roi, const double &cosroi)
Returns length of circular arc within circular ROI.
std::string number(const std::string &noun, const int &number)
Convert singular noun into number noun.
GFilename filename(void) const
Return filename of XML file.
void xml_check_par(const std::string &origin, const std::string &name, const int &number)
Checks whether a parameter has occured once.
Energy value class definition.
void warning(const std::string &origin, const std::string &message)
Emits warning.
XML element node class interface definition.
GVector abs(const GVector &vector)
Computes absolute of vector elements.
GVector cos(const GVector &vector)
Computes cosine of vector elements.
std::string strdate(void)
Return current date.
bool is_empty(void) const
Signal if filename is empty.
int recv(int fd, char *buffer, int len, int flags, int timeout)
Checks whether a parameter has occured once.
double acos(const double &arg)
Computes acos by avoiding NaN due to rounding errors.
std::string strip_chars(const std::string &arg, const std::string &chars)
Strip leading and trailing character from string.
std::vector< std::string > split(const std::string &s, const std::string &sep)
Split string.
double MeV(void) const
Return energy in MeV.
virtual int elements(void) const
Return number of GXMLElement children of node.
FITS file class interface definition.
long tolong(const std::string &arg)
Convert string into long value.
std::string strip_whitespace(const std::string &arg)
Strip leading and trailing whitespace from string.
GFilename xml_file_reduce(const GXmlElement &xml, const std::string &filename)
Reduce file name provided for writing as XML attribute.
double plaw_energy_flux(const double &emin, const double &emax, const double &epivot, const double &gamma)
Compute energy flux between two energies for a power law.
std::string centre(const std::string &s, const int &n, const char &c= ' ')
Centre string to achieve a length of n characters.
double log10MeV(void) const
Return log10 of energy in MeV.
bool is_notanumber(const double &x)
Signal if argument is not a number.
bool is_infinite(const double &x)
Signal if argument is infinite.
std::string right(const std::string &s, const int &n, const char &c= ' ')
Right justify string to achieve a length of n characters.
std::string path(void) const
Return access path.
std::string http_query(const std::string &host, const std::string &query)
Return response to a HTTP query.
const GXmlAttribute * attribute(const int &index) const
Return attribute.
short toshort(const std::string &arg)
Convert string into short value.
char * tochar(const std::string &arg)
Convert string to C string.
std::string left(const std::string &s, const int &n, const char &c= ' ')
Left justify string to achieve a length of n characters.
bool has_attribute(const std::string &name) const
Check if element has a given attribute.
GXmlElement * xml_need_par(const std::string &origin, GXmlElement &xml, const std::string &name)
Return pointer to parameter with given name in XML element.
GVector log(const GVector &vector)
Computes natural logarithm of vector elements.
const std::string & text(void) const
Return text.
bool dir_exists(const std::string &dirname)
Checks if directory exists.
GFilename gamma_filename(const std::string &name)
Returns filename in .gamma directory.
void xml_check_parnum(const std::string &origin, const GXmlElement &xml, const int &number)
Checks number of parameters.
XML text node class interface definition.
unsigned long long toulonglong(const std::string &arg)
Convert string into unsigned long long value.
bool xml_has_par(const GXmlElement &xml, const std::string &name)
Checks if parameter with given name in XML element exists.
std::string xml2str(const std::string &arg)
Convert XML character references in string to characters.
long long tolonglong(const std::string &arg)
Convert string into long long value.
unsigned long toulong(const std::string &arg)
Convert string into unsigned long value.
std::string rstrip_chars(const std::string &arg, const std::string &chars)
Strip trailing character from string.
std::string url(void) const
Return Uniform Resource Locator (URL)
virtual GXmlElement * element(const int &index)
Return pointer to GXMLElement child.
std::string host_country(const bool &force_query=false)
Return two-digit host country code.
std::string tmpnam(void)
Return temporary file name.
GVector pow(const GVector &vector, const double &power)
Computes tanh of vector elements.
unsigned int touint(const std::string &arg)
Convert string into unsigned integer value.
unsigned short toushort(const std::string &arg)
Convert string into unsigned short value.
GVector sin(const GVector &vector)
Computes sine of vector elements.
Exception handler interface definition.
std::string toupper(const std::string &s)
Convert string to upper case.
std::string tolower(const std::string &s)
Convert string to lower case.
bool compare(const double &a, const double &b, const double &tol)
Compare two floating point values with tolerance.
std::string xml_get_attr(const std::string &origin, const GXmlElement &xml, const std::string &name, const std::string &attribute)
Return attribute value for a given parameter in XML element.
std::string expand_env(const std::string &arg)
Expand environment variables in string.
int toint(const std::string &arg)
Convert string into integer value.
std::string filepath(const std::string &pathname, const std::string &filename)
Build file path from path name and file name.
virtual GXmlNode * append(const GXmlNode &node)
Append XML child node.
std::string parformat(const std::string &s, const int &indent=0)
Convert string in parameter format.
std::string str2xml(const std::string &arg)
Convert special characters in string to XML character references.
std::string fill(const std::string &s, const int &n)
Fill string with n strings of same type.
Abstract XML node base class interface definition.
const GXmlElement * xml_get_par(const std::string &origin, const GXmlElement &xml, const std::string &name)
Return pointer to parameter with given name in XML element.
Filename class interface definition.
Mathematical function definitions.
GEnergy elogmean(const GEnergy &a, const GEnergy &b)
Computes log mean energy.
double todouble(const std::string &arg)
Convert string into double precision value.
Class that handles energies in a unit independent way.
double plaw_photon_flux(const double &emin, const double &emax, const double &epivot, const double &gamma)
Compute photon flux between two energies for a power law.
float tofloat(const std::string &arg)
Convert string into single precision value.
GFilename xml_file_expand(const GXmlElement &xml, const std::string &filename)
Expand file name provided as XML attribute for loading.
std::string str(const unsigned short int &value)
Convert unsigned short integer value into string.
void xml_check_type(const std::string &origin, GXmlElement &xml, const std::string &type)
Checks the model type.