From fc944d5c622a7e6051e1cadb55c63e82ebdbbf01 Mon Sep 17 00:00:00 2001 From: Mohcine Chraibi <m.chraibi@fz-juelich.de> Date: Thu, 15 Nov 2018 08:49:33 +0000 Subject: [PATCH] Resolve "Use Boost Directory Functionality" --- .gitlab-ci.yml | 4 +- .vs/dirent.h | 1157 ----------------------- Analysis.cpp | 49 +- Analysis.h | 12 +- CHANGELOG.md | 21 + CMakeLists.txt | 42 +- IO/OutputHandler.cpp | 9 +- demos/T-Junction/ini_KO_240_050_240.xml | 125 ++- general/ArgumentParser.cpp | 245 ++--- general/ArgumentParser.h | 42 +- general/Macros.h | 6 +- main.cpp | 14 +- methods/Method_A.cpp | 33 +- methods/Method_A.h | 19 +- methods/Method_B.cpp | 14 +- methods/Method_B.h | 8 +- methods/Method_C.cpp | 8 +- methods/Method_C.h | 7 +- methods/Method_D.cpp | 116 ++- methods/Method_D.h | 32 +- methods/PedData.cpp | 38 +- methods/PedData.h | 34 +- packages.config | 4 + scripts/_Plot_N_t.py | 29 +- scripts/_Plot_cell_rho.py | 7 +- scripts/_Plot_cell_v.py | 12 +- scripts/_Plot_profiles.py | 26 +- 27 files changed, 582 insertions(+), 1531 deletions(-) delete mode 100644 .vs/dirent.h create mode 100644 packages.config diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 164f6ec4..beef3797 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -26,9 +26,7 @@ configure-linux: - mkdir -p build - cd build - which git - - which g++ - - ls /usr/bin/g++* - - cmake -DCMAKE_BUILD_TYPE=Debug .. + - cmake -DCMAKE_BUILD_TYPE=Debug .. - echo "configure | ${CI_PROJECT_DIR}" stage: configure tags: diff --git a/.vs/dirent.h b/.vs/dirent.h deleted file mode 100644 index bcc2f556..00000000 --- a/.vs/dirent.h +++ /dev/null @@ -1,1157 +0,0 @@ -/* - * Dirent interface for Microsoft Visual Studio - * - * Copyright (C) 2006-2012 Toni Ronkko - * This file is part of dirent. Dirent may be freely distributed - * under the MIT license. For all details and documentation, see - * https://github.com/tronkko/dirent - */ -#ifndef DIRENT_H -#define DIRENT_H - -/* - * Include windows.h without Windows Sockets 1.1 to prevent conflicts with - * Windows Sockets 2.0. - */ -#ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -#endif -#include <windows.h> - -#include <stdio.h> -#include <stdarg.h> -#include <wchar.h> -#include <string.h> -#include <stdlib.h> -#include <malloc.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <errno.h> - -/* Indicates that d_type field is available in dirent structure */ -#define _DIRENT_HAVE_D_TYPE - -/* Indicates that d_namlen field is available in dirent structure */ -#define _DIRENT_HAVE_D_NAMLEN - -/* Entries missing from MSVC 6.0 */ -#if !defined(FILE_ATTRIBUTE_DEVICE) -# define FILE_ATTRIBUTE_DEVICE 0x40 -#endif - -/* File type and permission flags for stat(), general mask */ -#if !defined(S_IFMT) -# define S_IFMT _S_IFMT -#endif - -/* Directory bit */ -#if !defined(S_IFDIR) -# define S_IFDIR _S_IFDIR -#endif - -/* Character device bit */ -#if !defined(S_IFCHR) -# define S_IFCHR _S_IFCHR -#endif - -/* Pipe bit */ -#if !defined(S_IFFIFO) -# define S_IFFIFO _S_IFFIFO -#endif - -/* Regular file bit */ -#if !defined(S_IFREG) -# define S_IFREG _S_IFREG -#endif - -/* Read permission */ -#if !defined(S_IREAD) -# define S_IREAD _S_IREAD -#endif - -/* Write permission */ -#if !defined(S_IWRITE) -# define S_IWRITE _S_IWRITE -#endif - -/* Execute permission */ -#if !defined(S_IEXEC) -# define S_IEXEC _S_IEXEC -#endif - -/* Pipe */ -#if !defined(S_IFIFO) -# define S_IFIFO _S_IFIFO -#endif - -/* Block device */ -#if !defined(S_IFBLK) -# define S_IFBLK 0 -#endif - -/* Link */ -#if !defined(S_IFLNK) -# define S_IFLNK 0 -#endif - -/* Socket */ -#if !defined(S_IFSOCK) -# define S_IFSOCK 0 -#endif - -/* Read user permission */ -#if !defined(S_IRUSR) -# define S_IRUSR S_IREAD -#endif - -/* Write user permission */ -#if !defined(S_IWUSR) -# define S_IWUSR S_IWRITE -#endif - -/* Execute user permission */ -#if !defined(S_IXUSR) -# define S_IXUSR 0 -#endif - -/* Read group permission */ -#if !defined(S_IRGRP) -# define S_IRGRP 0 -#endif - -/* Write group permission */ -#if !defined(S_IWGRP) -# define S_IWGRP 0 -#endif - -/* Execute group permission */ -#if !defined(S_IXGRP) -# define S_IXGRP 0 -#endif - -/* Read others permission */ -#if !defined(S_IROTH) -# define S_IROTH 0 -#endif - -/* Write others permission */ -#if !defined(S_IWOTH) -# define S_IWOTH 0 -#endif - -/* Execute others permission */ -#if !defined(S_IXOTH) -# define S_IXOTH 0 -#endif - -/* Maximum length of file name */ -#if !defined(PATH_MAX) -# define PATH_MAX MAX_PATH -#endif -#if !defined(FILENAME_MAX) -# define FILENAME_MAX MAX_PATH -#endif -#if !defined(NAME_MAX) -# define NAME_MAX FILENAME_MAX -#endif - -/* File type flags for d_type */ -#define DT_UNKNOWN 0 -#define DT_REG S_IFREG -#define DT_DIR S_IFDIR -#define DT_FIFO S_IFIFO -#define DT_SOCK S_IFSOCK -#define DT_CHR S_IFCHR -#define DT_BLK S_IFBLK -#define DT_LNK S_IFLNK - -/* Macros for converting between st_mode and d_type */ -#define IFTODT(mode) ((mode) & S_IFMT) -#define DTTOIF(type) (type) - -/* - * File type macros. Note that block devices, sockets and links cannot be - * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are - * only defined for compatibility. These macros should always return false - * on Windows. - */ -#if !defined(S_ISFIFO) -# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) -#endif -#if !defined(S_ISDIR) -# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#endif -#if !defined(S_ISREG) -# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#endif -#if !defined(S_ISLNK) -# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) -#endif -#if !defined(S_ISSOCK) -# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) -#endif -#if !defined(S_ISCHR) -# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) -#endif -#if !defined(S_ISBLK) -# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) -#endif - -/* Return the exact length of the file name without zero terminator */ -#define _D_EXACT_NAMLEN(p) ((p)->d_namlen) - -/* Return the maximum size of a file name */ -#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1) - - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Wide-character version */ -struct _wdirent { - /* Always zero */ - long d_ino; - - /* File position within stream */ - long d_off; - - /* Structure size */ - unsigned short d_reclen; - - /* Length of name without \0 */ - size_t d_namlen; - - /* File type */ - int d_type; - - /* File name */ - wchar_t d_name[PATH_MAX+1]; -}; -typedef struct _wdirent _wdirent; - -struct _WDIR { - /* Current directory entry */ - struct _wdirent ent; - - /* Private file data */ - WIN32_FIND_DATAW data; - - /* True if data is valid */ - int cached; - - /* Win32 search handle */ - HANDLE handle; - - /* Initial directory name */ - wchar_t *patt; -}; -typedef struct _WDIR _WDIR; - -/* Multi-byte character version */ -struct dirent { - /* Always zero */ - long d_ino; - - /* File position within stream */ - long d_off; - - /* Structure size */ - unsigned short d_reclen; - - /* Length of name without \0 */ - size_t d_namlen; - - /* File type */ - int d_type; - - /* File name */ - char d_name[PATH_MAX+1]; -}; -typedef struct dirent dirent; - -struct DIR { - struct dirent ent; - struct _WDIR *wdirp; -}; -typedef struct DIR DIR; - - -/* Dirent functions */ -static DIR *opendir (const char *dirname); -static _WDIR *_wopendir (const wchar_t *dirname); - -static struct dirent *readdir (DIR *dirp); -static struct _wdirent *_wreaddir (_WDIR *dirp); - -static int readdir_r( - DIR *dirp, struct dirent *entry, struct dirent **result); -static int _wreaddir_r( - _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result); - -static int closedir (DIR *dirp); -static int _wclosedir (_WDIR *dirp); - -static void rewinddir (DIR* dirp); -static void _wrewinddir (_WDIR* dirp); - -static int scandir (const char *dirname, struct dirent ***namelist, - int (*filter)(const struct dirent*), - int (*compare)(const void *, const void *)); - -static int alphasort (const struct dirent **a, const struct dirent **b); - -static int versionsort (const struct dirent **a, const struct dirent **b); - - -/* For compatibility with Symbian */ -#define wdirent _wdirent -#define WDIR _WDIR -#define wopendir _wopendir -#define wreaddir _wreaddir -#define wclosedir _wclosedir -#define wrewinddir _wrewinddir - - -/* Internal utility functions */ -static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp); -static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp); - -static int dirent_mbstowcs_s( - size_t *pReturnValue, - wchar_t *wcstr, - size_t sizeInWords, - const char *mbstr, - size_t count); - -static int dirent_wcstombs_s( - size_t *pReturnValue, - char *mbstr, - size_t sizeInBytes, - const wchar_t *wcstr, - size_t count); - -static void dirent_set_errno (int error); - - -/* - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static _WDIR* -_wopendir( - const wchar_t *dirname) -{ - _WDIR *dirp = NULL; - int error; - - /* Must have directory name */ - if (dirname == NULL || dirname[0] == '\0') { - dirent_set_errno (ENOENT); - return NULL; - } - - /* Allocate new _WDIR structure */ - dirp = (_WDIR*) malloc (sizeof (struct _WDIR)); - if (dirp != NULL) { - DWORD n; - - /* Reset _WDIR structure */ - dirp->handle = INVALID_HANDLE_VALUE; - dirp->patt = NULL; - dirp->cached = 0; - - /* Compute the length of full path plus zero terminator - * - * Note that on WinRT there's no way to convert relative paths - * into absolute paths, so just assume it is an absolute path. - */ -# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) - n = wcslen(dirname); -# else - n = GetFullPathNameW (dirname, 0, NULL, NULL); -# endif - - /* Allocate room for absolute directory name and search pattern */ - dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16); - if (dirp->patt) { - - /* - * Convert relative directory name to an absolute one. This - * allows rewinddir() to function correctly even when current - * working directory is changed between opendir() and rewinddir(). - * - * Note that on WinRT there's no way to convert relative paths - * into absolute paths, so just assume it is an absolute path. - */ -# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) - wcsncpy_s(dirp->patt, n+1, dirname, n); -# else - n = GetFullPathNameW (dirname, n, dirp->patt, NULL); -# endif - if (n > 0) { - wchar_t *p; - - /* Append search pattern \* to the directory name */ - p = dirp->patt + n; - if (dirp->patt < p) { - switch (p[-1]) { - case '\\': - case '/': - case ':': - /* Directory ends in path separator, e.g. c:\temp\ */ - /*NOP*/; - break; - - default: - /* Directory name doesn't end in path separator */ - *p++ = '\\'; - } - } - *p++ = '*'; - *p = '\0'; - - /* Open directory stream and retrieve the first entry */ - if (dirent_first (dirp)) { - /* Directory stream opened successfully */ - error = 0; - } else { - /* Cannot retrieve first entry */ - error = 1; - dirent_set_errno (ENOENT); - } - - } else { - /* Cannot retrieve full path name */ - dirent_set_errno (ENOENT); - error = 1; - } - - } else { - /* Cannot allocate memory for search pattern */ - error = 1; - } - - } else { - /* Cannot allocate _WDIR structure */ - error = 1; - } - - /* Clean up in case of error */ - if (error && dirp) { - _wclosedir (dirp); - dirp = NULL; - } - - return dirp; -} - -/* - * Read next directory entry. - * - * Returns pointer to static directory entry which may be overwritten by - * subsequent calls to _wreaddir(). - */ -static struct _wdirent* -_wreaddir( - _WDIR *dirp) -{ - struct _wdirent *entry; - - /* - * Read directory entry to buffer. We can safely ignore the return value - * as entry will be set to NULL in case of error. - */ - (void) _wreaddir_r (dirp, &dirp->ent, &entry); - - /* Return pointer to statically allocated directory entry */ - return entry; -} - -/* - * Read next directory entry. - * - * Returns zero on success. If end of directory stream is reached, then sets - * result to NULL and returns zero. - */ -static int -_wreaddir_r( - _WDIR *dirp, - struct _wdirent *entry, - struct _wdirent **result) -{ - WIN32_FIND_DATAW *datap; - - /* Read next directory entry */ - datap = dirent_next (dirp); - if (datap) { - size_t n; - DWORD attr; - - /* - * Copy file name as wide-character string. If the file name is too - * long to fit in to the destination buffer, then truncate file name - * to PATH_MAX characters and zero-terminate the buffer. - */ - n = 0; - while (n < PATH_MAX && datap->cFileName[n] != 0) { - entry->d_name[n] = datap->cFileName[n]; - n++; - } - entry->d_name[n] = 0; - - /* Length of file name excluding zero terminator */ - entry->d_namlen = n; - - /* File type */ - attr = datap->dwFileAttributes; - if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { - entry->d_type = DT_CHR; - } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { - entry->d_type = DT_DIR; - } else { - entry->d_type = DT_REG; - } - - /* Reset dummy fields */ - entry->d_ino = 0; - entry->d_off = 0; - entry->d_reclen = sizeof (struct _wdirent); - - /* Set result address */ - *result = entry; - - } else { - - /* Return NULL to indicate end of directory */ - *result = NULL; - - } - - return /*OK*/0; -} - -/* - * Close directory stream opened by opendir() function. This invalidates the - * DIR structure as well as any directory entry read previously by - * _wreaddir(). - */ -static int -_wclosedir( - _WDIR *dirp) -{ - int ok; - if (dirp) { - - /* Release search handle */ - if (dirp->handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->handle); - dirp->handle = INVALID_HANDLE_VALUE; - } - - /* Release search pattern */ - if (dirp->patt) { - free (dirp->patt); - dirp->patt = NULL; - } - - /* Release directory structure */ - free (dirp); - ok = /*success*/0; - - } else { - - /* Invalid directory stream */ - dirent_set_errno (EBADF); - ok = /*failure*/-1; - - } - return ok; -} - -/* - * Rewind directory stream such that _wreaddir() returns the very first - * file name again. - */ -static void -_wrewinddir( - _WDIR* dirp) -{ - if (dirp) { - /* Release existing search handle */ - if (dirp->handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->handle); - } - - /* Open new search handle */ - dirent_first (dirp); - } -} - -/* Get first directory entry (internal) */ -static WIN32_FIND_DATAW* -dirent_first( - _WDIR *dirp) -{ - WIN32_FIND_DATAW *datap; - - /* Open directory and retrieve the first entry */ - dirp->handle = FindFirstFileExW( - dirp->patt, FindExInfoStandard, &dirp->data, - FindExSearchNameMatch, NULL, 0); - if (dirp->handle != INVALID_HANDLE_VALUE) { - - /* a directory entry is now waiting in memory */ - datap = &dirp->data; - dirp->cached = 1; - - } else { - - /* Failed to re-open directory: no directory entry in memory */ - dirp->cached = 0; - datap = NULL; - - } - return datap; -} - -/* - * Get next directory entry (internal). - * - * Returns - */ -static WIN32_FIND_DATAW* -dirent_next( - _WDIR *dirp) -{ - WIN32_FIND_DATAW *p; - - /* Get next directory entry */ - if (dirp->cached != 0) { - - /* A valid directory entry already in memory */ - p = &dirp->data; - dirp->cached = 0; - - } else if (dirp->handle != INVALID_HANDLE_VALUE) { - - /* Get the next directory entry from stream */ - if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) { - /* Got a file */ - p = &dirp->data; - } else { - /* The very last entry has been processed or an error occurred */ - FindClose (dirp->handle); - dirp->handle = INVALID_HANDLE_VALUE; - p = NULL; - } - - } else { - - /* End of directory stream reached */ - p = NULL; - - } - - return p; -} - -/* - * Open directory stream using plain old C-string. - */ -static DIR* -opendir( - const char *dirname) -{ - struct DIR *dirp; - int error; - - /* Must have directory name */ - if (dirname == NULL || dirname[0] == '\0') { - dirent_set_errno (ENOENT); - return NULL; - } - - /* Allocate memory for DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp) { - wchar_t wname[PATH_MAX + 1]; - size_t n; - - /* Convert directory name to wide-character string */ - error = dirent_mbstowcs_s( - &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1); - if (!error) { - - /* Open directory stream using wide-character name */ - dirp->wdirp = _wopendir (wname); - if (dirp->wdirp) { - /* Directory stream opened */ - error = 0; - } else { - /* Failed to open directory stream */ - error = 1; - } - - } else { - /* - * Cannot convert file name to wide-character string. This - * occurs if the string contains invalid multi-byte sequences or - * the output buffer is too small to contain the resulting - * string. - */ - error = 1; - } - - } else { - /* Cannot allocate DIR structure */ - error = 1; - } - - /* Clean up in case of error */ - if (error && dirp) { - free (dirp); - dirp = NULL; - } - - return dirp; -} - -/* - * Read next directory entry. - */ -static struct dirent* -readdir( - DIR *dirp) -{ - struct dirent *entry; - - /* - * Read directory entry to buffer. We can safely ignore the return value - * as entry will be set to NULL in case of error. - */ - (void) readdir_r (dirp, &dirp->ent, &entry); - - /* Return pointer to statically allocated directory entry */ - return entry; -} - -/* - * Read next directory entry into called-allocated buffer. - * - * Returns zero on success. If the end of directory stream is reached, then - * sets result to NULL and returns zero. - */ -static int -readdir_r( - DIR *dirp, - struct dirent *entry, - struct dirent **result) -{ - WIN32_FIND_DATAW *datap; - - /* Read next directory entry */ - datap = dirent_next (dirp->wdirp); - if (datap) { - size_t n; - int error; - - /* Attempt to convert file name to multi-byte string */ - error = dirent_wcstombs_s( - &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1); - - /* - * If the file name cannot be represented by a multi-byte string, - * then attempt to use old 8+3 file name. This allows traditional - * Unix-code to access some file names despite of unicode - * characters, although file names may seem unfamiliar to the user. - * - * Be ware that the code below cannot come up with a short file - * name unless the file system provides one. At least - * VirtualBox shared folders fail to do this. - */ - if (error && datap->cAlternateFileName[0] != '\0') { - error = dirent_wcstombs_s( - &n, entry->d_name, PATH_MAX + 1, - datap->cAlternateFileName, PATH_MAX + 1); - } - - if (!error) { - DWORD attr; - - /* Length of file name excluding zero terminator */ - entry->d_namlen = n - 1; - - /* File attributes */ - attr = datap->dwFileAttributes; - if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { - entry->d_type = DT_CHR; - } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { - entry->d_type = DT_DIR; - } else { - entry->d_type = DT_REG; - } - - /* Reset dummy fields */ - entry->d_ino = 0; - entry->d_off = 0; - entry->d_reclen = sizeof (struct dirent); - - } else { - - /* - * Cannot convert file name to multi-byte string so construct - * an erroneous directory entry and return that. Note that - * we cannot return NULL as that would stop the processing - * of directory entries completely. - */ - entry->d_name[0] = '?'; - entry->d_name[1] = '\0'; - entry->d_namlen = 1; - entry->d_type = DT_UNKNOWN; - entry->d_ino = 0; - entry->d_off = -1; - entry->d_reclen = 0; - - } - - /* Return pointer to directory entry */ - *result = entry; - - } else { - - /* No more directory entries */ - *result = NULL; - - } - - return /*OK*/0; -} - -/* - * Close directory stream. - */ -static int -closedir( - DIR *dirp) -{ - int ok; - if (dirp) { - - /* Close wide-character directory stream */ - ok = _wclosedir (dirp->wdirp); - dirp->wdirp = NULL; - - /* Release multi-byte character version */ - free (dirp); - - } else { - - /* Invalid directory stream */ - dirent_set_errno (EBADF); - ok = /*failure*/-1; - - } - return ok; -} - -/* - * Rewind directory stream to beginning. - */ -static void -rewinddir( - DIR* dirp) -{ - /* Rewind wide-character string directory stream */ - _wrewinddir (dirp->wdirp); -} - -/* - * Scan directory for entries. - */ -static int -scandir( - const char *dirname, - struct dirent ***namelist, - int (*filter)(const struct dirent*), - int (*compare)(const void*, const void*)) -{ - struct dirent **files = NULL; - size_t size = 0; - size_t allocated = 0; - const size_t init_size = 1; - DIR *dir = NULL; - struct dirent *entry; - struct dirent *tmp = NULL; - size_t i; - int result = 0; - - /* Open directory stream */ - dir = opendir (dirname); - if (dir) { - - /* Read directory entries to memory */ - while (1) { - - /* Enlarge pointer table to make room for another pointer */ - if (size >= allocated) { - void *p; - size_t num_entries; - - /* Compute number of entries in the enlarged pointer table */ - if (size < init_size) { - /* Allocate initial pointer table */ - num_entries = init_size; - } else { - /* Double the size */ - num_entries = size * 2; - } - - /* Allocate first pointer table or enlarge existing table */ - p = realloc (files, sizeof (void*) * num_entries); - if (p != NULL) { - /* Got the memory */ - files = (dirent**) p; - allocated = num_entries; - } else { - /* Out of memory */ - result = -1; - break; - } - - } - - /* Allocate room for temporary directory entry */ - if (tmp == NULL) { - tmp = (struct dirent*) malloc (sizeof (struct dirent)); - if (tmp == NULL) { - /* Cannot allocate temporary directory entry */ - result = -1; - break; - } - } - - /* Read directory entry to temporary area */ - if (readdir_r (dir, tmp, &entry) == /*OK*/0) { - - /* Did we get an entry? */ - if (entry != NULL) { - int pass; - - /* Determine whether to include the entry in result */ - if (filter) { - /* Let the filter function decide */ - pass = filter (tmp); - } else { - /* No filter function, include everything */ - pass = 1; - } - - if (pass) { - /* Store the temporary entry to pointer table */ - files[size++] = tmp; - tmp = NULL; - - /* Keep up with the number of files */ - result++; - } - - } else { - - /* - * End of directory stream reached => sort entries and - * exit. - */ - qsort (files, size, sizeof (void*), compare); - break; - - } - - } else { - /* Error reading directory entry */ - result = /*Error*/ -1; - break; - } - - } - - } else { - /* Cannot open directory */ - result = /*Error*/ -1; - } - - /* Release temporary directory entry */ - if (tmp) { - free (tmp); - } - - /* Release allocated memory on error */ - if (result < 0) { - for (i = 0; i < size; i++) { - free (files[i]); - } - free (files); - files = NULL; - } - - /* Close directory stream */ - if (dir) { - closedir (dir); - } - - /* Pass pointer table to caller */ - if (namelist) { - *namelist = files; - } - return result; -} - -/* Alphabetical sorting */ -static int -alphasort( - const struct dirent **a, const struct dirent **b) -{ - return strcoll ((*a)->d_name, (*b)->d_name); -} - -/* Sort versions */ -static int -versionsort( - const struct dirent **a, const struct dirent **b) -{ - /* FIXME: implement strverscmp and use that */ - return alphasort (a, b); -} - - -/* Convert multi-byte string to wide character string */ -static int -dirent_mbstowcs_s( - size_t *pReturnValue, - wchar_t *wcstr, - size_t sizeInWords, - const char *mbstr, - size_t count) -{ - int error; - -#if defined(_MSC_VER) && _MSC_VER >= 1400 - - /* Microsoft Visual Studio 2005 or later */ - error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count); - -#else - - /* Older Visual Studio or non-Microsoft compiler */ - size_t n; - - /* Convert to wide-character string (or count characters) */ - n = mbstowcs (wcstr, mbstr, sizeInWords); - if (!wcstr || n < count) { - - /* Zero-terminate output buffer */ - if (wcstr && sizeInWords) { - if (n >= sizeInWords) { - n = sizeInWords - 1; - } - wcstr[n] = 0; - } - - /* Length of resulting multi-byte string WITH zero terminator */ - if (pReturnValue) { - *pReturnValue = n + 1; - } - - /* Success */ - error = 0; - - } else { - - /* Could not convert string */ - error = 1; - - } - -#endif - - return error; -} - -/* Convert wide-character string to multi-byte string */ -static int -dirent_wcstombs_s( - size_t *pReturnValue, - char *mbstr, - size_t sizeInBytes, /* max size of mbstr */ - const wchar_t *wcstr, - size_t count) -{ - int error; - -#if defined(_MSC_VER) && _MSC_VER >= 1400 - - /* Microsoft Visual Studio 2005 or later */ - error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count); - -#else - - /* Older Visual Studio or non-Microsoft compiler */ - size_t n; - - /* Convert to multi-byte string (or count the number of bytes needed) */ - n = wcstombs (mbstr, wcstr, sizeInBytes); - if (!mbstr || n < count) { - - /* Zero-terminate output buffer */ - if (mbstr && sizeInBytes) { - if (n >= sizeInBytes) { - n = sizeInBytes - 1; - } - mbstr[n] = '\0'; - } - - /* Length of resulting multi-bytes string WITH zero-terminator */ - if (pReturnValue) { - *pReturnValue = n + 1; - } - - /* Success */ - error = 0; - - } else { - - /* Cannot convert string */ - error = 1; - - } - -#endif - - return error; -} - -/* Set errno variable */ -static void -dirent_set_errno( - int error) -{ -#if defined(_MSC_VER) && _MSC_VER >= 1400 - - /* Microsoft Visual Studio 2005 and later */ - _set_errno (error); - -#else - - /* Non-Microsoft compiler or older Microsoft compiler */ - errno = error; - -#endif -} - - -#ifdef __cplusplus -} -#endif -#endif /*DIRENT_H*/ \ No newline at end of file diff --git a/Analysis.cpp b/Analysis.cpp index 1e46409e..b6736b88 100644 --- a/Analysis.cpp +++ b/Analysis.cpp @@ -180,14 +180,15 @@ void Analysis::InitArgs(ArgumentParser* args) _cutRadius=args->GetCutRadius(); _circleEdges=args->GetCircleEdges(); _scriptsLocation=args->GetScriptsLocation(); + _outputLocation=args->GetOutputLocation(); } -std::map<int, polygon_2d> Analysis::ReadGeometry(const std::string& geometryFile, const std::vector<MeasurementArea_B*>& areas) +std::map<int, polygon_2d> Analysis::ReadGeometry(const fs::path& geometryFile, const std::vector<MeasurementArea_B*>& areas) { _building = new Building(); - _building->LoadGeometry(geometryFile); + _building->LoadGeometry(geometryFile.string()); // create the polygons _building->InitGeometry(); @@ -260,12 +261,12 @@ std::map<int, polygon_2d> Analysis::ReadGeometry(const std::string& geometryFile } -int Analysis::RunAnalysis(const string& filename, const string& path) +int Analysis::RunAnalysis(const fs::path& filename, const fs::path& path) { PedData data; - if(data.ReadData(_projectRootDir, path, filename, _trajFormat, _deltaF, _vComponent, _IgnoreBackwardMovement)==false) + if(data.ReadData(_projectRootDir, _outputLocation, path, filename, _trajFormat, _deltaF, _vComponent, _IgnoreBackwardMovement)==false) { - Log->Write("ERROR:\tCould not parse the file"); + Log->Write("ERROR:\tCould not parse the file %d", filename.c_str()); return -1; } @@ -306,14 +307,19 @@ int Analysis::RunAnalysis(const string& filename, const string& path) if(_DoesUseMethodA) //Method A { + if(_areaForMethod_A.empty()) + { + Log->Write("ERROR: Method A selected with no measurement area!"); + exit(EXIT_FAILURE); + } #pragma omp parallel for - for(signed int i=0; i<_areaForMethod_A.size(); i++) + for(long unsigned int i=0; i < _areaForMethod_A.size(); i++) { Method_A method_A ; method_A.SetMeasurementArea(_areaForMethod_A[i]); method_A.SetTimeInterval(_deltaT[i]); method_A.SetPlotTimeSeries(_plotTimeseriesA[i]); - bool result_A=method_A.Process(data,_scriptsLocation, _areaForMethod_A[i]->_zPos); + bool result_A=method_A.Process(data,_scriptsLocation,_areaForMethod_A[i]->_zPos); if(result_A) { Log->Write("INFO:\tSuccess with Method A using measurement area id %d!\n",_areaForMethod_A[i]->_id); @@ -327,8 +333,14 @@ int Analysis::RunAnalysis(const string& filename, const string& path) if(_DoesUseMethodB) //Method_B { + if(_areaForMethod_B.empty()) + { + Log->Write("ERROR: Method B selected with no measurement area!"); + exit(EXIT_FAILURE); + } + #pragma omp parallel for - for(signed int i=0; i<_areaForMethod_B.size(); i++) + for(long unsigned int i=0; i < _areaForMethod_B.size(); i++) { Method_B method_B; method_B.SetMeasurementArea(_areaForMethod_B[i]); @@ -346,8 +358,13 @@ int Analysis::RunAnalysis(const string& filename, const string& path) if(_DoesUseMethodC) //Method C { + if(_areaForMethod_C.empty()) + { + Log->Write("ERROR: Method C selected with no measurement area!"); + exit(EXIT_FAILURE); + } #pragma omp parallel for - for(signed int i=0; i<_areaForMethod_C.size(); i++) + for(long unsigned int i=0; i < _areaForMethod_C.size(); i++) { Method_C method_C; method_C.SetMeasurementArea(_areaForMethod_C[i]); @@ -357,8 +374,8 @@ int Analysis::RunAnalysis(const string& filename, const string& path) Log->Write("INFO:\tSuccess with Method C using measurement area id %d!\n",_areaForMethod_C[i]->_id); if(_plotTimeseriesC[i]) { - string parameters_Timeseries=" " + _scriptsLocation+ -"/_Plot_timeseries_rho_v.py -p "+ _projectRootDir+VORO_LOCATION + " -n "+filename+ + string parameters_Timeseries=" " + _scriptsLocation.string()+ + "/_Plot_timeseries_rho_v.py -p "+ _projectRootDir.string()+VORO_LOCATION + " -n "+filename.string()+ " -f "+boost::lexical_cast<std::string>(data.GetFps()); parameters_Timeseries = PYTHON + parameters_Timeseries; int res=system(parameters_Timeseries.c_str()); @@ -374,8 +391,14 @@ int Analysis::RunAnalysis(const string& filename, const string& path) if(_DoesUseMethodD) //method_D { + if(_areaForMethod_D.empty()) + { + Log->Write("ERROR: Method D selected with no measurement area!"); + exit(EXIT_FAILURE); + } + #pragma omp parallel for - for(signed int i=0; i<_areaForMethod_D.size(); i++) + for(long unsigned int i=0; i<_areaForMethod_D.size(); i++) { Method_D method_D; method_D.SetStartFrame(_StartFramesMethodD[i]); @@ -403,7 +426,7 @@ int Analysis::RunAnalysis(const string& filename, const string& path) std::cout << "INFO:\tSuccess with Method D using measurement area id "<< _areaForMethod_D[i]->_id << "\n"; if(_plotTimeseriesD[i]) { - string parameters_Timeseries= " " +_scriptsLocation+"/_Plot_timeseries_rho_v.py -p "+ _projectRootDir+VORO_LOCATION + " -n "+filename+ + string parameters_Timeseries= " " +_scriptsLocation.string()+"/_Plot_timeseries_rho_v.py -p "+ _projectRootDir.string()+VORO_LOCATION + " -n "+filename.string()+ " -f "+boost::lexical_cast<std::string>(data.GetFps()); parameters_Timeseries = PYTHON + parameters_Timeseries; std::cout << parameters_Timeseries << "\n;"; diff --git a/Analysis.h b/Analysis.h index 91397a76..d4e8c5e8 100644 --- a/Analysis.h +++ b/Analysis.h @@ -67,7 +67,7 @@ public: void InitArgs(ArgumentParser *args); void InitializeFiles(const std::string& file); - std::map<int, polygon_2d> ReadGeometry(const std::string& geometryFile, const std::vector<MeasurementArea_B*>& areas); + std::map<int, polygon_2d> ReadGeometry(const fs::path& geometryFile, const std::vector<MeasurementArea_B*>& areas); /** * Run the analysis for different files. @@ -75,7 +75,7 @@ public: * @param path * @return */ - int RunAnalysis(const std::string& file, const std::string& path); + int RunAnalysis(const fs::path& file, const fs::path& path); /** * return the base name from the string. @@ -145,9 +145,11 @@ private: bool _calcIndividualFD; //Adjust whether analyze the individual density and velocity of each pedestrian in stationary state (ALWAYS VORONOI-BASED) std::string _vComponent; // to mark whether x, y or x and y coordinate are used when calculating the velocity bool _IgnoreBackwardMovement; - std::string _projectRootDir; - std::string _scriptsLocation; - std::string _geometryFileName; + + fs::path _projectRootDir; + fs::path _scriptsLocation; + fs::path _outputLocation; + fs::path _geometryFileName; FileFormat _trajFormat; // format of the trajectory file std::vector<MeasurementArea_L*> _areaForMethod_A; diff --git a/CHANGELOG.md b/CHANGELOG.md index db4b2492..f294e216 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,27 @@ # Change Log All notable changes to `jpsreport` will be documented in this file. +## v0.8.4 [TBD] +### Added + +- brew install [jpsreport](https://github.com/JuPedSim/homebrew-jps/blob/master/README.md) +- added option --version -version 2e0632be +- Option added to define a customized output directory + ```xml + <output location="path/to/directory"/> + ``` + +### Changed +- use c++17 for filesystem functionality !10 +- call python detected by cmake 5fb97f32 + + +### Fixed +- Better handling negative frame id 5304efb8 +- Fix for polygon output considering interior and exterior rings 361cffdd +- Exit if no measurement area is selected cdf28328 +- Exit if no measurement method is selected cdf28328 + ## v0.8.3 [16.05.2018] ### Added - Option to output log in a file instead of the screen fe66fa49 diff --git a/CMakeLists.txt b/CMakeLists.txt index 65f2a1c5..637671e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,12 +6,12 @@ cmake_minimum_required(VERSION 3.5 FATAL_ERROR) set(JPSREPORT_MAJOR_VERSION 0) set(JPSREPORT_MINOR_VERSION 8) -set(JPSREPORT_PATCH_VERSION 3) +set(JPSREPORT_PATCH_VERSION 4) set(JPSREPORT_VERSION ${JPSREPORT_MAJOR_VERSION}.${JPSREPORT_MINOR_VERSION}.${JPSREPORT_PATCH_VERSION}) message( STATUS "JPSREPORT_VERSION: " ${JPSREPORT_VERSION} ) project(JPSreport VERSION ${JPSREPORT_VERSION} LANGUAGES CXX) -set (CMAKE_CXX_STANDARD 11) +#set (CMAKE_CXX_STANDARD 17) # Fix behavior of CMAKE_CXX_STANDARD when targeting macOS. if (POLICY CMP0025) cmake_policy(SET CMP0025 NEW) @@ -259,9 +259,12 @@ if(CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -Wno-unused-local-typedefs") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -Wno-unused-local-typedefs") endif(CMAKE_COMPILER_IS_GNUCXX) -message(STATUS "Debug flags: " ${CMAKE_CXX_FLAGS_DEBUG} ) -message(STATUS "Release flags: " ${CMAKE_CXX_FLAGS_RELEASE} -static ) - +if(CMAKE_BUILD_TYPE MATCHES Debug) + message(STATUS "Debug flags: " ${CMAKE_CXX_FLAGS_DEBUG} ) +endif() +if(CMAKE_BUILD_TYPE MATCHES Release) + message(STATUS "Release flags: " ${CMAKE_CXX_FLAGS_RELEASE} -static ) +endif() if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_BUILD_TYPE MATCHES Debug) set(WITH_COVERAGE TRUE) @@ -277,9 +280,11 @@ if (Boost_NO_SYSTEM_PATHS) set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} ${BOOST_ROOT}) set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${BOOST_LIBRARY_DIRS}) endif (Boost_NO_SYSTEM_PATHS) - -#find_package(Boost COMPONENTS system filesystem REQUIRED) -find_package(Boost REQUIRED) +if(MSVC) + find_package(Boost QUIET) +else() + find_package(Boost REQUIRED) +endif() if (Boost_FOUND) # set(Boost_USE_STATIC_LIBS ON) # set(Boost_USE_STATIC_RUNTIME ON) @@ -293,7 +298,7 @@ if (Boost_FOUND) message(STATUS "Boost_LIB_VERSION: " ${Boost_LIB_VERSION}) message(STATUS "Boost_libraries: " ${Boost_LIBRARIES}) link_directories(${Boost_LIBRARY_DIRS}) - include_directories(${Boost_INCLUDE_DIR}) + include_directories(SYSTEM ${Boost_INCLUDE_DIR}) # suppress warnings in boost libraries with attribute SYSTEM #include_directories(SYSTEM ${Boost_INCLUDE_DIR}) else() @@ -306,9 +311,20 @@ endif() #endif() add_library ( geometrycore STATIC ${source_files} ) +set_property(TARGET geometrycore PROPERTY CXX_STANDARD 17) +set_property(TARGET geometrycore PROPERTY CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +target_link_libraries(geometrycore stdc++fs) + add_executable( jpsreport main.cpp ${methods} ) + +set_property(TARGET jpsreport PROPERTY CXX_STANDARD 17) +set_property(TARGET jpsreport PROPERTY CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +target_link_libraries(jpsreport stdc++fs) + if (Boost_FOUND) target_link_libraries(geometrycore ${Boost_LIBRARIES}) endif() @@ -320,6 +336,14 @@ endif() target_link_libraries( jpsreport geometrycore ) if(WIN32) if(MSVC) + set_property(GLOBAL PROPERTY USE_FOLDERS ON) # groups cmake-projects in CMakePredefinedTargets + set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "cmake") + set(CMAKE_SKIP_INSTALL_ALL_DEPENDENCY TRUE) + set(CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY TRUE) + message(STATUS "MSVC: " ${MSVC}) + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT /WX-") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd /WX-") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17") set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT jpsreport) message(STATUS "set start project for VS") endif() diff --git a/IO/OutputHandler.cpp b/IO/OutputHandler.cpp index 9edf57b4..cf33f156 100644 --- a/IO/OutputHandler.cpp +++ b/IO/OutputHandler.cpp @@ -139,13 +139,16 @@ void STDIOHandler::Write(const string& str) FileHandler::FileHandler(const char *fn) { - _pfp.open(fn); - if (!fn) { + if (fn== nullptr) { char tmp[CLENGTH]; - sprintf(tmp, "Error!!! File [%s] could not be opened!", fn); + sprintf(tmp, "Error!!! File could not be opened!"); cerr << tmp << endl; exit(0); } + else + { + _pfp.open(fn); + } } FileHandler::~FileHandler() diff --git a/demos/T-Junction/ini_KO_240_050_240.xml b/demos/T-Junction/ini_KO_240_050_240.xml index 67f5ae75..3510babc 100644 --- a/demos/T-Junction/ini_KO_240_050_240.xml +++ b/demos/T-Junction/ini_KO_240_050_240.xml @@ -1,79 +1,78 @@ <?xml version="1.0" encoding="UTF-8" ?> <JPSreport project="JPS-Project" version="0.8" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xsd.jupedsim.org/0.6/jps_report.xsd"> - <!-- geometry file --> - <geometry file = "geo_KO_240_050_240.xml" /> - <!-- trajectories file and format --> - <!-- either a file name or a path location. In the latter case all files in the directory will be used--> - <trajectories format="txt" unit="m"> - <file name="traj_KO_240_050_240.txt" /> - <path location="./" /> - </trajectories> - <!-- give relative path based on the location inifile or give the absolute path- --> - <scripts location="../../scripts/"/> + <!-- geometry file --> + <geometry file = "geo_KO_240_050_240.xml" /> + <!-- trajectories file and format --> + <!-- either a file name or a path location. In the latter case all files in the directory will be used--> + <trajectories format="txt" unit="m"> + <file name="traj_KO_240_050_240.txt" /> + <path location="./" /> + </trajectories> + <!-- give relative path based on the location inifile or give the absolute path- --> + <scripts location="../../scripts/"/> + <output location="/Users/chraibi/Desktop/"/> - - <measurement_areas unit="m"> - <area_B id="1" type="BoundingBox" zPos="None"> - <vertex x="-2.40" y="1.00" /> <!-- Clockwise --> - <vertex x="-2.40" y="3.00" /> - <vertex x="0" y="3.00" /> - <vertex x="0" y="1.00" /> - <length_in_movement_direction distance="2.0" /> - </area_B> + <measurement_areas unit="m"> + <area_B id="1" type="BoundingBox" zPos="None"> + <vertex x="-2.40" y="1.00" /> <!-- Clockwise --> + <vertex x="-2.40" y="3.00" /> + <vertex x="0" y="3.00" /> + <vertex x="0" y="1.00" /> + <length_in_movement_direction distance="2.0" /> + </area_B> <area_B id="2" type="BoundingBox" zPos="1.0"> - <vertex x="-2.40" y="1.00" /> <!-- Clockwise --> - <vertex x="-2.40" y="3.00" /> - <vertex x="0" y="3.00" /> - <vertex x="0" y="1.00" /> - <length_in_movement_direction distance="2.0" /> - </area_B> - <area_L id="3" type="Line" zPos="1.0"> - <start x="-2.40" y="1.00" /> - <end x="0" y="1.00" /> - </area_L> + <vertex x="-2.40" y="1.00" /> <!-- Clockwise --> + <vertex x="-2.40" y="3.00" /> + <vertex x="0" y="3.00" /> + <vertex x="0" y="1.00" /> + <length_in_movement_direction distance="2.0" /> + </area_B> + <area_L id="3" type="Line" zPos="1.6883"> + <start x="-2.40" y="1.00" /> + <end x="0" y="1.00" /> + </area_L> <area_L id="4" type="Line" zPos="None"> - <start x="-2.40" y="2.00" /> - <end x="0" y="2.00" /> - </area_L> - </measurement_areas> + <start x="-2.40" y="2.00" /> + <end x="0" y="2.00" /> + </area_L> + </measurement_areas> - <velocity> - <use_x_component>true</use_x_component> - <use_y_component>true</use_y_component> - <!-- The time interval that used to calculate instantaneous velocity - of ped i [fr] here v_i = (X(t+frame_step/2) - X(t+frame_step/2))/frame_step. X is location. --> - <frame_step>10</frame_step> - </velocity> + <velocity> + <use_x_component>true</use_x_component> + <use_y_component>true</use_y_component> + <!-- The time interval that used to calculate instantaneous velocity + of ped i [fr] here v_i = (X(t+frame_step/2) - X(t+frame_step/2))/frame_step. X is location. --> + <frame_step>10</frame_step> + </velocity> <velocity frame_step="10" set_movement_direction="None" ignore_backward_movement="false"/> - <!-- frame_step is the time interval that used to calculate instantaneous velocity - of ped i [fr] here v_i = (X(t+frame_step/2) - X(t+frame_step/2))/frame_step. X is location. --> + <!-- frame_step is the time interval that used to calculate instantaneous velocity + of ped i [fr] here v_i = (X(t+frame_step/2) - X(t+frame_step/2))/frame_step. X is location. --> - <!-- Method A (Zhang2011a) Flow and Vel --> - <method_A enabled="false"> - <!-- Time interval used to count the flow [fr] --> - <measurement_area id="3" frame_interval="100" plot_time_series="true"/> - </method_A> + <!-- Method A (Zhang2011a) Flow and Vel --> + <method_A enabled="true"> + <!-- Time interval used to count the flow [fr] --> + <measurement_area id="3" frame_interval="100" plot_time_series="true"/> + </method_A> - <!-- Method B (Zhang2011a) Vel and Dens based on Tin and Tout --> - <method_B enabled="false"> - <measurement_area id="1" /> - </method_B> + <!-- Method B (Zhang2011a) Vel and Dens based on Tin and Tout --> + <method_B enabled="false"> + <measurement_area id="1" /> + </method_B> - <!-- Method C (Zhang2011a) Classical density and Vel --> - <method_C enabled="false"> - <measurement_area id="1" plot_time_series="true"/> + <!-- Method C (Zhang2011a) Classical density and Vel --> + <method_C enabled="false"> + <measurement_area id="1" plot_time_series="true"/> <measurement_area id="2" plot_time_series="true"/> - </method_C> - - <!-- Method D (Zhang2011a) Voronoi density and Vel --> - <method_D enabled="true"> - <measurement_area id="1" start_frame="500" stop_frame="800" get_individual_FD="false" plot_time_series="true"/> - <one_dimensional enabled="false"/> + </method_C> + + <!-- Method D (Zhang2011a) Voronoi density and Vel --> + <method_D enabled="false"> + <measurement_area id="1" start_frame="500" stop_frame="800" get_individual_FD="false" plot_time_series="true"/> + <one_dimensional enabled="false"/> <cut_by_circle enabled="false" radius="1.0" edges="10"/> <output_voronoi_cells enabled="false" plot_graphs="false"/> - <profiles enabled="true" grid_size_x="0.20" grid_size_y="0.20"/> - </method_D> + <profiles enabled="true" grid_size_x="0.20" grid_size_y="0.20"/> + </method_D> </JPSreport> - diff --git a/general/ArgumentParser.cpp b/general/ArgumentParser.cpp index 7adde86c..0bcc4e09 100644 --- a/general/ArgumentParser.cpp +++ b/general/ArgumentParser.cpp @@ -1,8 +1,8 @@ /** * \file ArgumentParser.cpp * \date Oct 10, 2014 - * \version v0.7 - * \copyright <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved. + * \version v0.8.3 + * \copyright <2009-2018> Forschungszentrum Jülich GmbH. All rights reserved. * * \section License * This file is part of JuPedSim. @@ -36,11 +36,7 @@ #include <chrono> #include <math.h> #include <ctime> -#ifdef _MSC_VER -#include "../.vs/dirent.h" -#else -#include <dirent.h> -#endif + #ifdef _OPENMP #include <omp.h> #else @@ -52,6 +48,7 @@ #include "../IO/OutputHandler.h" #include "ArgumentParser.h" #include "../Analysis.h" +#include <boost/range/iterator_range.hpp> using namespace std; @@ -65,7 +62,7 @@ std::string ver_string(int a, int b, int c) { std::string true_cxx = #ifdef __clang__ "clang++"; -#elif defined(__GNU__) +#elif defined(__GNUC__) "g++"; #elif defined(__MINGW32__) "MinGW"; @@ -75,11 +72,10 @@ std::string true_cxx = "Compiler not identified"; #endif - std::string true_cxx_ver = #ifdef __clang__ ver_string(__clang_major__, __clang_minor__, __clang_patchlevel__); -#elif defined(__GNU__) +#elif defined(__GNUC__) ver_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); #elif defined(__MINGW32__) ver_string(__MINGW32__, __MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION); @@ -89,7 +85,29 @@ ver_string(__MINGW32__, __MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION); ""; #endif +void Logs() +{ + time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now()); + std::ostringstream oss; + char foo[100]; + if(0 < std::strftime(foo, sizeof(foo), "%a %b %d %X %Y", std::localtime(&now))) + oss << foo; + else + oss << "No time!"; + // else // hack for g++ < 5 + // oss << std::put_time(std::localtime(&now), "%a %b %d %X %Y"); + auto currentTime = oss.str(); + // first logs will go to stdout + Log->Write("----\nJuPedSim - JPSreport\n"); + Log->Write("Current date : %s", currentTime.c_str()); + Log->Write("Version : %s", JPSREPORT_VERSION); + Log->Write("Compiler : %s (%s)", true_cxx.c_str(), true_cxx_ver.c_str()); + Log->Write("Commit hash : %s", GIT_COMMIT_HASH); + Log->Write("Commit date : %s", GIT_COMMIT_DATE); + Log->Write("Branch : %s", GIT_BRANCH); + Log->Write("Python : %s (%s)\n----\n", PYTHON, PYTHON_VERSION); +} void ArgumentParser::Usage(const std::string file) { @@ -152,7 +170,11 @@ bool ArgumentParser::ParseArgs(int argc, char **argv) if (argument == "-h" || argument == "--help") { Usage(argv[0]); - return false; + } + if (argument == "-v" || argument == "--version") + { + Logs(); + exit(EXIT_SUCCESS); } // other special case where a single configuration file is submitted @@ -175,12 +197,12 @@ bool ArgumentParser::ParseArgs(int argc, char **argv) return false; } -const vector<string>& ArgumentParser::GetTrajectoriesFiles() const +const vector<fs::path>& ArgumentParser::GetTrajectoriesFiles() const { return _trajectoriesFiles; } -const string& ArgumentParser::GetProjectRootDir() const +const fs::path& ArgumentParser::GetProjectRootDir() const { return _projectRootDir; } @@ -188,33 +210,12 @@ const string& ArgumentParser::GetProjectRootDir() const bool ArgumentParser::ParseIniFile(const string& inifile) { - time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now()); - std::ostringstream oss; - char foo[100]; - if(0 < std::strftime(foo, sizeof(foo), "%a %b %d %X %Y", std::localtime(&now))) - oss << foo; - else - oss << "No time!"; - // else // hack for g++ < 5 - // oss << std::put_time(std::localtime(&now), "%a %b %d %X %Y"); - auto currentTime = oss.str(); - - // first logs will go to stdout - Log->Write("----\nJuPedSim - JPSreport\n"); - Log->Write("Current date : %s", currentTime.c_str()); - Log->Write("Version : %s", JPSREPORT_VERSION); - Log->Write("Compiler : %s (%s)", true_cxx.c_str(), true_cxx_ver.c_str()); - Log->Write("Commit hash : %s", GIT_COMMIT_HASH); - Log->Write("Commit date : %s", GIT_COMMIT_DATE); - Log->Write("Branch : %s", GIT_BRANCH); - Log->Write("Python : %s (%s)\n----\n", PYTHON, PYTHON_VERSION); + Logs(); Log->Write("INFO: \tParsing the ini file <%s>",inifile.c_str()); //extract and set the project root dir - size_t found = inifile.find_last_of("/\\"); - if (found != string::npos) - _projectRootDir = inifile.substr(0, found) + "/"; - + fs::path p(inifile); + _projectRootDir = canonical(p.parent_path()); TiXmlDocument doc(inifile); if (!doc.LoadFile()) { @@ -237,10 +238,11 @@ bool ArgumentParser::ParseIniFile(const string& inifile) } if (xMainNode->FirstChild("logfile")) { - this->SetErrorLogFile( - this->GetProjectRootDir()+xMainNode->FirstChild("logfile")->FirstChild()->Value()); + fs::path logfile(xMainNode->FirstChild("logfile")->FirstChild()->Value()); + logfile = GetProjectRootDir() / logfile; + this->SetErrorLogFile(logfile); this->SetLog(2); - Log->Write("INFO:\tlogfile <%s>", this->GetErrorLogFile().c_str()); + Log->Write("INFO:\tlogfile <%s>", GetErrorLogFile().string().c_str()); } switch (this->GetLog()) { case 0: @@ -253,7 +255,7 @@ bool ArgumentParser::ParseIniFile(const string& inifile) break; case 2: { char name[CLENGTH]=""; - sprintf(name,"%s", this->GetErrorLogFile().c_str()); + sprintf(name,"%s", GetErrorLogFile().string().c_str()); if(Log) delete Log; Log = new FileHandler(name); } @@ -265,21 +267,21 @@ bool ArgumentParser::ParseIniFile(const string& inifile) // from this point if case 2, the logs will go to a logfile if(this->GetLog() == 2) { - Log->Write("----\nJuPedSim - JPSreport\n"); - Log->Write("Current date : %s %s", __DATE__, __TIME__); - Log->Write("Version : %s", JPSREPORT_VERSION); - Log->Write("Compiler : %s (%s)", true_cxx.c_str(), true_cxx_ver.c_str()); - Log->Write("Commit hash : %s", GIT_COMMIT_HASH); - Log->Write("Commit date : %s", GIT_COMMIT_DATE); - Log->Write("Branch : %s\n----\n", GIT_BRANCH); + Logs(); } //geometry if(xMainNode->FirstChild("geometry")) { - _geometryFileName=_projectRootDir+xMainNode->FirstChildElement("geometry")->Attribute("file"); - Log->Write("INFO: \tGeometry File is: <"+_geometryFileName+">"); + fs::path p(xMainNode->FirstChildElement("geometry")->Attribute("file")); + _geometryFileName = GetProjectRootDir() / p; + if(!fs::exists(_geometryFileName)){ + Log->Write("ERROR: \tGeometry File <%s> does not exist", _geometryFileName.string().c_str()); + return false; + } + _geometryFileName = fs::canonical(_geometryFileName); + Log->Write("INFO: \tGeometry File is: <%s>", _geometryFileName.string().c_str()); } //trajectories @@ -314,72 +316,59 @@ bool ArgumentParser::ParseIniFile(const string& inifile) xFile; xFile = xFile->NextSiblingElement("file")) { //collect all the files given - _trajectoriesFilename = - + xFile->Attribute("name"); + _trajectoriesFilename = fs::path(xFile->Attribute("name")); _trajectoriesFiles.push_back(_trajectoriesFilename); //check if the given file match the format - if(boost::algorithm::ends_with(_trajectoriesFilename,fmt)) + if(boost::algorithm::ends_with(_trajectoriesFilename.string(),fmt)) { - Log->Write("INFO: \tInput trajectory file is\t<"+ (_trajectoriesFilename)+">"); + Log->Write("INFO: \tInput trajectory file is <%s>", _trajectoriesFilename.string().c_str()); } else { - Log->Write("ERROR: \tWrong file extension\t<%s> for file <%s>",fmt.c_str(),_trajectoriesFilename.c_str()); + Log->Write("ERROR: \tWrong file extension\t<%s> for file <%s>",fmt.c_str(),_trajectoriesFilename.string().c_str()); return false; } } - - if (xTrajectories->FirstChildElement("path")) + auto xmlpath = xTrajectories->FirstChildElement("path"); + if (xmlpath) { - if(xTrajectories->FirstChildElement("path")->Attribute("location")) - { - _trajectoriesLocation = xTrajectories->FirstChildElement("path")->Attribute("location"); - - } - //hack to find if it is an absolute path - // ignore the project root in this case - if ( (boost::algorithm::contains(_trajectoriesLocation,":")==false) && //windows - (boost::algorithm::starts_with(_trajectoriesLocation,"/") ==false)) //linux - // &&() osx + if(xmlpath->Attribute("location")) { - Log->Write(_trajectoriesLocation); - _trajectoriesLocation=_projectRootDir+_trajectoriesLocation; + _trajectoriesLocation = GetProjectRootDir() / fs::path(xmlpath->Attribute("location")); + // _trajectoriesLocation = canonical(_trajectoriesLocation); } } else { - _trajectoriesLocation=_projectRootDir; + fs::path p(GetProjectRootDir()); + p = canonical(p); + _trajectoriesLocation=p.string(); } - - Log->Write("INFO: \tInput directory for loading trajectory is:\t<"+ (_trajectoriesLocation)+">"); + Log->Write("INFO: \tInput directory for loading trajectory is <%s>", _trajectoriesLocation.string().c_str()); // in the case no file was specified, collect all files in the specified directory if(_trajectoriesFiles.empty()) { - DIR *dir; - struct dirent *ent; - if ((dir = opendir (_trajectoriesLocation.c_str())) != NULL) + if(exists(_trajectoriesLocation)) { /* print all the files and directories within directory */ - while ((ent = readdir (dir)) != NULL) + fs::path p(GetTrajectoriesLocation()); + p = canonical(p); + for (auto& filename : boost::make_iterator_range(fs::directory_iterator(p), {})) { - string filename=ent->d_name; - - if (boost::algorithm::ends_with(filename, fmt)) - //if (filename.find(fmt)!=std::string::npos) + string s = filename.path().string(); + if (boost::algorithm::ends_with(s, fmt)) { - //_trajectoriesFiles.push_back(_projectRootDir+filename); - _trajectoriesFiles.push_back(filename); - Log->Write("INFO: \tInput trajectory file is\t<"+ (filename)+">"); + _trajectoriesFiles.push_back(s); + Log->Write("INFO: \tInput trajectory file is <%s>", s.c_str()); } } - closedir (dir); } else { /* could not open directory */ - Log->Write("ERROR: \tcould not open the directory <"+_trajectoriesLocation+">"); + Log->Write("ERROR: \tcould not open the directory <%s>", _trajectoriesLocation.string().c_str()); return false; } } @@ -403,28 +392,62 @@ bool ArgumentParser::ParseIniFile(const string& inifile) //scripts if(xMainNode->FirstChild("scripts")) { - _scriptsLocation=xMainNode->FirstChildElement("scripts")->Attribute("location"); - if(_scriptsLocation.empty()) + _scriptsLocation=fs::path(xMainNode->FirstChildElement("scripts")->Attribute("location")); + if(!fs::exists(_scriptsLocation)) + { + Log->Write("ERROR: \tcould not find the directory <%s>", _scriptsLocation.string().c_str()); + return false; + } + if(! _scriptsLocation.is_absolute()) + { + _scriptsLocation = GetProjectRootDir() / _scriptsLocation; + _scriptsLocation = fs::canonical(_scriptsLocation); + } + + if (!exists(_scriptsLocation)) + { + /* could not open directory */ + Log->Write("ERROR: \tcould not open the directory <%s>", _scriptsLocation.string().c_str()); + return false; + } + else { - _scriptsLocation="./"; + Log->Write("INFO: \tInput directory for loading scripts is:\t<%s>", _scriptsLocation.string().c_str()); } - if ( (boost::algorithm::contains(_scriptsLocation,":")==false) && //windows - (boost::algorithm::starts_with(_scriptsLocation,"/") ==false)) //linux - // &&() osx + } + + // output directory + _outputDir = GetProjectRootDir() / "Output"; + if(xMainNode->FirstChild("output")) + { + string tmp = xMainNode->FirstChildElement("output")->Attribute("location"); + fs::path tmpPath(tmp); + _outputDir = tmpPath; + if(tmp.empty()) { - _scriptsLocation=_projectRootDir+_scriptsLocation; + _outputDir = GetProjectRootDir() / "Output"; } - if (opendir (_scriptsLocation.c_str()) == NULL) + if (! _outputDir.is_absolute()) { - /* could not open directory */ - Log->Write("ERROR: \tcould not open the directory <"+_scriptsLocation+">"); - return false; + // _outputDir=_projectRootDir + _outputDir; + _outputDir = _projectRootDir / _outputDir; } - else + } + else + Log->Write("INFO: \tDefault output directory"); + if (!exists(_outputDir)) + { + // does not exist yet. mkdir + bool res = fs::create_directory(_outputDir); + if (res == false) { - Log->Write("INFO: \tInput directory for loading scripts is:\t<"+_scriptsLocation+">"); + Log->Write("ERROR: \tcould not create the directory <"+_outputDir.string()+">"); + return false; } + else + Log->Write("INFO: \tcreated directory <"+_outputDir.string()+">"); } + Log->Write("INFO: \tOutput directory for results is:\t<"+_outputDir.string()+">"); //measurement area if(xMainNode->FirstChild("measurement_areas")) @@ -626,8 +649,7 @@ bool ArgumentParser::ParseIniFile(const string& inifile) Log->Write("INFO: \tThe instantaneous velocity in the direction of <"+MovementDirection+"> will be calculated over <"+FrameSteps+" frames>" ); } } - - // method A + // Method A TiXmlElement* xMethod_A=xMainNode->FirstChildElement("method_A"); if(xMethod_A) { @@ -876,11 +898,16 @@ bool ArgumentParser::ParseIniFile(const string& inifile) } } Log->Write("INFO: \tFinish parsing inifile"); + if(!(_isMethodA || _isMethodB || _isMethodC || _isMethodD)) + { + Log->Write("WARNING: No measurement method enabled. Nothing to do."); + exit(EXIT_SUCCESS); + } return true; } -const string& ArgumentParser::GetErrorLogFile() const +const fs::path& ArgumentParser::GetErrorLogFile() const { return _errorLogFile; } @@ -890,7 +917,7 @@ int ArgumentParser::GetLog() const return _log; } -const string& ArgumentParser::GetGeometryFilename() const +const fs::path& ArgumentParser::GetGeometryFilename() const { return _geometryFileName; } @@ -900,17 +927,21 @@ const FileFormat& ArgumentParser::GetFileFormat() const return _fileFormat; } -const string& ArgumentParser::GetTrajectoriesLocation() const +const fs::path& ArgumentParser::GetTrajectoriesLocation() const { return _trajectoriesLocation; } -const string& ArgumentParser::GetScriptsLocation() const +const fs::path& ArgumentParser::GetScriptsLocation() const { return _scriptsLocation; } +const fs::path& ArgumentParser::GetOutputLocation() const +{ + return _outputDir; +} -const string& ArgumentParser::GetTrajectoriesFilename() const +const fs::path& ArgumentParser::GetTrajectoriesFilename() const { return _trajectoriesFilename; } @@ -1079,9 +1110,9 @@ MeasurementArea* ArgumentParser::GetMeasurementArea(int id) } -void ArgumentParser::SetErrorLogFile(std::string errorLogFile) +void ArgumentParser::SetErrorLogFile(fs::path errorLogFile) { - _errorLogFile = errorLogFile; + _errorLogFile = errorLogFile; }; void ArgumentParser::SetLog(int log) { diff --git a/general/ArgumentParser.h b/general/ArgumentParser.h index 3a5df0f5..c64236ef 100644 --- a/general/ArgumentParser.h +++ b/general/ArgumentParser.h @@ -37,6 +37,10 @@ #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/adapted/c_array.hpp> +#include <filesystem> + +namespace fs = std::filesystem; + using namespace boost::geometry; typedef model::d2::point_xy<double, cs::cartesian> point_2d; typedef model::polygon<point_2d> polygon_2d; @@ -48,14 +52,16 @@ extern OutputHandler* Log; class ArgumentParser { private: - std::string _geometryFileName; - std::string _scriptsLocation; - std::string _errorLogFile; - std::string _trajectoriesLocation; - std::string _trajectoriesFilename; - std::string _projectRootDir; + fs::path _geometryFileName; + fs::path _scriptsLocation; + fs::path _errorLogFile; + fs::path _trajectoriesLocation; + fs::path _trajectoriesFilename; + fs::path _projectRootDir; + fs::path _outputDir; + FileFormat _fileFormat; - std::vector<std::string> _trajectoriesFiles; + std::vector<fs::path> _trajectoriesFiles; std::string _vComponent; bool _IgnoreBackwardMovement; @@ -70,8 +76,8 @@ private: bool _isPlotGraph; bool _isPlotIndex; /*bool _isPlotTimeSeriesA; - bool _isPlotTimeSeriesC; - bool _isPlotTimeSeriesD;*/ + bool _isPlotTimeSeriesC; + bool _isPlotTimeSeriesD;*/ bool _isOneDimensional; bool _isGetProfile; double _steadyStart; @@ -100,15 +106,15 @@ private: public: // Konstruktor ArgumentParser(); - - const std::string& GetTrajectoriesFilename() const; - const std::vector<std::string>& GetTrajectoriesFiles() const; - const std::string& GetTrajectoriesLocation() const; - const std::string& GetScriptsLocation() const; + const fs::path& GetTrajectoriesFilename() const; + const std::vector<fs::path>& GetTrajectoriesFiles() const; + const fs::path& GetTrajectoriesLocation() const; + const fs::path& GetScriptsLocation() const; const FileFormat& GetFileFormat() const; - const std::string& GetGeometryFilename() const; - const std::string& GetErrorLogFile() const; - const std::string& GetProjectRootDir() const; + const fs::path& GetGeometryFilename() const; + const fs::path& GetErrorLogFile() const; + const fs::path& GetProjectRootDir() const; + const fs::path& GetOutputLocation() const; double GetLengthMeasurementArea() const; polygon_2d GetMeasureArea() const; @@ -151,7 +157,7 @@ public: float GetGridSizeY() const; int GetLog() const; bool ParseArgs(int argc, char **argv); - void SetErrorLogFile(std::string errorLogFile); + void SetErrorLogFile(fs::path errorLogFile); void SetLog(int log); MeasurementArea* GetMeasurementArea(int id); diff --git a/general/Macros.h b/general/Macros.h index 67231e62..689e9711 100644 --- a/general/Macros.h +++ b/general/Macros.h @@ -25,7 +25,7 @@ * * **/ - + #ifndef _MACROS_H #define _MACROS_H @@ -41,10 +41,10 @@ #ifndef M_PI #define M_PI 3.14159265358979323846 -#endif +#endif #ifndef VORO_LOCATION -#define VORO_LOCATION "./Output/Fundamental_Diagram/Classical_Voronoi/" +#define VORO_LOCATION "Fundamental_Diagram/Classical_Voronoi/" #endif // should be true only when using this file in the simulation core diff --git a/main.cpp b/main.cpp index c9c1b80f..f6ba2797 100644 --- a/main.cpp +++ b/main.cpp @@ -47,20 +47,20 @@ int main(int argc, char **argv) if(args->ParseArgs(argc, argv)) { // get the number of file to analyse - const vector<string>& files = args->GetTrajectoriesFiles(); - const string& path = args->GetTrajectoriesLocation(); + const vector<fs::path>& files = args->GetTrajectoriesFiles(); + const fs::path& Path = args->GetTrajectoriesLocation(); // create and initialize the analysis engine for (unsigned int i = 0; i < files.size(); i++) { - const string& file = files[i]; + const fs::path& File = files[i]; Analysis analysis = Analysis(); - Log->Write("\nINFO: \tStart Analysis for the file: %s",file.c_str()); + Log->Write("\nINFO: \tStart Analysis for the file: %s", File.string().c_str()); Log->Write("**********************************************************************"); analysis.InitArgs(args); - analysis.RunAnalysis(file, path); + analysis.RunAnalysis(File, Path); Log->Write("**********************************************************************"); - Log->Write("INFO: \tEnd Analysis for the file: %s\n",file.c_str()); - std::cout << "INFO: \tEnd Analysis for the file: " << file.c_str() << "\n"; + Log->Write("INFO: \tEnd Analysis for the file: %s\n", File.string().c_str()); + std::cout << "INFO: \tEnd Analysis for the file: " << File.string().c_str() << "\n"; } } else diff --git a/methods/Method_A.cpp b/methods/Method_A.cpp index 545e18b9..3d91592f 100644 --- a/methods/Method_A.cpp +++ b/methods/Method_A.cpp @@ -2,7 +2,7 @@ * \file Method_A.cpp * \date Oct 10, 2014 * \version v0.7 - * \copyright <2009-2015> Forschungszentrum J��lich GmbH. All rights reserved. + * \copyright <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved. * * \section License * This file is part of JuPedSim. @@ -54,11 +54,12 @@ Method_A::~Method_A() } -bool Method_A::Process (const PedData& peddata,const string& scriptsLocation, const double& zPos_measureArea) +bool Method_A::Process (const PedData& peddata,const fs::path& scriptsLocation, const double& zPos_measureArea) { _trajName = peddata.GetTrajName(); _projectRootDir = peddata.GetProjectRootDir(); _scriptsLocation=scriptsLocation; + _outputLocation=peddata.GetOutputLocation(); _peds_t = peddata.GetPedsFrame(); _xCor = peddata.GetXCor(); _yCor = peddata.GetYCor(); @@ -113,20 +114,30 @@ bool Method_A::Process (const PedData& peddata,const string& scriptsLocation, co void Method_A::WriteFile_N_t(string data) { - string fN_t= _projectRootDir+"./Output/Fundamental_Diagram/FlowVelocity/Flow_NT_"+_trajName+"_id_"+_measureAreaId+".dat"; + fs::path tmp = ("_id_"+_measureAreaId+".dat"); + fs::path FD_FlowVelocity ("Fundamental_Diagram/FlowVelocity"); + tmp = _outputLocation / FD_FlowVelocity / ("Flow_NT_" + _trajName.string() + tmp.string()); + // _outputLocation.string()+"Fundamental_Diagram/FlowVelocity/Flow_NT_"+_trajName+"_id_"+_measureAreaId+".dat"; + string fN_t = tmp.string(); ofstream file(fN_t); if(file.is_open()) { file<<data; file.close(); - string METHOD_A_LOCATION =_projectRootDir+"./Output/Fundamental_Diagram/FlowVelocity/"; - string file_N_t ="Flow_NT_"+_trajName+"_id_"+_measureAreaId+".dat"; + fs::path tmp2 = _outputLocation / FD_FlowVelocity; +// _outputLocation.string()+"Fundamental_Diagram/FlowVelocity/"; + string METHOD_A_LOCATION =tmp2.string(); + //string file_N_t ="Flow_NT_"+_trajName+"_id_"+_measureAreaId+".dat"; + string file_N_t = fN_t; //@todo: this is redundant if(_plotTimeSeries) { - string parameters_N_t=" " + _scriptsLocation+"/_Plot_N_t.py\" -p \""+ METHOD_A_LOCATION + "\" -n "+file_N_t; + string parameters_N_t=" " + _scriptsLocation.string()+"/_Plot_N_t.py -p \""+ METHOD_A_LOCATION + "\" -n "+file_N_t; parameters_N_t = PYTHON + parameters_N_t; + std::cout << ">> <"<< parameters_N_t << ">\n"; + int res = system(parameters_N_t.c_str()); Log->Write("INFO:\tPlotting N-t diagram! Status: %d", res); + /// todo: return value of this function: true or false } } else @@ -178,10 +189,14 @@ void Method_A::FlowRate_Velocity(int fps, const vector<int>& AccumPeds, const ve { FILE *fFD_FlowVelocity; - string fdFlowVelocity = _projectRootDir+"./Output/Fundamental_Diagram/FlowVelocity/FDFlowVelocity_"+_trajName+"_id_"+_measureAreaId+".dat"; - if((fFD_FlowVelocity=Analysis::CreateFile(fdFlowVelocity))==NULL) { + fs::path tmp ("_id_"+_measureAreaId+".dat"); + tmp = _outputLocation / "Fundamental_Diagram" / "FlowVelocity" / ("FDFlowVelocity_" + _trajName.string() + tmp.string()); + //string fdFlowVelocity = _outputLocation.string() + "Fundamental_Diagram/FlowVelocity/FDFlowVelocity_"+_trajName+"_id_"+_measureAreaId+".dat"; + string fdFlowVelocity = tmp.string(); + + if((fFD_FlowVelocity=Analysis::CreateFile(fdFlowVelocity))==nullptr) { Log->Write("cannot open the file to write the Flow-Velocity data\n"); - exit(0); + exit(EXIT_FAILURE); } fprintf(fFD_FlowVelocity,"#Flow rate(1/s) \t Mean velocity(m/s)\n"); int TotalTime=AccumPeds.size(); // the total Frame of in the data file diff --git a/methods/Method_A.h b/methods/Method_A.h index 8eb1d1ae..6e953494 100644 --- a/methods/Method_A.h +++ b/methods/Method_A.h @@ -28,20 +28,19 @@ #ifndef METHOD_A_H_ #define METHOD_A_H_ -#include <string> #include "MeasurementArea.h" #include "PedData.h" -#include <vector> #include "../general/Macros.h" #include "../tinyxml/tinyxml.h" #include "../IO/OutputHandler.h" -using namespace boost::geometry; -typedef boost::geometry::model::segment<boost::geometry::model::d2::point_xy<double> > segment; - #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> + +typedef boost::geometry::model::segment<boost::geometry::model::d2::point_xy<double> > segment; + namespace ub=boost::numeric::ublas; +using namespace boost::geometry; class Method_A { @@ -50,15 +49,17 @@ public: virtual ~Method_A(); void SetMeasurementArea (MeasurementArea_L* area); void SetTimeInterval(int deltaT); - bool Process (const PedData& peddata,const std::string& scriptsLocation, const double& zPos_measureArea); + bool Process (const PedData& peddata,const fs::path& scriptsLocation, const double& zPos_measureArea); void SetPlotTimeSeries(bool plotTimeseries); private: - std::string _trajName; + fs::path _trajName; std::string _measureAreaId; MeasurementArea_L* _areaForMethod_A; - std::string _projectRootDir; - std::string _scriptsLocation; + + fs::path _projectRootDir; + fs::path _scriptsLocation; + fs::path _outputLocation; std::vector<int> _accumPedsPassLine; // the accumulative pedestrians pass a line with time std::vector<double> _accumVPassLine; // the accumulative instantaneous velocity of the pedestrians pass a line diff --git a/methods/Method_B.cpp b/methods/Method_B.cpp index 86ce997f..45909935 100644 --- a/methods/Method_B.cpp +++ b/methods/Method_B.cpp @@ -57,6 +57,8 @@ bool Method_B::Process (const PedData& peddata) Log->Write("------------------------Analyzing with Method B-----------------------------"); _trajName = peddata.GetTrajName(); _projectRootDir = peddata.GetProjectRootDir(); + _outputLocation = peddata.GetOutputLocation(); + _fps =peddata.GetFps(); _peds_t = peddata.GetPedsFrame(); _NumPeds = peddata.GetNumPeds(); @@ -140,11 +142,15 @@ void Method_B::GetFundamentalTinTout(double *DensityPerFrame,double LengthMeasur FILE *fFD_TinTout; Log->Write("---------Fundamental diagram from Method B will be calculated!------------------"); - string fdTinTout=_projectRootDir+"./Output/Fundamental_Diagram/TinTout/FDTinTout_"+_trajName+"_id_"+_measureAreaId+".dat";; - if((fFD_TinTout=Analysis::CreateFile(fdTinTout))==NULL) + fs::path tmp("_id_"+_measureAreaId+".dat"); + tmp = _outputLocation / "Fundamental_Diagram" / "TinTout" / ("FDTinTout_" + _trajName.string() + tmp.string()); +// string fdTinTout=_outputLocation.string()+"Fundamental_Diagram/TinTout/FDTinTout_"+_trajName+"_id_"+_measureAreaId+".dat"; + string fdTinTout = tmp.string(); + + if((fFD_TinTout=Analysis::CreateFile(fdTinTout))==nullptr) { - Log->Write("cannot open the file to write the TinTout data\n"); - exit(0); + Log->Write("ERROR:\tcannot open the file to write the TinTout data\n"); + exit(EXIT_FAILURE); } fprintf(fFD_TinTout,"#person Index\t density_i(m^(-2))\t velocity_i(m/s)\n"); for(int i=0; i<_NumPeds; i++) diff --git a/methods/Method_B.h b/methods/Method_B.h index 3257536b..543febe0 100644 --- a/methods/Method_B.h +++ b/methods/Method_B.h @@ -31,7 +31,7 @@ #include "PedData.h" #include "MeasurementArea.h" #include "Method_C.h" -#include "../Analysis.h" + #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> @@ -47,8 +47,10 @@ public: void SetMeasurementArea (MeasurementArea_B* area); private: - std::string _trajName; - std::string _projectRootDir; + + fs::path _trajName; + fs::path _projectRootDir; + fs::path _outputLocation; std::string _measureAreaId; std::map<int , std::vector<int> > _peds_t; MeasurementArea_B* _areaForMethod_B; diff --git a/methods/Method_C.cpp b/methods/Method_C.cpp index bcdeff27..30305e11 100644 --- a/methods/Method_C.cpp +++ b/methods/Method_C.cpp @@ -51,6 +51,7 @@ bool Method_C::Process (const PedData& peddata, const double& zPos_measureArea) _minFrame = peddata.GetMinFrame(); _trajName = peddata.GetTrajName(); _projectRootDir = peddata.GetProjectRootDir(); + _outputLocation = peddata.GetOutputLocation(); _measureAreaId = boost::lexical_cast<string>(_areaForMethod_C->_id); _fps = peddata.GetFps(); OpenFileMethodC(); @@ -77,8 +78,11 @@ bool Method_C::Process (const PedData& peddata, const double& zPos_measureArea) void Method_C::OpenFileMethodC() { - string results_C= _projectRootDir+"./Output/Fundamental_Diagram/Classical_Voronoi/rho_v_Classic_"+_trajName+"_id_"+_measureAreaId+".dat"; - if((_fClassicRhoV=Analysis::CreateFile(results_C))==NULL) { + fs::path tmp("_id_"+_measureAreaId+".dat"); + tmp = _outputLocation / "Fundamental_Diagram" / "Classical_Voronoi" / ("rho_v_Classic_" + _trajName.string() + tmp.string()); +//_outputLocation.string()+"Fundamental_Diagram/Classical_Voronoi/rho_v_Classic_"+_trajName+"_id_"+_measureAreaId+".dat"; + string results_C= tmp.string(); + if((_fClassicRhoV=Analysis::CreateFile(results_C))==nullptr) { Log->Write("Warning:\tcannot open file %s to write classical density and velocity\n", results_C.c_str()); exit(EXIT_FAILURE); } diff --git a/methods/Method_C.h b/methods/Method_C.h index 94c9cb3e..f7e7c727 100644 --- a/methods/Method_C.h +++ b/methods/Method_C.h @@ -44,8 +44,11 @@ private: int _minFrame; std::string _measureAreaId; MeasurementArea_B* _areaForMethod_C; - std::string _trajName; - std::string _projectRootDir; + + fs::path _trajName; + fs::path _projectRootDir; + fs::path _outputLocation; + float _fps; FILE *_fClassicRhoV; void OpenFileMethodC(); diff --git a/methods/Method_D.cpp b/methods/Method_D.cpp index 560dafa7..c72fd7c2 100644 --- a/methods/Method_D.cpp +++ b/methods/Method_D.cpp @@ -53,10 +53,10 @@ Method_D::Method_D() _cutByCircle = false; _cutRadius = -1; _circleEdges = -1; - _fIndividualFD = NULL; + _fIndividualFD = nullptr; _calcIndividualFD = false; - _fVoronoiRhoV = NULL; - _areaForMethod_D = NULL; + _fVoronoiRhoV = nullptr; + _areaForMethod_D = nullptr; _plotVoronoiCellData=false; _isOneDimensional=false; _startFrame =-1; @@ -71,10 +71,11 @@ Method_D::~Method_D() // { // return (number < start || number > end); // }; -bool Method_D::Process (const PedData& peddata,const std::string& scriptsLocation, const double& zPos_measureArea) +bool Method_D::Process (const PedData& peddata,const fs::path& scriptsLocation, const double& zPos_measureArea) { bool return_value = true; _scriptsLocation = scriptsLocation; + _outputLocation = peddata.GetOutputLocation(); _peds_t = peddata.GetPedsFrame(); _trajName = peddata.GetTrajName(); _projectRootDir = peddata.GetProjectRootDir(); @@ -225,8 +226,15 @@ bool Method_D::Process (const PedData& peddata,const std::string& scriptsLocatio bool Method_D::OpenFileMethodD() { - string results_V= _projectRootDir+VORO_LOCATION+"rho_v_Voronoi_"+_trajName+"_id_"+_measureAreaId+".dat"; - if((_fVoronoiRhoV=Analysis::CreateFile(results_V))==NULL) + + std::string voroLocation(VORO_LOCATION); + fs::path tmp("_id_"+_measureAreaId+".dat"); + tmp = _outputLocation / voroLocation / ("rho_v_Voronoi_" + _trajName.string() + tmp.string()); +// _outputLocation.string() + voroLocation+"rho_v_Voronoi_"+_trajName+"_id_"+_measureAreaId+".dat"; + string results_V= tmp.string(); + + + if((_fVoronoiRhoV=Analysis::CreateFile(results_V))==nullptr) { Log->Write("ERROR: \tcannot open the file to write Voronoi density and velocity\n"); return false; @@ -247,7 +255,10 @@ bool Method_D::OpenFileMethodD() bool Method_D::OpenFileIndividualFD() { - string Individualfundment=_projectRootDir+"./Output/Fundamental_Diagram/Individual_FD/IndividualFD"+_trajName+"_id_"+_measureAreaId+".dat"; + fs::path trajFileName("_id_"+_measureAreaId+".dat"); + fs::path indFDPath("Fundamental_Diagram"); + indFDPath = _outputLocation / indFDPath / "IndividualFD" / (_trajName.string() + trajFileName.string()); + string Individualfundment=indFDPath.string(); if((_fIndividualFD=Analysis::CreateFile(Individualfundment))==nullptr) { Log->Write("ERROR:\tcannot open the file individual\n"); @@ -340,20 +351,29 @@ std::tuple<double,double> Method_D::GetVoronoiDensityVelocity(const vector<polyg // and velocity is calculated for every frame void Method_D::GetProfiles(const string& frameId, const vector<polygon_2d>& polygons, const vector<double>& velocity) { - string voronoiLocation=_projectRootDir+VORO_LOCATION+"field/"; + std::string voroLocation(VORO_LOCATION); + fs::path tmp("field"); + fs::path vtmp ("velocity"); + fs::path dtmp("density"); + tmp = _outputLocation / voroLocation / tmp; + vtmp = tmp / vtmp / ("Prf_v_"+_trajName.string()+"_id_"+_measureAreaId+"_"+frameId+".dat"); + dtmp = tmp / dtmp / ("Prf_d_"+_trajName.string()+"_id_"+_measureAreaId+"_"+frameId+".dat"); + //string voronoiLocation=_outputLocation.string() + voroLocation+"field/"; - string Prfvelocity=voronoiLocation+"/velocity/Prf_v_"+_trajName+"_id_"+_measureAreaId+"_"+frameId+".dat"; - string Prfdensity=voronoiLocation+"/density/Prf_d_"+_trajName+"_id_"+_measureAreaId+"_"+frameId+".dat"; + // string Prfvelocity=voronoiLocation+"/velocity/Prf_v_"+_trajName.string()+"_id_"+_measureAreaId+"_"+frameId+".dat"; + // string Prfdensity=voronoiLocation+"/density/Prf_d_"+_trajName.string()+"_id_"+_measureAreaId+"_"+frameId+".dat"; + string Prfvelocity = vtmp.string(); + string Prfdensity = dtmp.string(); FILE *Prf_velocity; - if((Prf_velocity=Analysis::CreateFile(Prfvelocity))==NULL) { + if((Prf_velocity=Analysis::CreateFile(Prfvelocity))==nullptr) { Log->Write("cannot open the file <%s> to write the field data\n",Prfvelocity.c_str()); - exit(0); + exit(EXIT_FAILURE); } FILE *Prf_density; - if((Prf_density=Analysis::CreateFile(Prfdensity))==NULL) { + if((Prf_density=Analysis::CreateFile(Prfdensity))==nullptr) { Log->Write("cannot open the file to write the field density\n"); - exit(0); + exit(EXIT_FAILURE); } int NRow = (int)ceil((_geoMaxY-_geoMinY)/_grid_size_Y); // the number of rows that the geometry will be discretized for field analysis @@ -387,18 +407,40 @@ void Method_D::GetProfiles(const string& frameId, const vector<polygon_2d>& poly void Method_D::OutputVoroGraph(const string & frameId, std::vector<std::pair<polygon_2d, int> >& polygons_id, int numPedsInFrame, vector<double>& XInFrame, vector<double>& YInFrame,const vector<double>& VInFrame) { //string voronoiLocation=_projectRootDir+"./Output/Fundamental_Diagram/Classical_Voronoi/VoronoiCell/id_"+_measureAreaId; - string voronoiLocation=_projectRootDir+VORO_LOCATION+"VoronoiCell/"; - polygon_2d poly; - -#if defined(_WIN32) - mkdir(voronoiLocation.c_str()); -#else - mkdir(voronoiLocation.c_str(), 0777); -#endif - - string polygon=voronoiLocation+"/polygon"+_trajName+"_id_"+_measureAreaId+"_"+frameId+".dat"; + fs::path voroLocPath(_outputLocation); + fs::path voro_location_path (VORO_LOCATION); // TODO: convert + // this MACRO to + // path. Maybe + // remove the MACRO? + voroLocPath = voroLocPath / voro_location_path / "VoronoiCell"; + polygon_2d poly; + if(!fs::exists(voroLocPath)) + { + if(!fs::create_directories(voroLocPath)) + { + Log->Write("ERROR:\tcan not create directory <%s>", voroLocPath.string().c_str()); + std::cout << "can not create directory "<< voroLocPath.string().c_str() << "\n"; + exit(EXIT_FAILURE); + } + else + std::cout << "create directory "<< voroLocPath.string().c_str() << "\n"; + } + + fs::path polygonPath=voroLocPath / "polygon"; + if(!fs::exists(polygonPath)) + { + if(!fs::create_directory(polygonPath)) + { + Log->Write("ERROR:\tcan not create directory <%s>", polygonPath.string().c_str()); + exit(EXIT_FAILURE); + } + } + fs::path trajFileName(_trajName.string()+"_id_"+_measureAreaId+"_"+frameId+".dat"); + fs::path p = polygonPath / trajFileName; + string polygon = p.string(); ofstream polys (polygon.c_str()); + if(polys.is_open()) { //for(vector<polygon_2d> polygon_iterator=polygons.begin(); polygon_iterator!=polygons.end(); polygon_iterator++) @@ -427,8 +469,15 @@ void Method_D::OutputVoroGraph(const string & frameId, std::vector<std::pair<po Log->Write("ERROR:\tcannot create the file <%s>",polygon.c_str()); exit(EXIT_FAILURE); } - - string v_individual=voronoiLocation+"/speed"+_trajName+"_id_"+_measureAreaId+"_"+frameId+".dat"; + fs::path speedPath=voroLocPath / "speed"; + if(!fs::exists(speedPath)) + if(!fs::create_directory(speedPath)) + { + Log->Write("ERROR:\tcan not create directory <%s>", speedPath.string().c_str()); + exit(EXIT_FAILURE); + } + fs::path pv = speedPath /trajFileName; + string v_individual= pv.string(); ofstream velo (v_individual.c_str()); if(velo.is_open()) { @@ -439,7 +488,7 @@ void Method_D::OutputVoroGraph(const string & frameId, std::vector<std::pair<po } else { - Log->Write("ERROR:\tcannot create the file <%s>",v_individual.c_str()); + Log->Write("ERROR:\tcannot create the file <%s>",pv.string().c_str()); exit(EXIT_FAILURE); } @@ -460,10 +509,11 @@ void Method_D::OutputVoroGraph(const string & frameId, std::vector<std::pair<po if(_plotVoronoiCellData) { - string parameters_rho=" " + _scriptsLocation+"/_Plot_cell_rho.py -f \""+ voronoiLocation + "\" -n "+ _trajName+"_id_"+_measureAreaId+"_"+frameId+ - " -g "+_geometryFileName+" -p "+_trajectoryPath; - string parameters_v=" " + _scriptsLocation+"/_Plot_cell_v.py -f \""+ voronoiLocation + "\" -n "+ _trajName+"_id_"+_measureAreaId+"_"+frameId+ - " -g "+_geometryFileName+" -p "+_trajectoryPath; + //@todo: use fs::path + string parameters_rho=" " + _scriptsLocation.string()+"/_Plot_cell_rho.py -f \""+ voroLocPath.string() + "\" -n "+ _trajName.string()+"_id_"+_measureAreaId+"_"+frameId+ + " -g "+_geometryFileName.string()+" -p "+_trajectoryPath.string(); + string parameters_v=" " + _scriptsLocation.string()+"/_Plot_cell_v.py -f \""+ voroLocPath.string() + "\" -n "+ _trajName.string() + "_id_"+_measureAreaId+"_"+frameId+ + " -g "+_geometryFileName.string()+" -p "+_trajectoryPath.string(); if(_plotVoronoiIndex) parameters_rho += " -i"; @@ -578,12 +628,12 @@ void Method_D::SetGeometryBoundaries(double minX, double minY, double maxX, doub _geoMaxY = maxY; } -void Method_D::SetGeometryFileName(const std::string& geometryFile) +void Method_D::SetGeometryFileName(const fs::path& geometryFile) { _geometryFileName=geometryFile; } -void Method_D::SetTrajectoriesLocation(const std::string& trajectoryPath) +void Method_D::SetTrajectoriesLocation(const fs::path& trajectoryPath) { _trajectoryPath=trajectoryPath; } diff --git a/methods/Method_D.h b/methods/Method_D.h index 4946acba..49ebaa9d 100644 --- a/methods/Method_D.h +++ b/methods/Method_D.h @@ -27,21 +27,12 @@ #ifndef METHOD_D_H_ #define METHOD_D_H_ -#include <vector> + #include "PedData.h" #include "../Analysis.h" #include "VoronoiDiagram.h" -#include <algorithm> -#ifdef __linux__ -#include <sys/stat.h> -#include <dirent.h> -#elif __APPLE__ -#include <sys/stat.h> -#include <dirent.h> -#else -#include <direct.h> -#endif + //handle more than two person are in one line #define dmin 200 @@ -53,11 +44,11 @@ class Method_D public: Method_D(); virtual ~Method_D(); - bool Process (const PedData& peddata,const std::string& scriptsLocation, const double& zPos_measureArea); + bool Process (const PedData& peddata,const fs::path& scriptsLocation, const double& zPos_measureArea); void SetCalculateIndividualFD(bool individualFD); void Setcutbycircle(double radius,int edges); void SetGeometryPolygon(polygon_2d geometryPolygon); - void SetGeometryFileName(const std::string& geometryFile); + void SetGeometryFileName(const fs::path& geometryFile); void SetGeometryBoundaries(double minX, double minY, double maxX, double maxY); void SetGridSize(double x, double y); void SetCalculateProfiles(bool calcProfile); @@ -66,7 +57,7 @@ public: void SetPlotVoronoiIndex(bool plotVoronoiIndex); void SetMeasurementArea (MeasurementArea_B* area); void SetDimensional (bool dimension); - void SetTrajectoriesLocation(const std::string& trajectoryPath); + void SetTrajectoriesLocation(const fs::path& trajectoryPath); void SetStartFrame(int startFrame); void SetStopFrame(int stopFrame); @@ -74,9 +65,10 @@ private: std::map<int , std::vector<int> > _peds_t; std::string _measureAreaId; MeasurementArea_B* _areaForMethod_D; - std::string _trajName; - std::string _projectRootDir; - std::string _scriptsLocation; + fs::path _trajName; + fs::path _projectRootDir; + fs::path _outputLocation; + fs::path _scriptsLocation; bool _calcIndividualFD; polygon_2d _areaIndividualFD; bool _getProfile; @@ -99,8 +91,8 @@ private: float _fps; bool OpenFileMethodD(); bool OpenFileIndividualFD(); - std::string _geometryFileName; - std::string _trajectoryPath; + fs::path _geometryFileName; + fs::path _trajectoryPath; int _startFrame; int _stopFrame; @@ -111,7 +103,7 @@ private: std::tuple<double,double> GetVoronoiDensityVelocity(const std::vector<polygon_2d>& polygon, const std::vector<double>& Velocity, const polygon_2d & measureArea); void GetProfiles(const std::string& frameId, const std::vector<polygon_2d>& polygons, const std::vector<double>& velocity); void OutputVoroGraph(const std::string & frameId, std::vector<std::pair<polygon_2d, int> >& polygons, int numPedsInFrame,std::vector<double>& XInFrame, - std::vector<double>& YInFrame,const std::vector<double>& VInFrame); + std::vector<double>& YInFrame,const std::vector<double>& VInFrame); void GetIndividualFD(const std::vector<polygon_2d>& polygon, const std::vector<double>& Velocity, const std::vector<int>& Id, const polygon_2d& measureArea, const std::string& frid); /** * Reduce the precision of the points to two digits diff --git a/methods/PedData.cpp b/methods/PedData.cpp index 5cae0000..08d4d47e 100644 --- a/methods/PedData.cpp +++ b/methods/PedData.cpp @@ -29,7 +29,6 @@ #include "PedData.h" #include <cmath> #include <string> - using std::string; using std::map; using std::vector; @@ -43,8 +42,7 @@ PedData::~PedData() { } - -bool PedData::ReadData(const string& projectRootDir, const string& path, const string& filename, const FileFormat& trajformat, int deltaF, std::string vComponent, const bool IgnoreBackwardMovement) +bool PedData::ReadData(const fs::path& projectRootDir, const fs::path&outputLocation, const fs::path& path, const fs::path& filename, const FileFormat& trajformat, int deltaF, std::string vComponent, const bool IgnoreBackwardMovement) { _minID = INT_MAX; _minFrame = INT_MAX; @@ -52,22 +50,25 @@ bool PedData::ReadData(const string& projectRootDir, const string& path, const s _vComponent = vComponent; _IgnoreBackwardMovement=IgnoreBackwardMovement; _projectRootDir = projectRootDir; + _outputLocation = outputLocation; _trajName = filename; - - string fullTrajectoriesPathName= path+ "/" +_trajName; - Log->Write("INFO:\tthe name of the trajectory is: <%s>",_trajName.c_str()); - Log->Write("INFO:\tfull name of the trajectory is: <%s>",fullTrajectoriesPathName.c_str()); + fs::path p(path); + p /= _trajName; + fs::path fullTrajectoriesPathName= path / _trajName; + Log->Write("INFO:\tthe name of the trajectory is: <%s>", _trajName.string().c_str()); + Log->Write("INFO:\tfull name of the trajectory is: <%s>", fullTrajectoriesPathName.string().c_str()); bool result=true; if(trajformat == FORMAT_XML_PLAIN) { - TiXmlDocument docGeo(fullTrajectoriesPathName); + TiXmlDocument docGeo(fullTrajectoriesPathName.string()); if (!docGeo.LoadFile()) { Log->Write("ERROR: \t%s", docGeo.ErrorDesc()); - Log->Write("ERROR: \tcould not parse the trajectories file <%s>",fullTrajectoriesPathName.c_str()); + Log->Write("ERROR: \tcould not parse the trajectories file <%s>",fullTrajectoriesPathName.string().c_str()); return false; } TiXmlElement* xRootNode = docGeo.RootElement(); - result=InitializeVariables(xRootNode); //initialize some global variables + fs::path filename(xRootNode->ValueStr()); + result=InitializeVariables(filename); //initialize some global variables } else if(trajformat == FORMAT_PLAIN) @@ -78,7 +79,7 @@ bool PedData::ReadData(const string& projectRootDir, const string& path, const s } // init _xCor, _yCor and _zCor -bool PedData::InitializeVariables(const string& filename) +bool PedData::InitializeVariables(const fs::path& filename) { vector<double> xs; vector<double> ys; @@ -88,10 +89,10 @@ bool PedData::InitializeVariables(const string& filename) vector<int> _FramesTXT; // the Frame data from txt format trajectory data //string fullTrajectoriesPathName= _projectRootDir+"./"+_trajName; ifstream fdata; - fdata.open(filename.c_str()); + fdata.open(filename.string()); if (fdata.is_open() == false) { - Log->Write("ERROR: \t could not parse the trajectories file <%s>",filename.c_str()); + Log->Write("ERROR: \t could not parse the trajectories file <%s>",filename.string().c_str()); return false; } else @@ -212,7 +213,7 @@ bool PedData::InitializeVariables(const string& filename) if(fps_found == 0) { Log->Write("ERROR:\tFrame rate fps not defined "); - exit(1); + exit(EXIT_FAILURE); } Log->Write("INFO:\t Finished reading the data"); @@ -779,7 +780,7 @@ float PedData::GetFps() const return _fps; } -string PedData::GetTrajName() const +fs::path PedData::GetTrajName() const { return _trajName; } @@ -812,7 +813,12 @@ int* PedData::GetLastFrame() const return _lastFrame; } -string PedData::GetProjectRootDir() const +fs::path PedData::GetProjectRootDir() const { return _projectRootDir; } + +fs::path PedData::GetOutputLocation() const +{ + return _outputLocation; +} diff --git a/methods/PedData.h b/methods/PedData.h index 4b174a49..432b5f57 100644 --- a/methods/PedData.h +++ b/methods/PedData.h @@ -1,8 +1,8 @@ /** * \file PedData.h * \date Oct 10, 2014 - * \version v0.7 - * \copyright <2009-2015> Forschungszentrum J��lich GmbH. All rights reserved. + * \version v0.8.3 + * \copyright <2009-2018> Forschungszentrum Jülich GmbH. All rights reserved. * * \section License * This file is part of JuPedSim. @@ -42,6 +42,9 @@ #include <boost/numeric/ublas/io.hpp> namespace ub=boost::numeric::ublas; +#include <filesystem> + +namespace fs = std::filesystem; extern OutputHandler* Log; @@ -58,8 +61,8 @@ public: int GetNumFrames() const; int GetNumPeds() const; float GetFps() const; - std::string GetTrajName() const; - std::string GetProjectRootDir() const; + fs::path GetTrajName() const; + fs::path GetProjectRootDir() const; std::map<int , std::vector<int>> GetPedsFrame() const; ub::matrix<double> GetXCor() const; ub::matrix<double> GetYCor() const; @@ -74,26 +77,27 @@ public: std::vector<double> GetYInFrame(int frame, const std::vector<int>& ids) const; std::vector<double> GetZInFrame(int frame, const std::vector<int>& ids) const; std::vector<double> GetVInFrame(int frame, const std::vector<int>& ids, double zPos) const; - bool ReadData(const std::string& projectRootDir, const std::string& path, const std::string& filename, const FileFormat& _trajformat, int deltaF, std::string vComponent, const bool IgnoreBackwardMovement); + bool ReadData(const fs::path& projectRootDir,const fs::path& outputDir, const fs::path& path, const fs::path& filename, const FileFormat& _trajformat, int deltaF, std::string vComponent, const bool IgnoreBackwardMovement); + fs::path GetOutputLocation() const; private: - bool InitializeVariables(const std::string& filename); - bool InitializeVariables(TiXmlElement* xRootNode); - void CreateGlobalVariables(int numPeds, int numFrames); - double GetInstantaneousVelocity(int Tnow,int Tpast, int Tfuture, int ID, int *Tfirst, int *Tlast, const ub::matrix<double> & Xcor, const ub::matrix<double> & Ycor) const; - double GetInstantaneousVelocity1(int Tnow,int Tpast, int Tfuture, int ID, int *Tfirst, int *Tlast, const ub::matrix<double> & Xcor, const ub::matrix<double> & Ycor) const; + bool InitializeVariables(const fs::path& filename); + bool InitializeVariables(TiXmlElement* xRootNode); + void CreateGlobalVariables(int numPeds, int numFrames); + double GetInstantaneousVelocity(int Tnow,int Tpast, int Tfuture, int ID, int *Tfirst, int *Tlast, const ub::matrix<double> & Xcor, const ub::matrix<double> & Ycor) const; + double GetInstantaneousVelocity1(int Tnow,int Tpast, int Tfuture, int ID, int *Tfirst, int *Tlast, const ub::matrix<double> & Xcor, const ub::matrix<double> & Ycor) const; private: - - std::string _trajName=""; - std::string _projectRootDir=""; + fs::path _trajName; + fs::path _projectRootDir; + fs::path _outputLocation=""; int _minFrame=0; int _minID=1; int _numFrames=0; // total number of frames int _numPeds=0; // total number of pedestrians float _fps=16; - std::map<int , std::vector<int>> _peds_t; + std::map<int , std::vector<int> > _peds_t; int _deltaF=5; std::string _vComponent="B"; @@ -105,7 +109,7 @@ private: ub::matrix<double> _yCor; ub::matrix<double> _zCor; ub::matrix<std::string> _vComp; - + }; #endif /* PEDDATA_H_ */ diff --git a/packages.config b/packages.config new file mode 100644 index 00000000..5bdebd97 --- /dev/null +++ b/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="boost" version="1.68.0.0" targetFramework="native" /> +</packages> diff --git a/scripts/_Plot_N_t.py b/scripts/_Plot_N_t.py index ed8480a2..17f31eda 100644 --- a/scripts/_Plot_N_t.py +++ b/scripts/_Plot_N_t.py @@ -1,20 +1,20 @@ from numpy import * import matplotlib import matplotlib.pyplot as plt -from Polygon import * +from Polygon import * import matplotlib.cm as cm import pylab import argparse import sys - +import os def getParserArgs(): - parser = argparse.ArgumentParser(description='Plot N-t graph measured from method A') - parser.add_argument("-p", "--pathfile", default="./", help='give the path of source file') - parser.add_argument("-n", "--namefile", help='give the name of the source file') - #parser.add_argument("-f", "--fps", default="16", type=float, help='give the frame rate of data') - args = parser.parse_args() - return args + parser = argparse.ArgumentParser(description='Plot N-t graph measured from method A') + parser.add_argument("-p", "--pathfile", default="./", help='give the path of source file') + parser.add_argument("-n", "--namefile", help='give the name of the source file') + #parser.add_argument("-f", "--fps", default="16", type=float, help='give the frame rate of data') + args = parser.parse_args() + return args if __name__ == '__main__': @@ -29,14 +29,17 @@ if __name__ == '__main__': ax1 = fig.add_subplot(111,aspect='auto') plt.rc("font", size=30) plt.rc('pdf',fonttype = 42) - data_NT = loadtxt("%s/%s"%(pathfile,namefile)) + data_file = os.path.join(pathfile, namefile) + if not os.path.exists(data_file): + sys.exit("ERROR %s: file does not exist <%s>" %(sys.argv[0], data_file)) + + data_NT = loadtxt(data_file) + #"%s/%s"%(pathfile,namefile)) #plt.plot(data_NT[:,0]/fps,data_NT[:,1], 'r-') plt.plot(data_NT[:,0],data_NT[:,1], 'r-') plt.xlabel("t [s]") plt.ylabel("N [-]") plt.title("%s"%title) - plt.savefig("%s/%s.png"%(pathfile,figname)) + figname = os.path.join(pathfile, figname) + plt.savefig("%s.png"%figname) plt.close() - - - diff --git a/scripts/_Plot_cell_rho.py b/scripts/_Plot_cell_rho.py index ba8f4766..2ea0f910 100644 --- a/scripts/_Plot_cell_rho.py +++ b/scripts/_Plot_cell_rho.py @@ -178,11 +178,14 @@ def main(): # ax1.set_aspect("equal") plot_geometry(geoFile) - density = np.array([]) density_orig = np.array([]) polygons = [] # polygons converted from string - polygon_filename = os.path.join(filepath, "polygon"+namefile+".dat") + polygon_path = os.path.join(filepath, "polygon") + polygon_filename = os.path.join(polygon_path, '.'.join((namefile, "dat"))) + if(not os.path.exists(polygon_filename)): + sys.exit("ERROR %s: File does not exist. <%s>"%(argv[0], polygon_filename)) + File = open(polygon_filename) polys = File.readlines() File.close() diff --git a/scripts/_Plot_cell_v.py b/scripts/_Plot_cell_v.py index 2467a295..d25652f7 100644 --- a/scripts/_Plot_cell_v.py +++ b/scripts/_Plot_cell_v.py @@ -69,10 +69,18 @@ if __name__ == '__main__': plot_geometry(geoFile) velocity = np.array([]) - polygon_filename = os.path.join(filepath, "polygon"+namefile+".dat") + polygon_path = os.path.join(filepath, "polygon") + polygon_filename = os.path.join(polygon_path, '.'.join((namefile, "dat"))) + if(not os.path.exists(polygon_filename)): + sys.exit("ERROR %s: File does not exist. <%s>"%(argv[0], polygon_filename)) + File = open(polygon_filename) polys = File.readlines() - velocity_filename = os.path.join(filepath, "speed"+namefile+".dat") + velocity_path = os.path.join(filepath, "speed") + velocity_filename = os.path.join(velocity_path, '.'.join((namefile, "dat"))) + if(not os.path.exists(velocity_filename)): + sys.exit("ERROR %s: File does not exist. <%s>"%(argv[0], velocity_filename)) + velocity = np.loadtxt(velocity_filename) sm = cm.ScalarMappable(cmap=cm.jet) sm.set_array(velocity) diff --git a/scripts/_Plot_profiles.py b/scripts/_Plot_profiles.py index 8d5ea6fd..3071b801 100644 --- a/scripts/_Plot_profiles.py +++ b/scripts/_Plot_profiles.py @@ -48,14 +48,15 @@ if __name__ == '__main__': print("geometry: X [%.1f, %.1f], Y=[%.1f, %.1f]" % (geominX, geomaxX, geominY, geomaxY)) - density_files = os.path.join( - pathfile, "density", "*%s*%d.dat" % - (nametraj, beginsteady)) + density_files_path = os.path.join(pathfile, "density") + density_files = os.path.join(density_files_path, + "*%s*%d.dat"%(nametraj, beginsteady)) + print("looking for %s" % density_files) f_Voronoi = glob.glob(density_files) # get the shape of the matrices - if len(f_Voronoi) == 0: - sys.exit("no Voronoi files found in %s" % pathfile) + if not f_Voronoi: + sys.exit("%s: no Voronoi files found in %s" %(sys.argv[0], pathfile)) shape = np.shape(np.loadtxt(f_Voronoi[0])) density = np.zeros(shape) @@ -66,14 +67,14 @@ if __name__ == '__main__': ax1 = fig.add_subplot(111, aspect='1') plt.rc("font", size=40) for j in range(beginsteady, endsteady): - density_file = os.path.join(pathfile, "density", "Prf_d_%s_id_1_%.5d.dat" %(nametraj, j)) + density_file = os.path.join(density_files_path, "Prf_d_%s_id_1_%.5d.dat" %(nametraj, j)) if os.path.exists(density_file): print("loading: %s" % density_file) density += np.loadtxt(density_file) - + else: print("WARNING: file not found %s"%density_file) - + density = density / (endsteady - beginsteady) @@ -98,8 +99,9 @@ if __name__ == '__main__': ax1 = fig.add_subplot(111, aspect='1') plt.rc("font", size=40) for j in range(beginsteady, endsteady): - velocity_file = os.path.join( - pathfile, "velocity", "Prf_v_%s_id_1_%.5d.dat" % (nametraj, j)) + velocity_file_path = os.path.join(pathfile, "velocity") + velocity_file = os.path.join(velocity_file_path, + "Prf_v_%s_id_1_%.5d.dat" % (nametraj, j)) if os.path.exists(velocity_file): print("loading: %s" % velocity_file) velocity += np.loadtxt(velocity_file) @@ -137,10 +139,8 @@ if __name__ == '__main__': divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="2.5%", pad=0.3) cb = plt.colorbar(im, cax=cax) - cb.set_label('Specific flow [$1/m \cdot s$]') - figname = "%s/profile_flux_%s.png" % (pathfile, nametraj) + cb.set_label(r'Specific flow [$1/m \cdot s$]') flux_figname = os.path.join(pathfile, "profile_flux_%s.png" % nametraj) - plt.savefig(flux_figname) plt.close() -- GitLab