From a815a56e5bae8df3d467ddc3e43f3d26e8bfbeb8 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 28 May 2020 22:20:01 +0530 Subject: change to outitf.c, to iterate all the IPs and ports and send close message to all the ghdl-server --- src/outitf.c | 148 +++++++++++++++++++++-------------------------------------- 1 file changed, 53 insertions(+), 95 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index fba5224..9a656c1 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -49,6 +49,12 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include #include #include +// 27.May.2020 - BM - Added the following #include +#include +#include +#include +#include +#include extern char *spice_analysis_get_name(int index); extern char *spice_analysis_get_description(int index); @@ -112,102 +118,46 @@ static double *valueold, *valuenew; static bool savenone = FALSE; #endif -/* 10.Mar.2017 - RM - Added nghdl_tb_SIGUSR1().*/ -static void nghdl_tb_SIGUSR1(char* pid_file) -{ - int ret; - char line[80]; - char* nptr; - pid_t pid[256], tmp; - int count=0, i; - - FILE* fp = fopen(pid_file, "r"); - - if (fp) - { - /* 22.Oct.2019 - RP - Scan and store all the PIDs in this file */ - while (fscanf(fp, "%s", line) == 1) - { - // PID is converted to a decimal value. - tmp = (pid_t) strtol(line, &nptr, 10); - if ((errno != ERANGE) && (errno!= EINVAL)) - { - pid[count++] = tmp; - } - } - - fclose(fp); - } - - /* 22.Oct.2019 - RP - Kill all the active PIDs */ - for(i=0; i*" files.*/ - while ((dirp = readdir(dirfd)) != NULL) - { - struct stat stbuf; - sprintf(filename_tmp, "/tmp/%s", dirp->d_name); - if (strstr(filename_tmp, pid_file_prefix)) - { - if (stat(filename_tmp, &stbuf) == -1) - { - fprintf(stderr, - "nghdl_orphan_tb: stat() failed; ERRNO=%d on file:%s\n", - errno, filename_tmp); - continue; - } - - if ((stbuf.st_mode & S_IFMT) == S_IFDIR) - { - continue; - } - else - { - nghdl_tb_SIGUSR1(filename_tmp); - } - } - } - - // 22.Oct.2019 - RP - char ip_filename[40]; - sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - remove(ip_filename); -} -/* End 10.Mar.2017 - RM */ - -/* The two "begin plot" routines share all their internals... */ +// The two "begin plot" routines share all their internals... int OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, @@ -1136,10 +1086,13 @@ fileEnd(runDesc *run) /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are * found, force them to exit. */ - nghdl_orphan_tb(); - + //nghdl_orphan_tb(); /* End 10.Mar.2017 */ + /* 28.MaY.2020 - BM */ + close_server; + /* End 28.MaY.2020 */ + if (run->fp != stdout) { long place = ftell(run->fp); @@ -1294,9 +1247,14 @@ static void plotEnd(runDesc *run) { /* 10.Mar.2017 - RM */ - nghdl_orphan_tb(); + //nghdl_orphan_tb(); /* End 10.Mar.2017 */ + /* 28.MaY.2020 - BM */ + close_server; + /* End 28.MaY.2020 */ + + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); } -- cgit From c8cfe4d383d38bdb9ebc5ed8b7f8cec60bdcb0e6 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 28 May 2020 22:21:44 +0530 Subject: change to ghdlserver: receive close message from NGSPICE --- src/ghdlserver/ghdlserver.c | 97 +++++---------------------------------------- 1 file changed, 10 insertions(+), 87 deletions(-) (limited to 'src') diff --git a/src/ghdlserver/ghdlserver.c b/src/ghdlserver/ghdlserver.c index 60e1a20..d324e7b 100644 --- a/src/ghdlserver/ghdlserver.c +++ b/src/ghdlserver/ghdlserver.c @@ -89,89 +89,6 @@ struct my_struct { static struct my_struct *s, *users, *tmp = NULL; -/* 17.Mar.2017 - RM - Get the process id of ngspice program.*/ -static int get_ngspice_pid(void) -{ - DIR* dirp; - FILE* fp = NULL; - struct dirent* dir_entry; - char path[1024], rd_buff[1024]; - pid_t pid = -1; - - if ((dirp = opendir("/proc/")) == NULL) - { - perror("get_ngspice_pid() - opendir /proc failed "); - exit(-1); - } - - while ((dir_entry = readdir(dirp)) != NULL) - { - char* nptr; - int valid_num = 0; - - int tmp = strtol(dir_entry->d_name, &nptr, 10); - if ((errno == ERANGE) && (tmp == LONG_MAX || tmp == LONG_MIN)) - { - perror("get_ngspice_pid() - strtol"); // Number out of range. - return(-1); - } - if (dir_entry->d_name == nptr) - { - continue; // No digits found. - } - if (tmp) - { - sprintf(path, "/proc/%s/comm", dir_entry->d_name); - if ((fp = fopen(path, "r")) != NULL) - { - fscanf(fp, "%s", rd_buff); - if (strcmp(rd_buff, NGSPICE) == 0) - { - pid = (pid_t)tmp; // 5.July.2019 - RP - Kludge - } - } - } - } - - if (fp) fclose(fp); - - return(pid); -} - - -/* 23.Mar.2017 - RM - Pass the sock_port argument. We need this if a netlist - * uses more than one instance of the same test bench, so that we can uniquely - * identify the PID files. - */ -/* 10.Mar.2017 - RM - Create PID file for the test bench in /tmp. */ -static void create_pid_file(int sock_port) -{ - pid_t my_pid = getpid(); - pid_t ngspice_pid = get_ngspice_pid(); - - if (ngspice_pid == -1) - { - fprintf(stderr, "create_pid_file() Failed to get ngspice PID"); - syslog(LOG_ERR, "create_pid_file() Failed to get ngspice PID"); - exit(1); - } - - sprintf(pid_filename, "/tmp/NGHDL_%d_%s_%d", ngspice_pid, __progname, sock_port); - pid_file = fopen(pid_filename, "a"); // 26.Sept.2019 - RP - Open file in append mode - - if (pid_file) - { - pid_file_created = 1; - fprintf(pid_file,"%d\n", my_pid); - fclose(pid_file); - } else { - perror("create_pid_file() - cannot open PID file "); - syslog(LOG_ERR, "create_pid_file(): Unable to open PID file in /tmp"); - exit(1); - } -} - - #ifdef DEBUG static char* curtim(void) { @@ -316,16 +233,23 @@ static int connect_to_client(int server_fd) //Receive string from socket and put it inside buffer. static void receive_string(int sock_id, char* buffer) -{ +{ int nbytes = 0; /* 08.Nov.2019 - RP - Blocking Socket - Receive */ nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); if (nbytes <= 0) { - perror("receive_string() - READ FAILURE "); + perror("receive_string() - READ FAILURE "); exit(1); } + + //28.May.2020 - BM - Added method to close server by NGSPICE after simulation + char *exitstr = "CLOSE_FROM_NGSPICE"; + if (strcmp(buffer, exitstr)==0) + { + Vhpi_Exit(0); + } } @@ -447,7 +371,6 @@ void Vhpi_Initialize(int sock_port, char sock_ip[]) nanosleep(&ts, NULL); // 10.Mar.2017 - RM - Create PID file for the test bench. - create_pid_file(sock_port); } @@ -510,4 +433,4 @@ void Vhpi_Exit(int sig) close(server_socket_id); syslog(LOG_INFO, "*** Closed VHPI link. Exiting... ***"); exit(0); -} \ No newline at end of file +} -- cgit From 0c128ccda3fbb75522d317649917f695f0cf5ef1 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 28 May 2020 22:24:18 +0530 Subject: automate the writing of IP and port to the common_ip_file --- src/model_generation.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/model_generation.py b/src/model_generation.py index da8e272..dcb0788 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -268,7 +268,8 @@ class ModelGeneration: if (fptr) { char line[20]; - while(fscanf(fptr, "%s", line) == 1) { + int line_port; + while(fscanf(fptr, "%s %d\\n", line, &line_port) == 2) { ip_count++; } @@ -284,7 +285,7 @@ class ModelGeneration: fptr = fopen(ip_filename, "a"); if (fptr) { - fprintf(fptr, "%s\\n", my_ip); + fprintf(fptr, "%s %d\\n", my_ip, sock_port); fclose(fptr); } else { perror("Client - cannot open Common_IP file "); -- cgit From 2177768160df1be0825b4964baabe0e3e41385fd Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 28 May 2020 22:26:48 +0530 Subject: Update outitf.c --- src/outitf.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index 9a656c1..c4cbfe4 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -135,7 +135,7 @@ static void close_server(void) { printf("\nIPaddr - %s portno - %d", IPaddr_file, PORT_file); int sock = 0; struct sockaddr_in serv_addr; - char *hello = "CLOSE_FROM_NGSPICE"; + char *message = "CLOSE_FROM_NGSPICE"; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); @@ -149,7 +149,7 @@ static void close_server(void) { printf("\nConnection Failed \n"); } - send(sock , hello , strlen(hello) , 0 ); + send(sock , message , strlen(message) , 0 ); close(sock); } } -- cgit From 4618b501f3194dd148d0ad255670e4ae436860a8 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 28 May 2020 22:28:40 +0530 Subject: to iterate all the IPs and ports and send close message to all the ghdlserver --- src/outitf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index c4cbfe4..c015c04 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -147,7 +147,7 @@ static void close_server(void) if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { - printf("\nConnection Failed \n"); + printf("\nConnection Failed\n"); } send(sock , message , strlen(message) , 0 ); close(sock); -- cgit From ab1642936c210977eea25f6b57e208ecae3f26ef Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Fri, 29 May 2020 20:09:38 +0530 Subject: removed reading of newline character --- src/model_generation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/model_generation.py b/src/model_generation.py index dcb0788..eecd716 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -267,9 +267,9 @@ class ModelGeneration: fptr = fopen(ip_filename, "r"); if (fptr) { - char line[20]; - int line_port; - while(fscanf(fptr, "%s %d\\n", line, &line_port) == 2) { + char line_ip[20]; + int line_port; + while(fscanf(fptr, "%s %d", line_ip, &line_port) == 2) { ip_count++; } -- cgit From dfe61a0fb01b725478720bfd71aa2a456a3b36dd Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Fri, 29 May 2020 21:03:41 +0530 Subject: removed pid comments and related library, added credits --- src/ghdlserver/ghdlserver.c | 54 +++++++++++++++------------------------------ 1 file changed, 18 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/ghdlserver/ghdlserver.c b/src/ghdlserver/ghdlserver.c index d324e7b..1b1e706 100644 --- a/src/ghdlserver/ghdlserver.c +++ b/src/ghdlserver/ghdlserver.c @@ -1,38 +1,21 @@ -/********************************************************************************** - * FOSSEE, IIT-Bombay - ********************************************************************************** +/************************************************************************************ + * eSim Team, FOSSEE, IIT-Bombay + ************************************************************************************ + * 28.May.2020 - Bladen Martin - Termination of testbench: Replaced Process ID + * mechanism with socket connection from client + * receiving the special close message + ************************************************************************************ + ************************************************************************************ * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking - * - Close previous used socket to prevent from - * generating too many socket descriptors - * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options - * 26.Sept.2019 - Rahul Paknikar - Added reading of IP from a file to - * support multiple digital models - * - On exit, the test bench removes the - * NGHDL_COMMON_IP_ file, shared by all - * nghdl digital models and is stored in /tmp - * directory. It tracks the used IPs for existing - * digital models in current simulation. - * - Writes PID file in append mode. + * - Close previous used socket to prevent from + * generating too many socket descriptors + * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for * a given event. - * - Removed bug to terminate multiple testbench - * instances in ngpsice windows. - ********************************************************************************** - ********************************************************************************** - * 24.Mar.2017 - Raj Mohan - Added signal handler for SIGUSR1, to handle an - * orphan test bench process. - * The test bench will now create a PID file in - * /tmp directory with the name - * NGHDL___ - * This file contains the PID of the test bench . - * On exit, the test bench removes this file. - * The SIGUSR1 signal serves the same purpose as the - * "End" signal. - * - Added syslog interface for logging. + ************************************************************************************ + ************************************************************************************ + * 24.Mar.2017 - Raj Mohan - Added syslog interface for logging. * - Enabled SO_REUSEADDR socket option. - * - Added the following functions: - * o create_pid_file() - * o get_ngspice_pid() * 22.Feb.2017 - Raj Mohan - Implemented a kludge to fix a problem in the * test bench VHDL code. * - Changed sleep() to nanosleep(). @@ -40,7 +23,7 @@ * Added the following functions: * o curtim() * o print_hash_table() - *********************************************************************************/ + ***********************************************************************************/ #include #include "ghdlserver.h" @@ -60,7 +43,6 @@ #include #include #include -#include #include #define _XOPEN_SOURCE 500 @@ -240,13 +222,13 @@ static void receive_string(int sock_id, char* buffer) nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); if (nbytes <= 0) { - perror("receive_string() - READ FAILURE "); + perror("receive_string() - READ FAILURE "); exit(1); } - //28.May.2020 - BM - Added method to close server by NGSPICE after simulation + // 28.May.2020 - BM - Added method to close server by Ngspice after simulation char *exitstr = "CLOSE_FROM_NGSPICE"; - if (strcmp(buffer, exitstr)==0) + if (strcmp(buffer, exitstr) == 0) { Vhpi_Exit(0); } -- cgit From cb798c842a17fa58520e6f0184b165728b41c5d4 Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Fri, 29 May 2020 21:05:34 +0530 Subject: multiple retries for closing the server --- src/outitf.c | 140 ++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 82 insertions(+), 58 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index c015c04..9f1a851 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -3,17 +3,6 @@ Copyright 1990 Regents of the University of California. All rights reserved. Author: 1988 Wayne A. Christopher, U. C. Berkeley CAD Group Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski **********/ -/************************************************************************** - * 10.Mar.2017 - RM - Added a dirty fix to handle orphan FOSSEE test bench - * processes. The following static functions were added in the process: - * o nghdl_orphan_tb() - * o nghdl_tb_SIGUSR1() - **************************************************************************/ -/************************************************************************** - * 22.Oct.2019 - RP - Read all the PIDs and send kill signal to all those - * processes. Also, Remove the common file of used IPs and PIDs for this - * Ngspice's instance rather than depending on GHDLServer to do the same. - **************************************************************************/ /* * This module replaces the old "writedata" routines in nutmeg. * Unlike the writedata routines, the OUT routines are only called by @@ -21,6 +10,12 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski * of nutmeg doesn't deal with OUT at all. */ +/************************************************************************** + * 29.May.2020 - RP, BM - Read all the IPs and ports from NGHDL_COMMON_IP + * file from /tmp folder. It connects to each of the ghdlserver and sends + * CLOSE_FROM_NGSPICE message to terminate themselves + **************************************************************************/ + #include "ngspice/ngspice.h" #include "ngspice/cpdefs.h" #include "ngspice/ftedefs.h" @@ -34,7 +29,6 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include "circuits.h" #include "outitf.h" #include "variable.h" -#include #include "ngspice/cktdefs.h" #include "ngspice/inpdefs.h" #include "breakp2.h" @@ -43,18 +37,19 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include "../misc/misc_time.h" /* 10.Mar.2917 - RM - Added the following #include */ -#include +#include #include #include #include #include #include -// 27.May.2020 - BM - Added the following #include + +/* 27.May.2020 - BM - Added the following #include */ #include #include #include #include -#include + extern char *spice_analysis_get_name(int index); extern char *spice_analysis_get_description(int index); @@ -102,7 +97,7 @@ int fixme_onoise_type = SV_NOTYPE; int fixme_inoise_type = SV_NOTYPE; -#define DOUBLE_PRECISION 15 +#define DOUBLE_PRECISION 15 static clock_t lastclock, currclock; @@ -119,40 +114,75 @@ static bool savenone = FALSE; #endif -//28.May.2020 - BM - Closing the GHDL server after simulation is over - -static void close_server(void) +/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ +static void close_server() { FILE *fptr; char ip_filename[48]; sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - if (fptr) - { - char IPaddr_file[20]; - int PORT_file; - while(fscanf(fptr, "%s %d\n", IPaddr_file, &PORT_file) == 2) - { printf("\nIPaddr - %s portno - %d", IPaddr_file, PORT_file); - int sock = 0; - struct sockaddr_in serv_addr; - char *message = "CLOSE_FROM_NGSPICE"; - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - printf("\n Socket creation error \n"); - } - - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(PORT_file); - serv_addr.sin_addr.s_addr = inet_addr(IPaddr_file); + fptr = fopen(ip_filename, "r"); + + if(fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; - if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - printf("\nConnection Failed\n"); - } - send(sock , message , strlen(message) , 0 ); - close(sock); - } - } + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + /* send close message to the server */ + send(sock, message, strlen(message), 0); + close(sock); + } + } + remove(ip_filename); } @@ -1083,15 +1113,13 @@ fileEndPoint(FILE *fp, bool bin) static void fileEnd(runDesc *run) { - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are + /* 28.May.2020 - RP, BM - Check if any orphan test benches are running. If any are * found, force them to exit. */ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - /* 28.MaY.2020 - BM */ - close_server; - /* End 28.MaY.2020 */ + /* 28.May.2020 - BM */ + close_server(); + /* End 28.May.2020 */ if (run->fp != stdout) { @@ -1246,13 +1274,9 @@ plotAddComplexValue(dataDesc *desc, IFcomplex value) static void plotEnd(runDesc *run) { - /* 10.Mar.2017 - RM */ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - - /* 28.MaY.2020 - BM */ - close_server; - /* End 28.MaY.2020 */ + /* 28.May.2020 - BM, RP */ + close_server(); + /* End 28.May.2020 */ fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); -- cgit From b575711c0fb1b5c202382e489d48df0861a3a8ea Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Sat, 6 Jun 2020 10:29:37 +0530 Subject: Added patch for Windows, Code made multi-platform(linux & Windows) --- src/outitf.c | 2817 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 1521 insertions(+), 1296 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index c015c04..45bbe23 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -22,12 +22,15 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski */ #include "ngspice/ngspice.h" +#ifdef _WIN32 + #undef BOOLEAN //05.Jue.2020 - BM - Undefine BOOLEAN due to clashing definition in WIndows +#endif #include "ngspice/cpdefs.h" #include "ngspice/ftedefs.h" #include "ngspice/dvec.h" #include "ngspice/plot.h" #include "ngspice/sim.h" -#include "ngspice/inpdefs.h" /* for INPtables */ +#include "ngspice/inpdefs.h" /* for INPtables */ #include "ngspice/ifsim.h" #include "ngspice/jobdefs.h" #include "ngspice/iferrmsg.h" @@ -49,17 +52,24 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include #include #include -// 27.May.2020 - BM - Added the following #include -#include -#include -#include -#include -#include + +//05.June.2020 - BM - Added follwing includes for Windows +#ifdef _WIN32 + #include + #include +#endif + +/* 27.May.2020 - BM - Added the following #include */ +#ifdef __linux__ + #include + #include + #include + #include +#endif extern char *spice_analysis_get_name(int index); extern char *spice_analysis_get_description(int index); - static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp); @@ -101,9 +111,7 @@ extern bool orflag; int fixme_onoise_type = SV_NOTYPE; int fixme_inoise_type = SV_NOTYPE; - -#define DOUBLE_PRECISION 15 - +#define DOUBLE_PRECISION 15 static clock_t lastclock, currclock; static double *rowbuf; @@ -118,1412 +126,1786 @@ static double *valueold, *valuenew; static bool savenone = FALSE; #endif +/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ -//28.May.2020 - BM - Closing the GHDL server after simulation is over - -static void close_server(void) +#ifdef __linux__ +static void close_server() { FILE *fptr; char ip_filename[48]; sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - if (fptr) - { - char IPaddr_file[20]; - int PORT_file; - while(fscanf(fptr, "%s %d\n", IPaddr_file, &PORT_file) == 2) - { printf("\nIPaddr - %s portno - %d", IPaddr_file, PORT_file); - int sock = 0; - struct sockaddr_in serv_addr; - char *message = "CLOSE_FROM_NGSPICE"; - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - printf("\n Socket creation error \n"); - } - - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(PORT_file); - serv_addr.sin_addr.s_addr = inet_addr(IPaddr_file); + fptr = fopen(ip_filename, "r"); + + if(fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; - if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - printf("\nConnection Failed\n"); - } - send(sock , message , strlen(message) , 0 ); - close(sock); - } - } + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + /* send close message to the server */ + send(sock, message, strlen(message)+1, 0); + close(sock); + } + } + remove(ip_filename); } +#endif +#ifdef _WIN32 +static void close_server() +{ + WSADATA WSAData; + SOCKADDR_IN addr; + WSAStartup(MAKEWORD(2, 2), &WSAData); + FILE *fptr; + char ip_filename[48]; + sprintf(ip_filename, "C:\Windows\Temp\NGHDL_COMMON_IP_%d.txt", getpid()); + fptr = fopen(ip_filename, "r"); + if(fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } -// The two "begin plot" routines share all their internals... + if (skip_flag) + continue; + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + if (skip_flag) + continue; + /* send close message to the server */ + send(sock, message, strlen(message)+1, 0); + closesocket(sock); + WSACleanup(); + } + } + remove(ip_filename); +} +#endif -int -OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) -{ - char *name; - if (ft_curckt->ci_ckt == circuitPtr) - name = ft_curckt->ci_name; - else - name = "circuit name"; + /* The two "begin plot" routines share all their internals... */ - return (beginPlot(analysisPtr, circuitPtr, name, - analName, refName, refType, numNames, - dataNames, dataType, FALSE, - plotPtr)); -} + int OUTpBeginPlot(CKTcircuit * circuitPtr, JOB * analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) + { + char *name; + if (ft_curckt->ci_ckt == circuitPtr) + name = ft_curckt->ci_name; + else + name = "circuit name"; -int -OUTwBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) -{ + return (beginPlot(analysisPtr, circuitPtr, name, + analName, refName, refType, numNames, + dataNames, dataType, FALSE, + plotPtr)); + } - return (beginPlot(analysisPtr, circuitPtr, "circuit name", - analName, refName, refType, numNames, - dataNames, dataType, TRUE, - plotPtr)); -} + int OUTwBeginPlot(CKTcircuit * circuitPtr, JOB * analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) + { + return (beginPlot(analysisPtr, circuitPtr, "circuit name", + analName, refName, refType, numNames, + dataNames, dataType, TRUE, + plotPtr)); + } -static int -beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) -{ - runDesc *run; - struct save_info *saves; - bool *savesused = NULL; - int numsaves; - int i, j, depind = 0; - char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; - char *ch, tmpname[BSIZE_SP]; - bool saveall = TRUE; - bool savealli = FALSE; - char *an_name; - int initmem; - /*to resume a run saj + static int + beginPlot(JOB * analysisPtr, CKTcircuit * circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) + { + runDesc *run; + struct save_info *saves; + bool *savesused = NULL; + int numsaves; + int i, j, depind = 0; + char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; + char *ch, tmpname[BSIZE_SP]; + bool saveall = TRUE; + bool savealli = FALSE; + char *an_name; + int initmem; + /*to resume a run saj *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) */ - if (dataType == 666 && numNames == 666) { - run = *runp; - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); - - } else { - /*end saj*/ + if (dataType == 666 && numNames == 666) + { + run = *runp; + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); + } + else + { + /*end saj*/ - /* Check to see if we want to print informational data. */ - if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) - fprintf(cp_err, "(debug printing enabled)\n"); + /* Check to see if we want to print informational data. */ + if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) + fprintf(cp_err, "(debug printing enabled)\n"); - /* Check to see if we want to save only interpolated data. */ - if (cp_getvar("interp", CP_BOOL, NULL, 0)) { - interpolated = TRUE; - fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); - } + /* Check to see if we want to save only interpolated data. */ + if (cp_getvar("interp", CP_BOOL, NULL, 0)) + { + interpolated = TRUE; + fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); + } - *runp = run = TMALLOC(struct runDesc, 1); + *runp = run = TMALLOC(struct runDesc, 1); - /* First fill in some general information. */ - run->analysis = analysisPtr; - run->circuit = circuitPtr; - run->name = copy(cktName); - run->type = copy(analName); - run->windowed = windowed; - run->numData = 0; + /* First fill in some general information. */ + run->analysis = analysisPtr; + run->circuit = circuitPtr; + run->name = copy(cktName); + run->type = copy(analName); + run->windowed = windowed; + run->numData = 0; - an_name = spice_analysis_get_name(analysisPtr->JOBtype); - ft_curckt->ci_last_an = an_name; + an_name = spice_analysis_get_name(analysisPtr->JOBtype); + ft_curckt->ci_last_an = an_name; - /* Now let's see which of these things we need. First toss in the + /* Now let's see which of these things we need. First toss in the * reference vector. Then toss in anything that getSaves() tells * us to save that we can find in the name list. Finally unpack * the remaining saves into parameters. */ - numsaves = ft_getSaves(&saves); - if (numsaves) { - savesused = TMALLOC(bool, numsaves); - saveall = FALSE; - for (i = 0; i < numsaves; i++) { - if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) { - /* ignore this one this time around */ - savesused[i] = TRUE; - continue; - } + numsaves = ft_getSaves(&saves); + if (numsaves) + { + savesused = TMALLOC(bool, numsaves); + saveall = FALSE; + for (i = 0; i < numsaves; i++) + { + if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) + { + /* ignore this one this time around */ + savesused[i] = TRUE; + continue; + } - /* Check for ".save all" and new synonym ".save allv" */ + /* Check for ".save all" and new synonym ".save allv" */ - if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) { - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } + if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) + { + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } - /* And now for the new ".save alli" option */ + /* And now for the new ".save alli" option */ - if (cieq(saves[i].name, "alli")) { - savealli = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } + if (cieq(saves[i].name, "alli")) + { + savealli = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } #ifdef SHARED_MODULE - /* this may happen if shared ngspice*/ - if (cieq(saves[i].name, "none")) { - savenone = TRUE; - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } + /* this may happen if shared ngspice*/ + if (cieq(saves[i].name, "none")) + { + savenone = TRUE; + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } #endif - } - } - - if (numsaves && !saveall) - initmem = numsaves; - else - initmem = numNames; - - /* Pass 0. */ - if (refName) { - addDataDesc(run, refName, refType, -1, initmem); - for (i = 0; i < numsaves; i++) - if (!savesused[i] && name_eq(saves[i].name, refName)) { - savesused[i] = TRUE; - saves[i].used = 1; } - } else { - run->refIndex = -1; - } + } + if (numsaves && !saveall) + initmem = numsaves; + else + initmem = numNames; - /* Pass 1. */ - if (numsaves && !saveall) { - for (i = 0; i < numsaves; i++) - if (!savesused[i]) - for (j = 0; j < numNames; j++) - if (name_eq(saves[i].name, dataNames[j])) { - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - break; - } - } else { - for (i = 0; i < numNames; i++) - if (!refName || !name_eq(dataNames[i], refName)) - /* Save the node as long as it's an internal device node */ - if (!strstr(dataNames[i], "#internal") && - !strstr(dataNames[i], "#source") && - !strstr(dataNames[i], "#drain") && - !strstr(dataNames[i], "#collector") && - !strstr(dataNames[i], "#emitter") && - !strstr(dataNames[i], "#base")) + /* Pass 0. */ + if (refName) + { + addDataDesc(run, refName, refType, -1, initmem); + for (i = 0; i < numsaves; i++) + if (!savesused[i] && name_eq(saves[i].name, refName)) { - addDataDesc(run, dataNames[i], dataType, i, initmem); + savesused[i] = TRUE; + saves[i].used = 1; } - } + } + else + { + run->refIndex = -1; + } + + /* Pass 1. */ + if (numsaves && !saveall) + { + for (i = 0; i < numsaves; i++) + if (!savesused[i]) + for (j = 0; j < numNames; j++) + if (name_eq(saves[i].name, dataNames[j])) + { + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + break; + } + } + else + { + for (i = 0; i < numNames; i++) + if (!refName || !name_eq(dataNames[i], refName)) + /* Save the node as long as it's an internal device node */ + if (!strstr(dataNames[i], "#internal") && + !strstr(dataNames[i], "#source") && + !strstr(dataNames[i], "#drain") && + !strstr(dataNames[i], "#collector") && + !strstr(dataNames[i], "#emitter") && + !strstr(dataNames[i], "#base")) + { + addDataDesc(run, dataNames[i], dataType, i, initmem); + } + } - /* Pass 1 and a bit. + /* Pass 1 and a bit. This is a new pass which searches for all the internal device nodes, and saves the terminal currents instead */ - if (savealli) { - depind = 0; - for (i = 0; i < numNames; i++) { - if (strstr(dataNames[i], "#internal") || - strstr(dataNames[i], "#source") || - strstr(dataNames[i], "#drain") || - strstr(dataNames[i], "#collector") || - strstr(dataNames[i], "#emitter") || - strstr(dataNames[i], "#base")) + if (savealli) + { + depind = 0; + for (i = 0; i < numNames; i++) { - tmpname[0] = '@'; - tmpname[1] = '\0'; - strncat(tmpname, dataNames[i], BSIZE_SP-1); - ch = strchr(tmpname, '#'); - - if (strstr(ch, "#collector")) { - strcpy(ch, "[ic]"); - } else if (strstr(ch, "#base")) { - strcpy(ch, "[ib]"); - } else if (strstr(ch, "#emitter")) { - strcpy(ch, "[ie]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[is]"); - } else if (strstr(ch, "#drain")) { - strcpy(ch, "[id]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ig]"); - } else if (strstr(ch, "#source")) { - strcpy(ch, "[is]"); + if (strstr(dataNames[i], "#internal") || + strstr(dataNames[i], "#source") || + strstr(dataNames[i], "#drain") || + strstr(dataNames[i], "#collector") || + strstr(dataNames[i], "#emitter") || + strstr(dataNames[i], "#base")) + { + tmpname[0] = '@'; + tmpname[1] = '\0'; + strncat(tmpname, dataNames[i], BSIZE_SP - 1); + ch = strchr(tmpname, '#'); + + if (strstr(ch, "#collector")) + { + strcpy(ch, "[ic]"); + } + else if (strstr(ch, "#base")) + { + strcpy(ch, "[ib]"); + } + else if (strstr(ch, "#emitter")) + { + strcpy(ch, "[ie]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[is]"); + } + else if (strstr(ch, "#drain")) + { + strcpy(ch, "[id]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ig]"); + } + else if (strstr(ch, "#source")) + { + strcpy(ch, "[is]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ib]"); + } + else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) + { + strcpy(ch, "[id]"); + } + else + { + fprintf(cp_err, + "Debug: could output current for %s\n", tmpname); + continue; + } if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ib]"); - } else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) { - strcpy(ch, "[id]"); - } else { - fprintf(cp_err, - "Debug: could output current for %s\n", tmpname); - continue; - } - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) { - if (*depbuf) { - fprintf(stderr, - "Warning : unexpected dependent variable on %s\n", tmpname); - } else { - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + { + if (*depbuf) + { + fprintf(stderr, + "Warning : unexpected dependent variable on %s\n", tmpname); + } + else + { + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + } } } } } - } - - /* Pass 2. */ - for (i = 0; i < numsaves; i++) { + /* Pass 2. */ + for (i = 0; i < numsaves; i++) + { - if (savesused[i]) - continue; + if (savesused[i]) + continue; - if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) { - if (saves[i].analysis) - fprintf(cp_err, "Warning: can't parse '%s': ignored\n", - saves[i].name); - continue; - } + if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) + { + if (saves[i].analysis) + fprintf(cp_err, "Warning: can't parse '%s': ignored\n", + saves[i].name); + continue; + } - /* Now, if there's a dep variable, do we already have it? */ - if (*depbuf) { - for (j = 0; j < run->numData; j++) - if (name_eq(depbuf, run->data[j].name)) - break; - if (j == run->numData) { - /* Better add it. */ - for (j = 0; j < numNames; j++) - if (name_eq(depbuf, dataNames[j])) + /* Now, if there's a dep variable, do we already have it? */ + if (*depbuf) + { + for (j = 0; j < run->numData; j++) + if (name_eq(depbuf, run->data[j].name)) break; - if (j == numNames) { - fprintf(cp_err, - "Warning: can't find '%s': value '%s' ignored\n", - depbuf, saves[i].name); - continue; + if (j == run->numData) + { + /* Better add it. */ + for (j = 0; j < numNames; j++) + if (name_eq(depbuf, dataNames[j])) + break; + if (j == numNames) + { + fprintf(cp_err, + "Warning: can't find '%s': value '%s' ignored\n", + depbuf, saves[i].name); + continue; + } + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + depind = j; + } + else + { + depind = run->data[j].outIndex; } - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - depind = j; - } else { - depind = run->data[j].outIndex; } - } - addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); - } + addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); + } - if (numsaves) { - for (i = 0; i < numsaves; i++) { - tfree(saves[i].analysis); - tfree(saves[i].name); + if (numsaves) + { + for (i = 0; i < numsaves; i++) + { + tfree(saves[i].analysis); + tfree(saves[i].name); + } + tfree(saves); + tfree(savesused); } - tfree(saves); - tfree(savesused); - } - if (numNames && - ((run->numData == 1 && run->refIndex != -1) || - (run->numData == 0 && run->refIndex == -1))) - { - fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", - spice_analysis_get_description(analysisPtr->JOBtype)); - return E_NOTFOUND; - } + if (numNames && + ((run->numData == 1 && run->refIndex != -1) || + (run->numData == 0 && run->refIndex == -1))) + { + fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", + spice_analysis_get_description(analysisPtr->JOBtype)); + return E_NOTFOUND; + } - /* Now that we have our own data structures built up, let's see what + /* Now that we have our own data structures built up, let's see what * nutmeg wants us to do. */ - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); - if (run->writeOut) { - fileInit(run); - } else { - plotInit(run); - if (refName) - run->runPlot->pl_ndims = 1; + if (run->writeOut) + { + fileInit(run); + } + else + { + plotInit(run); + if (refName) + run->runPlot->pl_ndims = 1; + } } - } - /* define storage for old and new data, to allow interpolation */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) { - valueold = TMALLOC(double, run->numData); - for (i = 0; i < run->numData; i++) - valueold[i] = 0.0; - valuenew = TMALLOC(double, run->numData); - } + /* define storage for old and new data, to allow interpolation */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) + { + valueold = TMALLOC(double, run->numData); + for (i = 0; i < run->numData; i++) + valueold[i] = 0.0; + valuenew = TMALLOC(double, run->numData); + } - /*Start BLT, initilises the blt vectors saj*/ + /*Start BLT, initilises the blt vectors saj*/ #ifdef TCL_MODULE - blt_init(run); + blt_init(run); #elif defined SHARED_MODULE - sh_vecinit(run); + sh_vecinit(run); #endif - return (OK); -} + return (OK); + } -/* Initialze memory for the list of all vectors in the current plot. + /* Initialze memory for the list of all vectors in the current plot. Add a standard vector to this plot */ -static int -addDataDesc(runDesc *run, char *name, int type, int ind, int meminit) -{ - dataDesc *data; - - /* initialize memory (for all vectors or given by 'save') */ - if (!run->numData) { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - /* If there is need for more memory */ - else if (run->numData == run->maxData) { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); - } + static int + addDataDesc(runDesc * run, char *name, int type, int ind, int meminit) + { + dataDesc *data; - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); + /* initialize memory (for all vectors or given by 'save') */ + if (!run->numData) + { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + /* If there is need for more memory */ + else if (run->numData == run->maxData) + { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } - data->name = copy(name); - data->type = type; - data->gtype = GRID_LIN; - data->regular = TRUE; - data->outIndex = ind; + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); - /* It's the reference vector. */ - if (ind == -1) - run->refIndex = run->numData; + data->name = copy(name); + data->type = type; + data->gtype = GRID_LIN; + data->regular = TRUE; + data->outIndex = ind; - run->numData++; + /* It's the reference vector. */ + if (ind == -1) + run->refIndex = run->numData; - return (OK); -} + run->numData++; -/* Initialze memory for the list of all vectors in the current plot. - Add a special vector (e.g. @q1[ib]) to this plot */ -static int -addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit) -{ - dataDesc *data; - char *unique, *freeunique; /* unique char * from back-end */ - int ret; - - if (!run->numData) { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - else if (run->numData == run->maxData) { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); + return (OK); } - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); + /* Initialze memory for the list of all vectors in the current plot. + Add a special vector (e.g. @q1[ib]) to this plot */ + static int + addSpecialDesc(runDesc * run, char *name, char *devname, char *param, int depind, int meminit) + { + dataDesc *data; + char *unique, *freeunique; /* unique char * from back-end */ + int ret; + + if (!run->numData) + { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + else if (run->numData == run->maxData) + { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } - data->name = copy(name); + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); - freeunique = unique = copy(devname); + data->name = copy(name); - /* unique will be overridden, if it already exists */ - ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); - data->specName = unique; + freeunique = unique = copy(devname); - if (ret == E_EXISTS) - tfree(freeunique); + /* unique will be overridden, if it already exists */ + ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); + data->specName = unique; - data->specParamName = copy(param); + if (ret == E_EXISTS) + tfree(freeunique); - data->specIndex = depind; - data->specType = -1; - data->specFast = NULL; - data->regular = FALSE; + data->specParamName = copy(param); - run->numData++; + data->specIndex = depind; + data->specType = -1; + data->specFast = NULL; + data->regular = FALSE; - return (OK); -} + run->numData++; + return (OK); + } -static void -OUTpD_memory(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i, n = run->numData; + static void + OUTpD_memory(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) + { + int i, n = run->numData; - for (i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { - dataDesc *d; + dataDesc *d; #ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); + /*Locks the blt vector to stop access*/ + blt_lockvec(i); #endif - d = &run->data[i]; - - if (d->outIndex == -1) { - if (d->type == IF_REAL) - plotAddRealValue(d, refValue->rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, refValue->cValue); - } else if (d->regular) { - if (d->type == IF_REAL) - plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); - } else { - IFvalue val; - - /* should pre-check instance */ - if (!getSpecial(d, run, &val)) - continue; + d = &run->data[i]; - if (d->type == IF_REAL) - plotAddRealValue(d, val.rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, val.cValue); + if (d->outIndex == -1) + { + if (d->type == IF_REAL) + plotAddRealValue(d, refValue->rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, refValue->cValue); + } + else if (d->regular) + { + if (d->type == IF_REAL) + plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); + } else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } + { + IFvalue val; + + /* should pre-check instance */ + if (!getSpecial(d, run, &val)) + continue; + + if (d->type == IF_REAL) + plotAddRealValue(d, val.rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } #ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, d->vec); + /*relinks and unlocks vector*/ + blt_relink(i, d->vec); #endif - + } } -} + int OUTpData(runDesc * plotPtr, IFvalue * refValue, IFvalue * valuePtr) + { + runDesc *run = plotPtr; // FIXME + int i; -int -OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) -{ - runDesc *run = plotPtr; // FIXME - int i; - - run->pointCount++; + run->pointCount++; #ifdef TCL_MODULE - steps_completed = run->pointCount; + steps_completed = run->pointCount; #endif - /* interpolated batch mode output to file in transient analysis */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) { - InterpFileAdd(run, refValue, valuePtr); - return (OK); - } - /* interpolated interactive or control mode output to plot in transient analysis */ - else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) { - InterpPlotAdd(run, refValue, valuePtr); - return (OK); - } - /* standard batch mode output to file */ - else if (run->writeOut) { + /* interpolated batch mode output to file in transient analysis */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) + { + InterpFileAdd(run, refValue, valuePtr); + return (OK); + } + /* interpolated interactive or control mode output to plot in transient analysis */ + else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) + { + InterpPlotAdd(run, refValue, valuePtr); + return (OK); + } + /* standard batch mode output to file */ + else if (run->writeOut) + { - if (run->pointCount == 1) - fileInit_pass2(run); + if (run->pointCount == 1) + fileInit_pass2(run); - fileStartPoint(run->fp, run->binary, run->pointCount); + fileStartPoint(run->fp, run->binary, run->pointCount); - if (run->refIndex != -1) { - if (run->isComplex) { - fileAddComplexValue(run->fp, run->binary, refValue->cValue); + if (run->refIndex != -1) + { + if (run->isComplex) + { + fileAddComplexValue(run->fp, run->binary, refValue->cValue); - /* While we're looking at the reference value, print it to the screen + /* While we're looking at the reference value, print it to the screen every quarter of a second, to give some feedback without using too much CPU time */ #ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) { - currclock = clock(); - if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->cValue.real); - lastclock = currclock; + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->cValue.real); + lastclock = currclock; + } } - } #endif - } else { + } + else + { - /* And the same for a non-complex value */ + /* And the same for a non-complex value */ - fileAddRealValue(run->fp, run->binary, refValue->rValue); + fileAddRealValue(run->fp, run->binary, refValue->rValue); #ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) { - currclock = clock(); - if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } } - } #endif + } } - } - for (i = 0; i < run->numData; i++) { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; + for (i = 0; i < run->numData; i++) + { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; #ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); + blt_add(i, refValue ? refValue->rValue : NAN); #endif - if (run->data[i].regular) { - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, - valuePtr->v.vec.rVec [run->data[i].outIndex]); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, - valuePtr->v.vec.cVec [run->data[i].outIndex]); + if (run->data[i].regular) + { + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, + valuePtr->v.vec.rVec[run->data[i].outIndex]); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, + valuePtr->v.vec.cVec[run->data[i].outIndex]); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } else { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) { + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + { - /* If this is the first data point, print a warning for any unrecognized + /* If this is the first data point, print a warning for any unrecognized variables, since this has not already been checked */ - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); - if (run->isComplex) { - val.cValue.real = 0; - val.cValue.imag = 0; - fileAddComplexValue(run->fp, run->binary, val.cValue); - } else { - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); + if (run->isComplex) + { + val.cValue.real = 0; + val.cValue.imag = 0; + fileAddComplexValue(run->fp, run->binary, val.cValue); + } + else + { + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + } + + continue; } - continue; + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, val.rValue); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); } - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, val.rValue); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, val.cValue); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - #ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec [run->data[i].outIndex]); + blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); #endif + } - } - - fileEndPoint(run->fp, run->binary); + fileEndPoint(run->fp, run->binary); - /* Check that the write to disk completed successfully, otherwise abort */ + /* Check that the write to disk completed successfully, otherwise abort */ - if (ferror(run->fp)) { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; + if (ferror(run->fp)) + { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } } + else + { - } else { - - OUTpD_memory(run, refValue, valuePtr); + OUTpD_memory(run, refValue, valuePtr); - /* This is interactive mode. Update the screen with the reference + /* This is interactive mode. Update the screen with the reference variable just the same */ #ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) { - currclock = clock(); - if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { - if (run->isComplex) { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->cValue.real : NAN); - } else { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->rValue : NAN); - } - lastclock = currclock; - } - } + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + if (run->isComplex) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->cValue.real : NAN); + } + else + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->rValue : NAN); + } + lastclock = currclock; + } + } #endif - gr_iplot(run->runPlot); - } + gr_iplot(run->runPlot); + } - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; #ifdef TCL_MODULE - Tcl_ExecutePerLoop(); + Tcl_ExecutePerLoop(); #elif defined SHARED_MODULE - sh_ExecutePerLoop(); + sh_ExecutePerLoop(); #endif - return (OK); -} - - -int -OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) -{ - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(plotPtr); - - return (OK); -} - - -int -OUTwData(runDesc *plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) -{ - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(dataIndex); - NG_IGNORE(plotPtr); - - return (OK); -} - + return (OK); + } -int -OUTwEnd(runDesc *plotPtr) -{ - NG_IGNORE(plotPtr); + int OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) + { + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(plotPtr); - return (OK); -} + return (OK); + } + int OUTwData(runDesc * plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) + { + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(dataIndex); + NG_IGNORE(plotPtr); -int -OUTendPlot(runDesc *plotPtr) -{ - if (plotPtr->writeOut) { - fileEnd(plotPtr); - } else { - gr_end_iplot(); - plotEnd(plotPtr); + return (OK); } - tfree(valueold); - tfree(valuenew); + int OUTwEnd(runDesc * plotPtr) + { + NG_IGNORE(plotPtr); - freeRun(plotPtr); + return (OK); + } - return (OK); -} + int OUTendPlot(runDesc * plotPtr) + { + if (plotPtr->writeOut) + { + fileEnd(plotPtr); + } + else + { + gr_end_iplot(); + plotEnd(plotPtr); + } + tfree(valueold); + tfree(valuenew); -int -OUTbeginDomain(runDesc *plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) -{ - NG_IGNORE(outerRefValue); - NG_IGNORE(refType); - NG_IGNORE(refName); - NG_IGNORE(plotPtr); + freeRun(plotPtr); - return (OK); -} + return (OK); + } + int OUTbeginDomain(runDesc * plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) + { + NG_IGNORE(outerRefValue); + NG_IGNORE(refType); + NG_IGNORE(refName); + NG_IGNORE(plotPtr); -int -OUTendDomain(runDesc *plotPtr) -{ - NG_IGNORE(plotPtr); + return (OK); + } - return (OK); -} + int OUTendDomain(runDesc * plotPtr) + { + NG_IGNORE(plotPtr); + return (OK); + } -int -OUTattributes(runDesc *plotPtr, IFuid varName, int param, IFvalue *value) -{ - runDesc *run = plotPtr; // FIXME - GRIDTYPE type; + int OUTattributes(runDesc * plotPtr, IFuid varName, int param, IFvalue *value) + { + runDesc *run = plotPtr; // FIXME + GRIDTYPE type; - struct dvec *d; + struct dvec *d; - NG_IGNORE(value); + NG_IGNORE(value); - if (param == OUT_SCALE_LIN) - type = GRID_LIN; - else if (param == OUT_SCALE_LOG) - type = GRID_XLOG; - else - return E_UNSUPP; + if (param == OUT_SCALE_LIN) + type = GRID_LIN; + else if (param == OUT_SCALE_LOG) + type = GRID_XLOG; + else + return E_UNSUPP; - if (run->writeOut) { - if (varName) { - int i; - for (i = 0; i < run->numData; i++) - if (!strcmp(varName, run->data[i].name)) - run->data[i].gtype = type; - } else { - run->data[run->refIndex].gtype = type; + if (run->writeOut) + { + if (varName) + { + int i; + for (i = 0; i < run->numData; i++) + if (!strcmp(varName, run->data[i].name)) + run->data[i].gtype = type; + } + else + { + run->data[run->refIndex].gtype = type; + } } - } else { - if (varName) { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - if (!strcmp(varName, d->v_name)) - d->v_gridtype = type; - } else if (param == PLOT_COMB) { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - d->v_plottype = PLOT_COMB; - } else { - run->runPlot->pl_scale->v_gridtype = type; + else + { + if (varName) + { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + if (!strcmp(varName, d->v_name)) + d->v_gridtype = type; + } + else if (param == PLOT_COMB) + { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + d->v_plottype = PLOT_COMB; + } + else + { + run->runPlot->pl_scale->v_gridtype = type; + } } + + return (OK); } - return (OK); -} + /* The file writing routines. */ + static void + fileInit(runDesc * run) + { + char buf[513]; + int i; + size_t n; -/* The file writing routines. */ - -static void -fileInit(runDesc *run) -{ - char buf[513]; - int i; - size_t n; - - lastclock = clock(); - - /* This is a hack. */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - n = 0; - sprintf(buf, "Title: %s\n", run->name); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Date: %s\n", datestring()); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Plotname: %s\n", run->type); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Variables: %d\n", run->numData); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Points: "); - n += strlen(buf); - fputs(buf, run->fp); - - fflush(run->fp); /* Gotta do this for LATTICE. */ - if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) - run->pointPos = (long) n; - fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ - - /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ - fprintf(run->fp, "Variables:\n"); - - printf("No. of Data Columns : %d \n", run->numData); -} + lastclock = clock(); + /* This is a hack. */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; + + n = 0; + sprintf(buf, "Title: %s\n", run->name); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Date: %s\n", datestring()); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Plotname: %s\n", run->type); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Variables: %d\n", run->numData); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Points: "); + n += strlen(buf); + fputs(buf, run->fp); + + fflush(run->fp); /* Gotta do this for LATTICE. */ + if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) + run->pointPos = (long)n; + fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ + + /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ + fprintf(run->fp, "Variables:\n"); + + printf("No. of Data Columns : %d \n", run->numData); + } -static int -guess_type(const char *name) -{ - int type; - - if (substring("#branch", name)) - type = SV_CURRENT; - else if (cieq(name, "time")) - type = SV_TIME; - else if (cieq(name, "frequency")) - type = SV_FREQUENCY; - else if (ciprefix("inoise", name)) - type = fixme_inoise_type; - else if (ciprefix("onoise", name)) - type = fixme_onoise_type; - else if (cieq(name, "temp-sweep")) - type = SV_TEMP; - else if (cieq(name, "res-sweep")) - type = SV_RES; - else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ - type = SV_ADMITTANCE; - else if ((*name == '@') && substring("[c", name)) - type = SV_CAPACITANCE; - else if ((*name == '@') && substring("[i", name)) - type = SV_CURRENT; - else if ((*name == '@') && substring("[q", name)) - type = SV_CHARGE; - else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ - type = SV_POWER; - else - type = SV_VOLTAGE; - - return type; -} + static int + guess_type(const char *name) + { + int type; + + if (substring("#branch", name)) + type = SV_CURRENT; + else if (cieq(name, "time")) + type = SV_TIME; + else if (cieq(name, "frequency")) + type = SV_FREQUENCY; + else if (ciprefix("inoise", name)) + type = fixme_inoise_type; + else if (ciprefix("onoise", name)) + type = fixme_onoise_type; + else if (cieq(name, "temp-sweep")) + type = SV_TEMP; + else if (cieq(name, "res-sweep")) + type = SV_RES; + else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ + type = SV_ADMITTANCE; + else if ((*name == '@') && substring("[c", name)) + type = SV_CAPACITANCE; + else if ((*name == '@') && substring("[i", name)) + type = SV_CURRENT; + else if ((*name == '@') && substring("[q", name)) + type = SV_CHARGE; + else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ + type = SV_POWER; + else + type = SV_VOLTAGE; + return type; + } -static void -fileInit_pass2(runDesc *run) -{ - int i, type; + static void + fileInit_pass2(runDesc * run) + { + int i, type; - for (i = 0; i < run->numData; i++) { + for (i = 0; i < run->numData; i++) + { - char *name = run->data[i].name; + char *name = run->data[i].name; - type = guess_type(name); + type = guess_type(name); - if (type == SV_CURRENT) { - char *branch = strstr(name, "#branch"); - if (branch) - *branch = '\0'; - fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); - if (branch) - *branch = '#'; - } else if (type == SV_VOLTAGE) { - fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); - } else { - fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); - } + if (type == SV_CURRENT) + { + char *branch = strstr(name, "#branch"); + if (branch) + *branch = '\0'; + fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); + if (branch) + *branch = '#'; + } + else if (type == SV_VOLTAGE) + { + fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); + } + else + { + fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); + } - if (run->data[i].gtype == GRID_XLOG) - fprintf(run->fp, "\tgrid=3"); + if (run->data[i].gtype == GRID_XLOG) + fprintf(run->fp, "\tgrid=3"); - fprintf(run->fp, "\n"); - } + fprintf(run->fp, "\n"); + } - fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); - fflush(run->fp); + fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); + fflush(run->fp); - /* Allocate Row buffer */ + /* Allocate Row buffer */ - if (run->binary) { - rowbuflen = (size_t) (run->numData); - if (run->isComplex) - rowbuflen *= 2; - rowbuf = TMALLOC(double, rowbuflen); - } else { - rowbuflen = 0; - rowbuf = NULL; + if (run->binary) + { + rowbuflen = (size_t)(run->numData); + if (run->isComplex) + rowbuflen *= 2; + rowbuf = TMALLOC(double, rowbuflen); + } + else + { + rowbuflen = 0; + rowbuf = NULL; + } } -} - - -static void -fileStartPoint(FILE *fp, bool bin, int num) -{ - if (!bin) - fprintf(fp, "%d\t", num - 1); - /* reset buffer pointer to zero */ - - column = 0; -} + static void + fileStartPoint(FILE * fp, bool bin, int num) + { + if (!bin) + fprintf(fp, "%d\t", num - 1); + /* reset buffer pointer to zero */ -static void -fileAddRealValue(FILE *fp, bool bin, double value) -{ - if (bin) - rowbuf[column++] = value; - else - fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); -} - - -static void -fileAddComplexValue(FILE *fp, bool bin, IFcomplex value) -{ - if (bin) { - rowbuf[column++] = value.real; - rowbuf[column++] = value.imag; - } else { - fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, - DOUBLE_PRECISION, value.imag); + column = 0; } -} + static void + fileAddRealValue(FILE * fp, bool bin, double value) + { + if (bin) + rowbuf[column++] = value; + else + fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); + } -static void -fileEndPoint(FILE *fp, bool bin) -{ - /* write row buffer to file */ - /* otherwise the data has already been written */ + static void + fileAddComplexValue(FILE * fp, bool bin, IFcomplex value) + { + if (bin) + { + rowbuf[column++] = value.real; + rowbuf[column++] = value.imag; + } + else + { + fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, + DOUBLE_PRECISION, value.imag); + } + } - if (bin) - fwrite(rowbuf, sizeof(double), rowbuflen, fp); -} + static void + fileEndPoint(FILE * fp, bool bin) + { + /* write row buffer to file */ + /* otherwise the data has already been written */ + if (bin) + fwrite(rowbuf, sizeof(double), rowbuflen, fp); + } -/* Here's the hack... Run back and fill in the number of points. */ + /* Here's the hack... Run back and fill in the number of points. */ -static void -fileEnd(runDesc *run) -{ - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are - * found, force them to exit. - */ + static void + fileEnd(runDesc * run) + { + /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any arefound, force them to exit.*/ //nghdl_orphan_tb(); /* End 10.Mar.2017 */ /* 28.MaY.2020 - BM */ - close_server; + close_server(); /* End 28.MaY.2020 */ + if (run->fp != stdout) + { + long place = ftell(run->fp); + fseek(run->fp, run->pointPos, SEEK_SET); + fprintf(run->fp, "%d", run->pointCount); + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); + fseek(run->fp, place, SEEK_SET); + } + else + { + /* Yet another hack-around */ + fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); + } - if (run->fp != stdout) { - long place = ftell(run->fp); - fseek(run->fp, run->pointPos, SEEK_SET); - fprintf(run->fp, "%d", run->pointCount); - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); - fseek(run->fp, place, SEEK_SET); - } else { - /* Yet another hack-around */ - fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); - } - - fflush(run->fp); + fflush(run->fp); - tfree(rowbuf); -} + tfree(rowbuf); + } + /* The plot maintenance routines. */ + + static void + plotInit(runDesc * run) + { + struct plot *pl = plot_alloc(run->type); + struct dvec *v; + int i; + + pl->pl_title = copy(run->name); + pl->pl_name = copy(run->type); + pl->pl_date = copy(datestring()); + pl->pl_ndims = 0; + plot_new(pl); + plot_setcur(pl->pl_typename); + run->runPlot = pl; + + /* This is a hack. */ + /* if any of them complex, make them all complex */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; -/* The plot maintenance routines. */ - -static void -plotInit(runDesc *run) -{ - struct plot *pl = plot_alloc(run->type); - struct dvec *v; - int i; - - pl->pl_title = copy(run->name); - pl->pl_name = copy(run->type); - pl->pl_date = copy(datestring()); - pl->pl_ndims = 0; - plot_new(pl); - plot_setcur(pl->pl_typename); - run->runPlot = pl; - - /* This is a hack. */ - /* if any of them complex, make them all complex */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - for (i = 0; i < run->numData; i++) { - dataDesc *dd = &run->data[i]; - char *name; + for (i = 0; i < run->numData; i++) + { + dataDesc *dd = &run->data[i]; + char *name; - if (isdigit_c(dd->name[0])) - name = tprintf("V(%s)", dd->name); - else - name = copy(dd->name); + if (isdigit_c(dd->name[0])) + name = tprintf("V(%s)", dd->name); + else + name = copy(dd->name); - v = dvec_alloc(name, - guess_type(name), - run->isComplex - ? (VF_COMPLEX | VF_PERMANENT) - : (VF_REAL | VF_PERMANENT), - 0, NULL); + v = dvec_alloc(name, + guess_type(name), + run->isComplex + ? (VF_COMPLEX | VF_PERMANENT) + : (VF_REAL | VF_PERMANENT), + 0, NULL); - vec_new(v); - dd->vec = v; + vec_new(v); + dd->vec = v; + } } -} -/* prepare the vector length data for memory allocation + /* prepare the vector length data for memory allocation If new, and tran or pss, length is TSTOP / TSTEP plus some margin. If allocated length is exceeded, check progress. When > 20% then extrapolate memory needed, if less than 20% then just double the size. If not tran or pss, return fixed value (1024) of memory to be added. */ -static inline int -vlength2delta(int len) -{ + static inline int + vlength2delta(int len) + { #ifdef SHARED_MODULE - if (savenone) - /* We need just a vector length of 1 */ - return 1; + if (savenone) + /* We need just a vector length of 1 */ + return 1; #endif - /* TSTOP / TSTEP */ - int points = ft_curckt->ci_ckt->CKTtimeListSize; - /* transient and pss analysis (points > 0) upon start */ - if (len == 0 && points > 0) { - /* number of timesteps plus some overhead */ - return points + 100; - } - /* transient and pss if original estimate is exceeded */ - else if (points > 0) { - /* check where we are */ - double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; - /* return an estimate of the appropriate number of time points, if more than 20% of + /* TSTOP / TSTEP */ + int points = ft_curckt->ci_ckt->CKTtimeListSize; + /* transient and pss analysis (points > 0) upon start */ + if (len == 0 && points > 0) + { + /* number of timesteps plus some overhead */ + return points + 100; + } + /* transient and pss if original estimate is exceeded */ + else if (points > 0) + { + /* check where we are */ + double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; + /* return an estimate of the appropriate number of time points, if more than 20% of the anticipated total time has passed */ - if (timerel > 0.2) - return (int)(len / timerel) - len + 1; - /* If not, just double the available memory */ + if (timerel > 0.2) + return (int)(len / timerel) - len + 1; + /* If not, just double the available memory */ + else + return len; + } + /* other analysis types that do not set CKTtimeListSize */ else - return len; + return 1024; } - /* other analysis types that do not set CKTtimeListSize */ - else - return 1024; -} - -static void -plotAddRealValue(dataDesc *desc, double value) -{ - struct dvec *v = desc->vec; + static void + plotAddRealValue(dataDesc * desc, double value) + { + struct dvec *v = desc->vec; #ifdef SHARED_MODULE - if (savenone) - /* always save new data to same location */ - v->v_length = 0; + if (savenone) + /* always save new data to same location */ + v->v_length = 0; #endif - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - if (isreal(v)) { - v->v_realdata[v->v_length] = value; - } else { - /* a real parading as a VF_COMPLEX */ - v->v_compdata[v->v_length].cx_real = value; - v->v_compdata[v->v_length].cx_imag = 0.0; - } + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ -} + if (isreal(v)) + { + v->v_realdata[v->v_length] = value; + } + else + { + /* a real parading as a VF_COMPLEX */ + v->v_compdata[v->v_length].cx_real = value; + v->v_compdata[v->v_length].cx_imag = 0.0; + } + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ + } -static void -plotAddComplexValue(dataDesc *desc, IFcomplex value) -{ - struct dvec *v = desc->vec; + static void + plotAddComplexValue(dataDesc * desc, IFcomplex value) + { + struct dvec *v = desc->vec; #ifdef SHARED_MODULE - if (savenone) - v->v_length = 0; + if (savenone) + v->v_length = 0; #endif - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - v->v_compdata[v->v_length].cx_real = value.real; - v->v_compdata[v->v_length].cx_imag = value.imag; + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ -} + v->v_compdata[v->v_length].cx_real = value.real; + v->v_compdata[v->v_length].cx_imag = value.imag; + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ + } -static void -plotEnd(runDesc *run) -{ - /* 10.Mar.2017 - RM */ + static void + plotEnd(runDesc * run) + { + /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are*/ //nghdl_orphan_tb(); /* End 10.Mar.2017 */ /* 28.MaY.2020 - BM */ - close_server; + close_server(); /* End 28.MaY.2020 */ + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); + } - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); -} - - -/* ParseSpecial takes something of the form "@name[param,index]" and rips + /* ParseSpecial takes something of the form "@name[param,index]" and rips * out name, param, andstrchr. */ -static bool -parseSpecial(char *name, char *dev, char *param, char *ind) -{ - char *s; + static bool + parseSpecial(char *name, char *dev, char *param, char *ind) + { + char *s; - *dev = *param = *ind = '\0'; + *dev = *param = *ind = '\0'; - if (*name != '@') - return FALSE; - name++; + if (*name != '@') + return FALSE; + name++; - s = dev; - while (*name && (*name != '[')) - *s++ = *name++; - *s = '\0'; + s = dev; + while (*name && (*name != '[')) + *s++ = *name++; + *s = '\0'; - if (!*name) - return TRUE; - name++; + if (!*name) + return TRUE; + name++; - s = param; - while (*name && (*name != ',') && (*name != ']')) - *s++ = *name++; - *s = '\0'; + s = param; + while (*name && (*name != ',') && (*name != ']')) + *s++ = *name++; + *s = '\0'; - if (*name == ']') - return (!name[1] ? TRUE : FALSE); - else if (!*name) - return FALSE; - name++; + if (*name == ']') + return (!name[1] ? TRUE : FALSE); + else if (!*name) + return FALSE; + name++; - s = ind; - while (*name && (*name != ']')) - *s++ = *name++; - *s = '\0'; + s = ind; + while (*name && (*name != ']')) + *s++ = *name++; + *s = '\0'; - if (*name && !name[1]) - return TRUE; - else - return FALSE; -} + if (*name && !name[1]) + return TRUE; + else + return FALSE; + } + /* This routine must match two names with or without a V() around them. */ -/* This routine must match two names with or without a V() around them. */ + static bool + name_eq(char *n1, char *n2) + { + char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; -static bool -name_eq(char *n1, char *n2) -{ - char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; + if ((s = strchr(n1, '(')) != NULL) + { + strcpy(buf1, s); + if ((s = strchr(buf1, ')')) == NULL) + return FALSE; + *s = '\0'; + n1 = buf1; + } - if ((s = strchr(n1, '(')) != NULL) { - strcpy(buf1, s); - if ((s = strchr(buf1, ')')) == NULL) - return FALSE; - *s = '\0'; - n1 = buf1; - } + if ((s = strchr(n2, '(')) != NULL) + { + strcpy(buf2, s); + if ((s = strchr(buf2, ')')) == NULL) + return FALSE; + *s = '\0'; + n2 = buf2; + } - if ((s = strchr(n2, '(')) != NULL) { - strcpy(buf2, s); - if ((s = strchr(buf2, ')')) == NULL) - return FALSE; - *s = '\0'; - n2 = buf2; + return (strcmp(n1, n2) ? FALSE : TRUE); } - return (strcmp(n1, n2) ? FALSE : TRUE); -} + static bool + getSpecial(dataDesc * desc, runDesc * run, IFvalue * val) + { + IFvalue selector; + struct variable *vv; + selector.iValue = desc->specIndex; + if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, + desc->specName, &desc->specFast, ft_sim, &desc->type, + &selector) == OK) + { + desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ + return TRUE; + } -static bool -getSpecial(dataDesc *desc, runDesc *run, IFvalue *val) -{ - IFvalue selector; - struct variable *vv; - - selector.iValue = desc->specIndex; - if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, - desc->specName, &desc->specFast, ft_sim, &desc->type, - &selector) == OK) { - desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ - return TRUE; - } + if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) + { + /* skip @ sign */ + desc->type = IF_REAL; + if (vv->va_type == CP_REAL) + val->rValue = vv->va_real; + else if (vv->va_type == CP_NUM) + val->rValue = vv->va_num; + else if (vv->va_type == CP_BOOL) + val->rValue = (vv->va_bool ? 1.0 : 0.0); + else + return FALSE; /* not a real */ + tfree(vv); + return TRUE; + } - if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) { - /* skip @ sign */ - desc->type = IF_REAL; - if (vv->va_type == CP_REAL) - val->rValue = vv->va_real; - else if (vv->va_type == CP_NUM) - val->rValue = vv->va_num; - else if (vv->va_type == CP_BOOL) - val->rValue = (vv->va_bool ? 1.0 : 0.0); - else - return FALSE; /* not a real */ - tfree(vv); - return TRUE; + return FALSE; } - return FALSE; -} + static void + freeRun(runDesc * run) + { + int i; + for (i = 0; i < run->numData; i++) + { + tfree(run->data[i].name); + tfree(run->data[i].specParamName); + } -static void -freeRun(runDesc *run) -{ - int i; + tfree(run->data); + tfree(run->type); + tfree(run->name); - for (i = 0; i < run->numData; i++) { - tfree(run->data[i].name); - tfree(run->data[i].specParamName); + tfree(run); } - tfree(run->data); - tfree(run->type); - tfree(run->name); + int OUTstopnow(void) + { + if (ft_intrpt || shouldstop) + { + ft_intrpt = shouldstop = FALSE; + return (1); + } - tfree(run); -} + return (0); + } + /* Print out error messages. */ + + static struct mesg + { + char *string; + long flag; + } msgs[] = { + {"Warning", ERR_WARNING}, + {"Fatal error", ERR_FATAL}, + {"Panic", ERR_PANIC}, + {"Note", ERR_INFO}, + {NULL, 0}}; + + void OUTerror(int flags, char *format, IFuid *names) + { + struct mesg *m; + char buf[BSIZE_SP], *s, *bptr; + int nindex = 0; + + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; + + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); + + for (s = format, bptr = buf; *s; s++) + { + if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') + { + if (names[nindex]) + strcpy(bptr, names[nindex]); + else + strcpy(bptr, "(null)"); + bptr += strlen(bptr); + s++; + nindex++; + } + else + { + *bptr++ = *s; + } + } -int -OUTstopnow(void) -{ - if (ft_intrpt || shouldstop) { - ft_intrpt = shouldstop = FALSE; - return (1); + *bptr = '\0'; + fprintf(cp_err, "%s\n", buf); + fflush(cp_err); } - return (0); -} + void OUTerrorf(int flags, const char *format, ...) + { + struct mesg *m; + va_list args; + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; -/* Print out error messages. */ + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); -static struct mesg { - char *string; - long flag; -} msgs[] = { - { "Warning", ERR_WARNING } , - { "Fatal error", ERR_FATAL } , - { "Panic", ERR_PANIC } , - { "Note", ERR_INFO } , - { NULL, 0 } -}; + va_start(args, format); + vfprintf(cp_err, format, args); + fputc('\n', cp_err); -void -OUTerror(int flags, char *format, IFuid *names) -{ - struct mesg *m; - char buf[BSIZE_SP], *s, *bptr; - int nindex = 0; + fflush(cp_err); - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; + va_end(args); + } - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); + static int + InterpFileAdd(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) + { + int i; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; - for (s = format, bptr = buf; *s; s++) { - if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') { - if (names[nindex]) - strcpy(bptr, names[nindex]); + if (run->pointCount == 1) + { + fileInit_pass2(run); + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; + } + + if (run->refIndex != -1) + { + /* Save first time step */ + if (refValue->rValue == run->circuit->CKTinitTime) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); + interpolatenow = nodata = FALSE; + } + /* Save last time step */ + else if (refValue->rValue == run->circuit->CKTfinalTime) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); + interpolatenow = nodata = FALSE; + } + /* Save exact point */ + else if (refValue->rValue == timestep) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + interpolatenow = nodata = FALSE; + } + else if (refValue->rValue > timestep) + { + /* add the next time step value to the vector */ + fileStartPoint(run->fp, run->binary, run->pointCount); + timenew = refValue->rValue; + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + nodata = FALSE; + interpolatenow = TRUE; + } else - strcpy(bptr, "(null)"); - bptr += strlen(bptr); - s++; - nindex++; - } else { - *bptr++ = *s; + { + /* Do not save this step */ + run->pointCount--; + timeold = refValue->rValue; + nodata = TRUE; + interpolatenow = FALSE; + } +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif } - } - *bptr = '\0'; - fprintf(cp_err, "%s\n", buf); - fflush(cp_err); -} + for (i = 0; i < run->numData; i++) + { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; +#ifdef TCL_MODULE + blt_add(i, refValue ? refValue->rValue : NAN); +#endif -void -OUTerrorf(int flags, const char *format, ...) -{ - struct mesg *m; - va_list args; + if (run->data[i].regular) + { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + } + else + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + { - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; + /* If this is the first data point, print a warning for any unrecognized + variables, since this has not already been checked */ + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + continue; + } + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = val.rValue; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = val.rValue; + } - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); +#ifdef TCL_MODULE + blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); +#endif + } - va_start (args, format); + fileEndPoint(run->fp, run->binary); - vfprintf(cp_err, format, args); - fputc('\n', cp_err); + /* Check that the write to disk completed successfully, otherwise abort */ + if (ferror(run->fp)) + { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } - fflush(cp_err); + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; - va_end(args); -} +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + return (OK); + } + static int + InterpPlotAdd(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) + { + int i, iscale = -1; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; -static int -InterpFileAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; + if (run->pointCount == 1) + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - if (run->pointCount == 1) { - fileInit_pass2(run); - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - } + /* find the scale vector */ + for (i = 0; i < run->numData; i++) + if (run->data[i].outIndex == -1) + { + iscale = i; + break; + } + if (iscale == -1) + fprintf(stderr, "Error: no scale vector found\n"); + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(iscale); +#endif - if (run->refIndex != -1) { /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) { + if (refValue->rValue == run->circuit->CKTinitTime) + { timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); + plotAddRealValue(&run->data[iscale], refValue->rValue); interpolatenow = nodata = FALSE; } /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) { + else if (refValue->rValue == run->circuit->CKTfinalTime) + { timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); + plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); interpolatenow = nodata = FALSE; } /* Save exact point */ - else if (refValue->rValue == timestep) { + else if (refValue->rValue == timestep) + { timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, timestep); + plotAddRealValue(&run->data[iscale], timestep); timestep += run->circuit->CKTstep; interpolatenow = nodata = FALSE; } - else if (refValue->rValue > timestep) { + else if (refValue->rValue > timestep) + { /* add the next time step value to the vector */ - fileStartPoint(run->fp, run->binary, run->pointCount); timenew = refValue->rValue; - fileAddRealValue(run->fp, run->binary, timestep); + plotAddRealValue(&run->data[iscale], timestep); timestep += run->circuit->CKTstep; nodata = FALSE; interpolatenow = TRUE; } - else { + else + { /* Do not save this step */ run->pointCount--; timeold = refValue->rValue; nodata = TRUE; interpolatenow = FALSE; } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(iscale, (run->data[iscale]).vec); +#endif + #ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) { + if (!orflag && !ft_norefprint) + { currclock = clock(); - if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { fprintf(stderr, " Reference value : % 12.5e\r", refValue->rValue); lastclock = currclock; @@ -1531,239 +1913,82 @@ InterpFileAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) } #endif - } - - for (i = 0; i < run->numData; i++) { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; - -#ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); -#endif - - if (run->data[i].regular) { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - } else { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) { - - /* If this is the first data point, print a warning for any unrecognized - variables, since this has not already been checked */ - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); + for (i = 0; i < run->numData; i++) + { + if (i == iscale) continue; - } - if (!interpolatenow && !nodata) { - /* store the first or last value */ - valueold[i] = val.rValue; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = val.rValue; - } - -#ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec [run->data[i].outIndex]); -#endif - - } - - fileEndPoint(run->fp, run->binary); - - /* Check that the write to disk completed successfully, otherwise abort */ - if (ferror(run->fp)) { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; - } - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - return(OK); -} - -static int -InterpPlotAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i, iscale = -1; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; - - if (run->pointCount == 1) - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - - /* find the scale vector */ - for (i = 0; i < run->numData; i++) - if (run->data[i].outIndex == -1) { - iscale = i; - break; - } - if (iscale == -1) - fprintf(stderr, "Error: no scale vector found\n"); - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(iscale); -#endif - - /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], refValue->rValue); - interpolatenow = nodata = FALSE; - } - /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); - interpolatenow = nodata = FALSE; - } - /* Save exact point */ - else if (refValue->rValue == timestep) { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - interpolatenow = nodata = FALSE; - } - else if (refValue->rValue > timestep) { - /* add the next time step value to the vector */ - timenew = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - nodata = FALSE; - interpolatenow = TRUE; - } - else { - /* Do not save this step */ - run->pointCount--; - timeold = refValue->rValue; - nodata = TRUE; - interpolatenow = FALSE; - } #ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(iscale, (run->data[iscale]).vec); + /*Locks the blt vector to stop access*/ + blt_lockvec(i); #endif -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) { - currclock = clock(); - if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - - for (i = 0; i < run->numData; i++) { - if (i == iscale) - continue; - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); -#endif - - if (run->data[i].regular) { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, + if (run->data[i].regular) + { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; - } else { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - continue; - if (!interpolatenow && !nodata) { - /* store the first or last value */ - valueold[i] = val.rValue; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, + else + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + continue; + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = val.rValue; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, but do not store to file */ - valueold[i] = val.rValue; - } + valueold[i] = val.rValue; + } #ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, (run->data[i]).vec); + /*relinks and unlocks vector*/ + blt_relink(i, (run->data[i]).vec); #endif + } - } - - gr_iplot(run->runPlot); + gr_iplot(run->runPlot); - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; #ifdef TCL_MODULE - Tcl_ExecutePerLoop(); + Tcl_ExecutePerLoop(); #elif defined SHARED_MODULE - sh_ExecutePerLoop(); + sh_ExecutePerLoop(); #endif - return(OK); -} + return (OK); + } -- cgit From 2f5db6223551cce11d6712c02639d1f64c0f9635 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Mon, 8 Jun 2020 21:49:35 +0530 Subject: Code made OS-idependent Modified to work on Windows OS.--- src/model_generation.py | 2484 +++++++++++++++++++++++++++-------------------- src/ngspice_ghdl.py | 57 +- 2 files changed, 1493 insertions(+), 1048 deletions(-) (limited to 'src') diff --git a/src/model_generation.py b/src/model_generation.py index dcb0788..305ced8 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -1,1034 +1,1450 @@ -#!/usr/bin/python3 - -import re -import os - - -class ModelGeneration: - - def __init__(self, file): - - # Script starts from here - print("Arguement is : ", file) - self.fname = os.path.basename(file) - print("VHDL filename is : ", self.fname) - self.home = os.path.expanduser("~") - - # #### Creating connection_info.txt file from vhdl file #### # - read_vhdl = open(file, 'r') - vhdl_data = read_vhdl.readlines() - read_vhdl.close() - - start_flag = -1 # Used for scaning part of data - scan_data = [] - # p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() - - for item in vhdl_data: - if re.search('port', item, re.I): - start_flag = 1 - - elif re.search("end", item, re.I): - start_flag = 0 - - if start_flag == 1: - item = re.sub("port", " ", item, flags=re.I) - item = re.sub("\(", " ", item, flags=re.I) # noqa - item = re.sub("\)", " ", item, flags=re.I) # noqa - item = re.sub(";", " ", item, flags=re.I) - - scan_data.append(item.rstrip()) - scan_data = [_f for _f in scan_data if _f] - elif start_flag == 0: - break - - port_info = [] - self.port_vector_info = [] - - for item in scan_data: - print("Scan Data :", item) - if re.search("in", item, flags=re.I): - if re.search("std_logic_vector", item, flags=re.I): - temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) - elif re.search("std_logic", item, flags=re.I): - temp = re.compile(r"\s*std_logic\s*", flags=re.I) - else: - raise ValueError("Please check your vhdl " + - "code for datatype of input port") - elif re.search("out", item, flags=re.I): - if re.search("std_logic_vector", item, flags=re.I): - temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) - elif re.search("std_logic", item, flags=re.I): - temp = re.compile(r"\s*std_logic\s*", flags=re.I) - else: - raise ValueError("Please check your vhdl " + - "code for datatype of output port") - else: - raise ValueError( - "Please check the in/out direction of your port" - ) - - lhs = temp.split(item)[0] - rhs = temp.split(item)[1] - bit_info = re.compile(r"\s*downto\s*", flags=re.I).split(rhs)[0] - if bit_info: - port_info.append(lhs + ":" + str(int(bit_info) + int(1))) - self.port_vector_info.append(1) - else: - port_info.append(lhs + ":" + str(int(1))) - self.port_vector_info.append(0) - - print("Port Info :", port_info) - - # Open connection_info.txt file - con_ifo = open('connection_info.txt', 'w') - - for item in port_info: - word = item.split(':') - con_ifo.write( - word[0].strip() + ' ' + word[1].strip() + ' ' + word[2].strip() - ) - con_ifo.write("\n") - con_ifo.close() - - def readPortInfo(self): - - # ############## Reading connection/port information ############## # - - # Declaring input and output list - input_list = [] - output_list = [] - - # Reading connection_info.txt file for port infomation - read_file = open('connection_info.txt', 'r') - data = read_file.readlines() - read_file.close() - - # Extracting input and output port list from data - print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") - for line in data: - print(line) - if re.match(r'^\s*$', line): - pass - else: - in_items = re.findall( - "IN", line, re.MULTILINE | re.IGNORECASE - ) - out_items = re.findall( - "OUT", line, re.MULTILINE | re.IGNORECASE - ) - if in_items: - input_list.append(line.split()) - - if out_items: - output_list.append(line.split()) - - print("Inout List :", input_list) - print("Output list", output_list) - - self.input_port = [] - self.output_port = [] - - # creating list of input and output port with its weight - for input in input_list: - self.input_port.append(input[0]+":"+input[2]) - for output in output_list: - self.output_port.append(output[0]+":"+output[2]) - - print("Output Port List : ", self.output_port) - print("Input Port List : ", self.input_port) - - def createCfuncModFile(self): - - # ############## Creating content for cfunc.mod file ############## # - - print("Starting With cfunc.mod file") - cfunc = open('cfunc.mod', 'w') - print("Building content for cfunc.mod file") - - comment = '''/* This is cfunc.mod file auto generated by gen_con_info.py - Developed by Fahim, Rahul at IIT Bombay */\n - ''' - - header = ''' - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - ''' - - function_open = ( - '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') - - digital_state_output = [] - for item in self.output_port: - digital_state_output.append( - "Digital_State_t *_op_" + item.split(':')[0] + - ", *_op_" + item.split(':')[0] + "_old;" - ) - - var_section = ''' - // Declaring components of Client - FILE *log_client = NULL; - log_client=fopen("client.log","a"); - int socket_fd, bytes_recieved; - char send_data[1024]; - char recv_data[1024]; - char *key_iter; - struct hostent *host; - struct sockaddr_in server_addr; - int sock_port = 5000+PARAM(instance_id); - ''' - - temp_input_var = [] - for item in self.input_port: - temp_input_var.append( - "char temp_" + item.split(':')[0] + "[1024];" - ) - - # Start of INIT function - init_start_function = ''' - if(INIT) - { - /* Allocate storage for output ports ''' \ - '''and set the load for input ports */ - ''' - - cm_event_alloc = [] - cm_count_output = 0 - for item in self.output_port: - cm_event_alloc.append( - "cm_event_alloc(" + - str(cm_count_output) + "," + item.split(':')[1] + - "*sizeof(Digital_State_t));" - ) - cm_count_output = cm_count_output + 1 - - load_in_port = [] - for item in self.input_port: - load_in_port.append( - "for(Ii=0;Iih_addr); - bzero(&(server_addr.sin_zero),8); - - ''' - - connect_server = ''' - fprintf(log_client,"Client-Connecting to server \\n"); - - //Connecting to server - int try_limit=10; - while(try_limit>0) - { - if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ - '''sizeof(struct sockaddr)) == -1) - { - sleep(1); - try_limit--; - if(try_limit==0) - { - fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ - '''failed...giving up \\n"); - fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ - '''port, failed...giving up \\n"); - exit(1); - } - } - else - { - printf("Client-Connected to server \\n"); - fprintf(log_client,"Client-Connected to server \\n"); - break; - } - } - ''' - - # Assign bit value to every input - assign_data_to_input = [] - for item in self.input_port: - assign_data_to_input.append("\tfor(Ii=0;Ii " + item.split(':')[0] + ",\n") - - for item in self.output_port: - if self.output_port.index(item) == len(self.output_port) - 1: - map.append("\t\t\t\t" + item.split(':')[0] + - " => " + item.split(':')[0] + "\n") - else: - map.append("\t\t\t\t" + item.split(':')[0] + - " => " + item.split(':')[0] + ",\n") - map.append("\t\t\t);") - - # Testbench Clock - tb_clk = "clk_s <= not clk_s after 5 us;\n\n" - - # Adding Process block for Vhpi - process_Vhpi = [] - process_Vhpi.append( - "process\n\t\tvariable sock_port : integer;" + - "\n\t\ttype string_ptr is access string;" + - "\n\t\tvariable sock_ip : string_ptr;" + - "\n\t\tbegin\n\t\tsock_port := sock_port_fun;" + - "\n\t\tsock_ip := new string'(sock_ip_fun);" + - "\n\t\tVhpi_Initialize(sock_port," + - "Pack_String_To_Vhpi_String(sock_ip.all));" + - "\n\t\twait until clk_s = '1';" + - "\n\t\twhile true loop\n\t\t\twait until clk_s = '0';" + - "\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\t" + - "Vhpi_Send;" + - "\n\t\tend loop;\n\t\twait;\n\tend process;\n\n" - ) - - # Adding process block - process = [] - process.append("\tprocess\n") - process.append("\t\tvariable count : integer:=0;\n") - - for item in self.input_port: - process.append( - "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" - ) - - for item in self.output_port: - process.append( - "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" - ) - - process.append("\t\tvariable obj_ref : VhpiString;\n") - process.append("\tbegin\n") - process.append("\t\twhile true loop\n") - process.append("\t\t\twait until clk_s = '0';\n\n") - - port_vector_count = 0 - - for item in self.input_port: - process.append( - '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + - item.split(':')[0] + '");\n' - ) - process.append( - '\t\t\tVhpi_Get_Port_Value(obj_ref,' + - item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' - ) - - if self.port_vector_info[port_vector_count]: - process.append( - '\t\t\t' + item.split(':')[0] + - ' <= Unpack_String(' + item.split(':')[0] + '_v,' + - item.split(':')[1] + ');\n' - ) - else: - process.append( - '\t\t\t' + item.split(':')[0] + - ' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n' - ) - - port_vector_count += 1 - process.append("\n") - - process.append('\t\t\twait for 1 us;\n') - - for item in self.output_port: - if self.port_vector_info[port_vector_count]: - process.append( - '\t\t\t' + item.split(':')[0] + - '_v := Pack_String_To_Vhpi_String' + - '(Convert_SLV_To_String(' + - item.split(':')[0]+'));\n' - ) - else: - process.append( - '\t\t\t' + item.split(':')[0] + - '_v := Pack_String_To_Vhpi_String(To_String(' + - item.split(':')[0]+'));\n' - ) - - port_vector_count += 1 - - process.append( - '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + - item.split(':')[0]+'");\n' - ) - process.append( - '\t\t\tVhpi_Set_Port_Value(obj_ref,' + - item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' - ) - process.append("\n") - - process.append( - '\t\t\treport "Iteration - "' + - "& integer'image(count) severity note;\n" - ) - process.append('\t\t\tcount := count + 1;\n') - process.append("\t\tend loop;\n") - process.append("\tend process;\n\n") - process.append("end architecture;") - - # Writing all the components to testbench file - testbench.write(comment_vhdl) - testbench.write(tb_header) - testbench.write(tb_entity) - testbench.write(arch) - - for item in components: - testbench.write(item) - - for item in signals: - testbench.write(item) - - testbench.write("\n\n") - - testbench.write("begin\n\n") - - for item in map: - testbench.write(item) - - testbench.write("\n\t"+tb_clk) - - for item in process_Vhpi: - testbench.write(item) - - for item in process: - testbench.write(item) - - testbench.close() - - def createServerScript(self): - - # ####### Creating and writing components in start_server.sh ####### # - - start_server = open('start_server.sh', 'w') - - start_server.write("#!/bin/bash\n\n") - start_server.write( - "###This server run ghdl testebench for infinite time till " + - "ngspice send END signal to stop it\n\n" - ) - start_server.write( - "cd "+self.home+"/ngspice-nghdl/src/xspice/icm/ghdl/" + - self.fname.split('.')[0]+"/DUTghdl/\n" - ) - start_server.write("chmod 775 sock_pkg_create.sh &&\n") - start_server.write("./sock_pkg_create.sh $1 $2 &&\n") - start_server.write("ghdl -i *.vhdl &&\n") - start_server.write("ghdl -a *.vhdl &&\n") - start_server.write("ghdl -a "+self.fname+" &&\n") - start_server.write( - "ghdl -a "+self.fname.split('.')[0]+"_tb.vhdl &&\n" - ) - start_server.write( - "ghdl -e -Wl,ghdlserver.o " + self.fname.split('.')[0] + "_tb &&\n" - ) - start_server.write("./"+self.fname.split('.')[0]+"_tb") - - start_server.close() - - def createSockScript(self): - - # ########### Creating and writing in sock_pkg_create.sh ########### # - - sock_pkg_create = open('sock_pkg_create.sh', 'w') - - sock_pkg_create.write("#!/bin/bash\n\n") - sock_pkg_create.write( - "##This file creates sock_pkg.vhdl file and sets the port " + - "and ip from parameters passed to it\n\n" - ) - sock_pkg_create.write("echo \"library ieee;\n") - sock_pkg_create.write("package sock_pkg is\n") - sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") - sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") - sock_pkg_create.write("end;\n\n") - sock_pkg_create.write("package body sock_pkg is\n") - sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") - sock_pkg_create.write("\t\tvariable sock_port : integer;\n") - sock_pkg_create.write("\t\t\tbegin\n") - sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") - sock_pkg_create.write("\t\t\t\treturn sock_port;\n") - sock_pkg_create.write("\t\t\tend function;\n\n") - sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") - sock_pkg_create.write("\t\ttype string_ptr is access string;\n") - sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") - sock_pkg_create.write("\t\t\tbegin\n") - sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') - sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") - sock_pkg_create.write("\t\t\tend function;\n\n") - sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl") +#!/usr/bin/python3 + +import re +import os +from configparser import SafeConfigParser + + +class ModelGeneration: + + def __init__(self, file): + + # Script starts from here + print("Arguement is : ", file) + self.fname = os.path.basename(file) + print("VHDL filename is : ", self.fname) + self.home = os.path.expanduser("~") + self.parser = SafeConfigParser() + self.parser.read(os.path.join( + self.home, os.path.join('.nghdl', 'config.ini'))) + self.ngspice_home = self.parser.get('NGSPICE', 'NGSPICE_HOME') + self.release_dir = self.parser.get('NGSPICE', 'RELEASE') + self.src_home = self.parser.get('SRC', 'SRC_HOME') + self.licensefile = self.parser.get('SRC', 'LICENSE') + + # #### Creating connection_info.txt file from vhdl file #### # + read_vhdl = open(file, 'r') + vhdl_data = read_vhdl.readlines() + read_vhdl.close() + + start_flag = -1 # Used for scaning part of data + scan_data = [] + # p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() + + for item in vhdl_data: + if re.search('port', item, re.I): + start_flag = 1 + + elif re.search("end", item, re.I): + start_flag = 0 + + if start_flag == 1: + item = re.sub("port", " ", item, flags=re.I) + item = re.sub("\(", " ", item, flags=re.I) # noqa + item = re.sub("\)", " ", item, flags=re.I) # noqa + item = re.sub(";", " ", item, flags=re.I) + + scan_data.append(item.rstrip()) + scan_data = [_f for _f in scan_data if _f] + elif start_flag == 0: + break + + port_info = [] + self.port_vector_info = [] + + for item in scan_data: + print("Scan Data :", item) + if re.search("in", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of input port") + elif re.search("out", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of output port") + else: + raise ValueError( + "Please check the in/out direction of your port" + ) + + lhs = temp.split(item)[0] + rhs = temp.split(item)[1] + bit_info = re.compile(r"\s*downto\s*", flags=re.I).split(rhs)[0] + if bit_info: + port_info.append(lhs + ":" + str(int(bit_info) + int(1))) + self.port_vector_info.append(1) + else: + port_info.append(lhs + ":" + str(int(1))) + self.port_vector_info.append(0) + + print("Port Info :", port_info) + + # Open connection_info.txt file + con_ifo = open('connection_info.txt', 'w') + + for item in port_info: + word = item.split(':') + con_ifo.write( + word[0].strip() + ' ' + word[1].strip() + ' ' + word[2].strip() + ) + con_ifo.write("\n") + con_ifo.close() + + def readPortInfo(self): + + # ############## Reading connection/port information ############## # + + # Declaring input and output list + input_list = [] + output_list = [] + + # Reading connection_info.txt file for port infomation + read_file = open('connection_info.txt', 'r') + data = read_file.readlines() + read_file.close() + + # Extracting input and output port list from data + print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") + for line in data: + print(line) + if re.match(r'^\s*$', line): + pass + else: + in_items = re.findall( + "IN", line, re.MULTILINE | re.IGNORECASE + ) + out_items = re.findall( + "OUT", line, re.MULTILINE | re.IGNORECASE + ) + if in_items: + input_list.append(line.split()) + + if out_items: + output_list.append(line.split()) + + print("Inout List :", input_list) + print("Output list", output_list) + + self.input_port = [] + self.output_port = [] + + # creating list of input and output port with its weight + for input in input_list: + self.input_port.append(input[0]+":"+input[2]) + for output in output_list: + self.output_port.append(output[0]+":"+output[2]) + + print("Output Port List : ", self.output_port) + print("Input Port List : ", self.input_port) + +#08.June.2020 - BM - If OS is Windows, write Windows socket version of cfunc.mod, else write Linux(BSD) socket version + if os.name == 'nt': + def createCfuncModFile(self): + + # ## Creating content for cfunc.mod file ## # + + print("Starting With cfunc.mod file") + cfunc = open('cfunc.mod', 'w') + print("Building content for cfunc.mod file") + + comment = '''/* This is cfunc.mod file auto generated by gen_con_info.py + Developed by Fahim, Rahul at IIT Bombay */\n + ''' + + header = ''' + #include + #include + #include + #include + #include + #include + #include + #include + + #undef BOOLEAN + #include + ''' + + function_open = ( + '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') + + digital_state_output = [] + for item in self.output_port: + digital_state_output.append( + "Digital_State_t *_op_" + item.split(':')[0] + + ", *_op_" + item.split(':')[0] + "_old;" + ) + + var_section = ''' + // Declaring components of Client + FILE *log_client = NULL; + log_client=fopen("client.log","a"); + int bytes_recieved; + char send_data[1024]; + char recv_data[1024]; + char *key_iter; + struct hostent *host; + struct sockaddr_in server_addr; + int sock_port = 5000+PARAM(instance_id); + ''' + + temp_input_var = [] + for item in self.input_port: + temp_input_var.append( + "char temp_" + item.split(':')[0] + "[1024];" + ) + + # Start of INIT function + init_start_function = ''' + if(INIT) + { + /* Allocate storage for output ports ''' \ + '''and set the load for input ports */ + ''' + + cm_event_alloc = [] + cm_count_output = 0 + for item in self.output_port: + cm_event_alloc.append( + "cm_event_alloc(" + + str(cm_count_output) + "," + item.split(':')[1] + + "*sizeof(Digital_State_t));" + ) + cm_count_output = cm_count_output + 1 + + load_in_port = [] + for item in self.input_port: + load_in_port.append( + "for(Ii=0;Iih_addr); + bzero(&(server_addr.sin_zero),8); + + ''' + + connect_server = ''' + fprintf(log_client,"Client-Connecting to server \\n"); + + //Connecting to server + int try_limit=10; + while(try_limit>0) + { + if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ + '''sizeof(struct sockaddr)) == -1) + { + sleep(1); + try_limit--; + if(try_limit==0) + { + fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ + '''failed...giving up \\n"); + fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ + '''port, failed...giving up \\n"); + exit(1); + } + } + else + { + printf("Client-Connected to server \\n"); + fprintf(log_client,"Client-Connected to server \\n"); + break; + } + } + ''' + + # Assign bit value to every input + assign_data_to_input = [] + for item in self.input_port: + assign_data_to_input.append("\tfor(Ii=0;Ii + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + ''' + + function_open = ( + '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') + + digital_state_output = [] + for item in self.output_port: + digital_state_output.append( + "Digital_State_t *_op_" + item.split(':')[0] + + ", *_op_" + item.split(':')[0] + "_old;" + ) + + var_section = ''' + // Declaring components of Client + FILE *log_client = NULL; + log_client=fopen("client.log","a"); + int socket_fd, bytes_recieved; + char send_data[1024]; + char recv_data[1024]; + char *key_iter; + struct hostent *host; + struct sockaddr_in server_addr; + int sock_port = 5000+PARAM(instance_id); + ''' + + temp_input_var = [] + for item in self.input_port: + temp_input_var.append( + "char temp_" + item.split(':')[0] + "[1024];" + ) + + # Start of INIT function + init_start_function = ''' + if(INIT) + { + /* Allocate storage for output ports ''' \ + '''and set the load for input ports */ + ''' + + cm_event_alloc = [] + cm_count_output = 0 + for item in self.output_port: + cm_event_alloc.append( + "cm_event_alloc(" + + str(cm_count_output) + "," + item.split(':')[1] + + "*sizeof(Digital_State_t));" + ) + cm_count_output = cm_count_output + 1 + + load_in_port = [] + for item in self.input_port: + load_in_port.append( + "for(Ii=0;Iih_addr); + bzero(&(server_addr.sin_zero),8); + ''' + + connect_server = ''' + fprintf(log_client,"Client-Connecting to server \\n"); + //Connecting to server + int try_limit=10; + while(try_limit>0) + { + if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ + '''sizeof(struct sockaddr)) == -1) + { + sleep(1); + try_limit--; + if(try_limit==0) + { + fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ + '''failed...giving up \\n"); + fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ + '''port, failed...giving up \\n"); + exit(1); + } + } + else + { + printf("Client-Connected to server \\n"); + fprintf(log_client,"Client-Connected to server \\n"); + break; + } + } + ''' + + # Assign bit value to every input + assign_data_to_input = [] + for item in self.input_port: + assign_data_to_input.append("\tfor(Ii=0;Ii " + item.split(':')[0] + ",\n") + + for item in self.output_port: + if self.output_port.index(item) == len(self.output_port) - 1: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + "\n") + else: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + ",\n") + map.append("\t\t\t);") + + # Testbench Clock + tb_clk = "clk_s <= not clk_s after 5 us;\n\n" + + # Adding Process block for Vhpi + process_Vhpi = [] + process_Vhpi.append( + "process\n\t\tvariable sock_port : integer;" + + "\n\t\ttype string_ptr is access string;" + + "\n\t\tvariable sock_ip : string_ptr;" + + "\n\t\tbegin\n\t\tsock_port := sock_port_fun;" + + "\n\t\tsock_ip := new string'(sock_ip_fun);" + + "\n\t\tVhpi_Initialize(sock_port," + + "Pack_String_To_Vhpi_String(sock_ip.all));" + + "\n\t\twait until clk_s = '1';" + + "\n\t\twhile true loop\n\t\t\twait until clk_s = '0';" + + "\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\t" + + "Vhpi_Send;" + + "\n\t\tend loop;\n\t\twait;\n\tend process;\n\n" + ) + + # Adding process block + process = [] + process.append("\tprocess\n") + process.append("\t\tvariable count : integer:=0;\n") + + for item in self.input_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + for item in self.output_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + process.append("\t\tvariable obj_ref : VhpiString;\n") + process.append("\tbegin\n") + process.append("\t\twhile true loop\n") + process.append("\t\t\twait until clk_s = '0';\n\n") + + port_vector_count = 0 + + for item in self.input_port: + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0] + '");\n' + ) + process.append( + '\t\t\tVhpi_Get_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= Unpack_String(' + item.split(':')[0] + '_v,' + + item.split(':')[1] + ');\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n' + ) + + port_vector_count += 1 + process.append("\n") + + process.append('\t\t\twait for 1 us;\n') + + for item in self.output_port: + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String' + + '(Convert_SLV_To_String(' + + item.split(':')[0]+'));\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String(To_String(' + + item.split(':')[0]+'));\n' + ) + + port_vector_count += 1 + + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0]+'");\n' + ) + process.append( + '\t\t\tVhpi_Set_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + process.append("\n") + + process.append( + '\t\t\treport "Iteration - "' + + "& integer'image(count) severity note;\n" + ) + process.append('\t\t\tcount := count + 1;\n') + process.append("\t\tend loop;\n") + process.append("\tend process;\n\n") + process.append("end architecture;") + + # Writing all the components to testbench file + testbench.write(comment_vhdl) + testbench.write(tb_header) + testbench.write(tb_entity) + testbench.write(arch) + + for item in components: + testbench.write(item) + + for item in signals: + testbench.write(item) + + testbench.write("\n\n") + + testbench.write("begin\n\n") + + for item in map: + testbench.write(item) + + testbench.write("\n\t"+tb_clk) + + for item in process_Vhpi: + testbench.write(item) + + for item in process: + testbench.write(item) + + testbench.close() + + def createServerScript(self): + + # ####### Creating and writing components in start_server.sh ####### # + self.digital_home = self.parser.get('NGSPICE', 'DIGITAL_MODEL') + + start_server = open('start_server.sh', 'w') + + start_server.write("#!/bin/bash\n\n") + start_server.write( + "###This server run ghdl testebench for infinite time till " + + "ngspice send END signal to stop it\n\n" + ) + #08.June.2020 - BM - Use correct path with respect to particular OS + if os.name == 'nt': + pathstr = self.digital_home + "/" + \ + self.fname.split('.')[0] + "/DUTghdl/" + pathstr = pathstr.replace("\\", "/") + start_server.write("cd "+pathstr+"\n") + else: + start_server.write("cd "+self.digital_home + + "/" + self.fname.split('.')[0] + "/DUTghdl/\n") + start_server.write("chmod 775 sock_pkg_create.sh &&\n") + start_server.write("./sock_pkg_create.sh $1 $2 &&\n") + start_server.write("ghdl -i *.vhdl &&\n") + start_server.write("ghdl -a *.vhdl &&\n") + start_server.write("ghdl -a "+self.fname+" &&\n") + start_server.write( + "ghdl -a "+self.fname.split('.')[0]+"_tb.vhdl &&\n" + ) + #08.June.2020 - BM - If OS i Windows, link server with libws2_32.a + if os.name == 'nt': + start_server.write("ghdl -e -Wl,ghdlserver.o " + + "-Wl,libws2_32.a " + self.fname.split('.')[0] + "_tb &&\n") + start_server.write("./"+self.fname.split('.')[0]+"_tb.exe") + else: + start_server.write("ghdl -e -Wl,ghdlserver.o " + + self.fname.split('.')[0] + "_tb &&\n") + start_server.write("./"+self.fname.split('.')[0]+"_tb") + + start_server.close() + + def createSockScript(self): + + # ########### Creating and writing in sock_pkg_create.sh ########### # + + sock_pkg_create = open('sock_pkg_create.sh', 'w') + + sock_pkg_create.write("#!/bin/bash\n\n") + sock_pkg_create.write( + "##This file creates sock_pkg.vhdl file and sets the port " + + "and ip from parameters passed to it\n\n" + ) + sock_pkg_create.write("echo \"library ieee;\n") + sock_pkg_create.write("package sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") + sock_pkg_create.write("end;\n\n") + sock_pkg_create.write("package body sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") + sock_pkg_create.write("\t\tvariable sock_port : integer;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") + sock_pkg_create.write("\t\t\t\treturn sock_port;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") + sock_pkg_create.write("\t\ttype string_ptr is access string;\n") + sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') + sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl") diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 9991793..06921ad 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -2,14 +2,15 @@ # This file create the gui to install code model in the ngspice. +#08.June.2020 - Bladen Martin - Added if-else constructs to make code OS independent# import os -import sys import shutil import subprocess -from PyQt4 import QtGui -from PyQt4 import QtCore +import sys from configparser import SafeConfigParser +from PyQt4 import QtCore +from PyQt4 import QtGui from Appconfig import Appconfig from createKicadLibrary import AutoSchematic from model_generation import ModelGeneration @@ -91,7 +92,7 @@ class Mainwindow(QtGui.QWidget): def browseFile(self): print("Browse button clicked") self.filename = QtGui.QFileDialog.getOpenFileName( - self, 'Open File', '.') + self, 'Open File', '.') self.ledit.setText(self.filename) print("Vhdl file uploaded to process :", self.filename) @@ -140,7 +141,11 @@ class Mainwindow(QtGui.QWidget): ) if ret == QtGui.QMessageBox.Ok: print("Overwriting existing model " + self.modelname) - cmd = "rm -rf " + self.modelname + #08.June.2020 - BM - Delete existing model directory + if os.name == 'nt': + cmd = "rmdir " + self.modelname + "/s /q" + else: + cmd = "rm -rf " + self.modelname # process = subprocess.Popen( # cmd, stdout=subprocess.PIPE, # stderr=subprocess.PIPE, shell=True @@ -214,14 +219,26 @@ class Mainwindow(QtGui.QWidget): "/src/ghdlserver/Utility_Package.vhdl", path + "/DUTghdl/") shutil.copy(os.path.join(self.home, self.src_home) + "/src/ghdlserver/Vhpi_Package.vhdl", path + "/DUTghdl/") - + #08.June.2020 - BM - If OS is Windows, copy C library libws2_32.a to DUTghl be linked with server by GHDL + if os.name == 'nt': + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/libws2_32.a", path + "/DUTghdl/") for file in self.file_list: shutil.copy(str(file), path + "/DUTghdl/") - os.chdir(path + "/DUTghdl") - subprocess.call("bash " + path + "/DUTghdl/compile.sh", shell=True) - subprocess.call("chmod a+x start_server.sh", shell=True) - subprocess.call("chmod a+x sock_pkg_create.sh", shell=True) + #08.June.2020 - BM - Run following commands as per OS. Use bash.exe provided by MSYS for Windows + if os.name == 'nt': + self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') #path to msys bin directory where bash is located + subprocess.call(self.msys_bin+"/bash.exe " + + path + "/DUTghdl/compile.sh", shell=True) + subprocess.call(self.msys_bin+"/bash.exe -c " + + "'chmod a+x start_server.sh'", shell=True) + subprocess.call(self.msys_bin+"/bash.exe -c " + + "'chmod a+x sock_pkg_create.sh'", shell=True) + else: + subprocess.call("bash " + path + "/DUTghdl/compile.sh", shell=True) + subprocess.call("chmod a+x start_server.sh", shell=True) + subprocess.call("chmod a+x sock_pkg_create.sh", shell=True) os.remove("compile.sh") os.remove("ghdlserver.c") # os.remove("ghdlserver.h") @@ -242,10 +259,18 @@ class Mainwindow(QtGui.QWidget): def runMake(self): print("run Make Called") self.release_home = self.parser.get('NGSPICE', 'RELEASE') - os.chdir(self.release_home) + #08.June.2020 - BM - Changed make location to .../ngspice-nghdl/release/src/xspice/icm + path_icm = os.path.join(self.release_home, "src/xspice/icm") + print(path_icm) + os.chdir(path_icm) try: - cmd = " make" - print("Running Make command in " + self.release_home) + #08.June.2020 - BM - Use make.exe provided by MSYS for Windows + if os.name == 'nt': + self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') #path to msys bin directory where make is located + cmd = self.msys_bin+"\make.exe" + else: + cmd = " make" + print("Running Make command in " + path_icm) path = os.getcwd() # noqa self.process = QtCore.QProcess(self) self.process.start(cmd) @@ -257,7 +282,11 @@ class Mainwindow(QtGui.QWidget): def runMakeInstall(self): print("run Make Install Called") try: - cmd = " make install" + if os.name == 'nt': + self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') + cmd = self.msys_bin+"\make.exe install" + else: + cmd = " make install" print("Running Make Install") path = os.getcwd() # noqa try: -- cgit From eb1f6005f327932652a84f01e298395ced7a3687 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Mon, 8 Jun 2020 21:53:17 +0530 Subject: Code has been made OS independent --- src/ghdlserver/ghdlserver.c | 939 ++++++++++++++++++++++++-------------------- src/ghdlserver/ghdlserver.h | 20 +- 2 files changed, 522 insertions(+), 437 deletions(-) (limited to 'src') diff --git a/src/ghdlserver/ghdlserver.c b/src/ghdlserver/ghdlserver.c index d324e7b..ec817fd 100644 --- a/src/ghdlserver/ghdlserver.c +++ b/src/ghdlserver/ghdlserver.c @@ -1,436 +1,503 @@ -/********************************************************************************** - * FOSSEE, IIT-Bombay - ********************************************************************************** - * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking - * - Close previous used socket to prevent from - * generating too many socket descriptors - * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options - * 26.Sept.2019 - Rahul Paknikar - Added reading of IP from a file to - * support multiple digital models - * - On exit, the test bench removes the - * NGHDL_COMMON_IP_ file, shared by all - * nghdl digital models and is stored in /tmp - * directory. It tracks the used IPs for existing - * digital models in current simulation. - * - Writes PID file in append mode. - * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for - * a given event. - * - Removed bug to terminate multiple testbench - * instances in ngpsice windows. - ********************************************************************************** - ********************************************************************************** - * 24.Mar.2017 - Raj Mohan - Added signal handler for SIGUSR1, to handle an - * orphan test bench process. - * The test bench will now create a PID file in - * /tmp directory with the name - * NGHDL___ - * This file contains the PID of the test bench . - * On exit, the test bench removes this file. - * The SIGUSR1 signal serves the same purpose as the - * "End" signal. - * - Added syslog interface for logging. - * - Enabled SO_REUSEADDR socket option. - * - Added the following functions: - * o create_pid_file() - * o get_ngspice_pid() - * 22.Feb.2017 - Raj Mohan - Implemented a kludge to fix a problem in the - * test bench VHDL code. - * - Changed sleep() to nanosleep(). - * 10.Feb.2017 - Raj Mohan - Log messages with timestamp/code clean up. - * Added the following functions: - * o curtim() - * o print_hash_table() - *********************************************************************************/ - -#include -#include "ghdlserver.h" -#include "uthash.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define _XOPEN_SOURCE 500 -#define MAX_NUMBER_PORT 100 -#define NGSPICE "ngspice" // 17.Mar.2017 - RM - -static FILE* pid_file; -static char pid_filename[80]; -static char* Out_Port_Array[MAX_NUMBER_PORT]; -static int out_port_num = 0; -static int server_socket_id = -1; -static int sendto_sock; // 22.Feb.2017 - RM - Kludge -static int prev_sendto_sock; // 22.Feb.2017 - RM - Kludge -static int pid_file_created; // 10.Mar.2017 - RM - -extern char* __progname; // 26.Feb.2017 May not be portable to non-GNU systems. - -void Vhpi_Exit(int sig); - -struct my_struct { - char val[1024]; - char key[1024]; - UT_hash_handle hh; //Makes this structure hashable. -}; - -static struct my_struct *s, *users, *tmp = NULL; - - -#ifdef DEBUG -static char* curtim(void) -{ - static char ct[50]; - struct timeval tv; - struct tm* ptm; - long milliseconds; - char time_string[40]; - - gettimeofday (&tv, NULL); - ptm = localtime (&tv.tv_sec); - strftime (time_string, sizeof (time_string), "%Y-%m-%d %H:%M:%S", ptm); - milliseconds = tv.tv_usec / 1000; - sprintf (ct, "%s.%03ld", time_string, milliseconds); - return(ct); -} -#endif - - -#ifdef DEBUG -static void print_hash_table(void) -{ - struct my_struct *sptr; - - for(sptr=users; sptr != NULL; sptr=sptr->hh.next) - syslog(LOG_INFO, "Hash table:val:%s: key: %s", sptr->val, sptr->key); -} -#endif - - -static void parse_buffer(int sock_id, char* receive_buffer) -{ - static int rcvnum; - - syslog(LOG_INFO,"RCVD RCVN:%d from CLT:%d buffer : %s", - rcvnum++, sock_id,receive_buffer); - - /*Parsing buffer to store in hash table */ - char *rest; - char *token; - char *ptr1=receive_buffer; - char *var; - char *value; - - // Processing tokens. - while(token = strtok_r(ptr1, ",", &rest)) - { - ptr1 = rest; - while(var=strtok_r(token, ":", &value)) - { - s = (struct my_struct*)malloc(sizeof(struct my_struct)); - strncpy(s->key, var, 64); - strncpy(s->val, value, 64); - HASH_ADD_STR(users, key, s ); - break; - } - } - - s = (struct my_struct*)malloc(sizeof(struct my_struct)); - strncpy(s->key, "sock_id", 64); - snprintf(s->val,64, "%d", sock_id); - HASH_ADD_STR(users, key, s); -} - - -//Create Server and listen for client connections. -// 26.Sept.2019 - RP - added parameter of socket ip -static int create_server(int port_number, char my_ip[], int max_connections) -{ - int sockfd, reuse = 1; - struct sockaddr_in serv_addr; - - sockfd = socket(AF_INET, SOCK_STREAM, 0); - - if (sockfd < 0) - { - fprintf(stderr, "%s- Error: in opening socket at server \n", __progname); - //exit(1); - return -1; - } - - /* 20.Mar.2017 - RM - SO_REUSEADDR option. To take care of TIME_WAIT state.*/ - int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)); - - /* 08.Nov.2019 - RP - SO_REUSEPORT and SO_DONTROUTE option.*/ - ret += setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)); - ret += setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, &reuse, sizeof(int)); - - if (ret < 0) - { - syslog(LOG_ERR, "create_server:setsockopt() failed...."); - // close(sockfd); - // return -1; - } - - bzero((char *) &serv_addr, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(my_ip); // 26.Sept.2019 - RP - Bind to specific IP only - serv_addr.sin_port = htons(port_number); - - if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) - { - fprintf(stderr,"%s- Error: could not bind socket to port %d\n", - __progname, port_number); - syslog(LOG_ERR, "Error: could not bind socket to port %d", port_number); - close(sockfd); - exit(1); - } - - // Start listening on the server. - listen(sockfd, max_connections); - - return sockfd; -} - - -// The server to wait (blocking) for a client connection. -static int connect_to_client(int server_fd) -{ - int ret_val = 0; - int newsockfd = -1; - socklen_t clilen; - struct sockaddr_in cli_addr; - - clilen = sizeof(cli_addr); - - /* 08.Nov.2019 - RP - Blocking Socket (Accept) */ - newsockfd = accept(server_fd, (struct sockaddr *) &cli_addr, &clilen); - if (newsockfd >= 0) - { - syslog(LOG_INFO, "SRV:%d New Client Connection CLT:%d", server_fd, newsockfd); - } - else - { - syslog(LOG_ERR,"Error: failed in accept(), socket=%d", server_fd); - exit(1); - } - - return newsockfd; -} - - -//Receive string from socket and put it inside buffer. -static void receive_string(int sock_id, char* buffer) -{ - int nbytes = 0; - - /* 08.Nov.2019 - RP - Blocking Socket - Receive */ - nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); - if (nbytes <= 0) - { - perror("receive_string() - READ FAILURE "); - exit(1); - } - - //28.May.2020 - BM - Added method to close server by NGSPICE after simulation - char *exitstr = "CLOSE_FROM_NGSPICE"; - if (strcmp(buffer, exitstr)==0) - { - Vhpi_Exit(0); - } -} - - -static void Data_Send(int sockid) -{ - static int trnum; - char* out; - - int i; - char colon = ':'; - char semicolon = ';'; - int wrt_retries = 0; - int ret; - - s = NULL; - - out = calloc(1, 2048); - - // 5.July.2019 - RP - loop to send all ports at once for an event - for (i=0; ikey) == 0) - { - strncat(out, s->key, strlen(s->key)); - strncat(out, &colon, 1); - strncat(out, s->val, strlen(s->val)); - strncat(out, &semicolon, 1); - } - else - { - syslog(LOG_ERR,"The %s's value not found in the table.", - Out_Port_Array[i]); - free(out); - return; - } - } - - /* 08.Nov.2019 - RP - Blocking Socket (Send) */ - if ((send(sockid, out, strlen(out), 0)) == -1) - { - syslog(LOG_ERR,"Failure sending to CLT:%d buffer:%s", sockid, out); - exit(1); - } - - syslog(LOG_INFO,"SNT:TRNUM:%d to CLT:%d buffer: %s", trnum++, sockid, out); - free(out); -} - - -// 26.Sept.2019 - RP - added parameter of socket ip -void Vhpi_Initialize(int sock_port, char sock_ip[]) -{ - DEFAULT_SERVER_PORT = sock_port; - - signal(SIGINT,Vhpi_Exit); - signal(SIGTERM,Vhpi_Exit); - signal(SIGUSR1, Vhpi_Exit); //10.Mar.2017 - RM - - int try_limit = 100; - - while(try_limit > 0) - { - // 26.Sept.2019 - RP - server_socket_id = create_server(DEFAULT_SERVER_PORT, sock_ip, DEFAULT_MAX_CONNECTIONS); - - if(server_socket_id >= 0) - { - syslog(LOG_INFO,"Started the server on port %d SRV:%d", - DEFAULT_SERVER_PORT, server_socket_id); - break; - } - - syslog(LOG_ERR,"Could not start server on port %d,will try again", - DEFAULT_SERVER_PORT); - usleep(1000); - try_limit--; - - if(try_limit==0) - { - syslog(LOG_ERR, - "Error:Tried to start server on port %d, failed..giving up.", - DEFAULT_SERVER_PORT); - exit(1); - } - } - - //Reading Output Port name and storing in Out_Port_Array; - char* line = NULL; - size_t len = 0; - ssize_t read; - char *token; - FILE *fp; - struct timespec ts; - - fp=fopen("connection_info.txt","r"); - if (!fp) - { - syslog(LOG_ERR,"Vhpi_Initialize: Failed to open connection_info.txt. Exiting..."); - exit(1); - } - - line = (char*) malloc(80); - while ((read = getline(&line, &len, fp)) != -1) - { - if (strstr(line,"OUT") != NULL || strstr(line,"out") != NULL) - { - strtok_r(line, " ",&token); - Out_Port_Array[out_port_num] = line; - out_port_num++; - } - line = (char*) malloc(80); - } - fclose(fp); - free(line); - - ts.tv_sec = 2; - ts.tv_nsec = 0; - nanosleep(&ts, NULL); - - // 10.Mar.2017 - RM - Create PID file for the test bench. -} - - -void Vhpi_Set_Port_Value(char *port_name,char *port_value,int port_width) -{ - s = (struct my_struct*)malloc(sizeof(struct my_struct)); - strncpy(s->key, port_name,64); - strncpy(s->val,port_value,64); - HASH_ADD_STR( users, key, s ); -} - - -void Vhpi_Get_Port_Value(char* port_name,char* port_value,int port_width) -{ - HASH_FIND_STR(users,port_name,s); - if(s) - { - snprintf(port_value,sizeof(port_value),"%s",s->val); - HASH_DEL(users, s); - free(s); - s=NULL; - } -} - - -void Vhpi_Listen() -{ - sendto_sock = connect_to_client(server_socket_id); // 22.Feb.2017 - RM - Kludge - char receive_buffer[MAX_BUF_SIZE]; - receive_string(sendto_sock, receive_buffer); - - syslog(LOG_INFO, "Vhpi_Listen:New socket connection CLT:%d",sendto_sock); - - if(strcmp(receive_buffer, "END")==0) - { - syslog(LOG_INFO, "RCVD:CLOSE REQUEST from CLT:%d", sendto_sock); - Vhpi_Exit(0); - } - - parse_buffer(sendto_sock, receive_buffer); -} - - -void Vhpi_Send() -{ -// 22.Feb.2017 - RM - Kludge - if (prev_sendto_sock != sendto_sock) - { - Data_Send(sendto_sock); - - close(prev_sendto_sock); // 08.Nov.2019 - RP - Close previous socket - prev_sendto_sock = sendto_sock; - } -// 22.Feb.2017 End kludge -} - - -void Vhpi_Exit(int sig) -{ - close(server_socket_id); - syslog(LOG_INFO, "*** Closed VHPI link. Exiting... ***"); - exit(0); -} +/********************************************************************************** + * FOSSEE, IIT-Bombay + ********************************************************************************** + * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking + * - Close previous used socket to prevent from + * generating too many socket descriptors + * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options + * 26.Sept.2019 - Rahul Paknikar - Added reading of IP from a file to + * support multiple digital models + * - On exit, the test bench removes the + * NGHDL_COMMON_IP_ file, shared by all + * nghdl digital models and is stored in /tmp + * directory. It tracks the used IPs for existing + * digital models in current simulation. + * - Writes PID file in append mode. + * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for + * a given event. + * - Removed bug to terminate multiple testbench + * instances in ngpsice windows. + ********************************************************************************** + ********************************************************************************** + * 24.Mar.2017 - Raj Mohan - Added signal handler for SIGUSR1, to handle an + * orphan test bench process. + * The test bench will now create a PID file in + * /tmp directory with the name + * NGHDL___ + * This file contains the PID of the test bench . + * On exit, the test bench removes this file. + * The SIGUSR1 signal serves the same purpose as the + * "End" signal. + * - Added //syslog interface for logging. + * - Enabled SO_REUSEADDR socket option. + * - Added the following functions: + * o create_pid_file() + * o get_ngspice_pid() + * 22.Feb.2017 - Raj Mohan - Implemented a kludge to fix a problem in the + * test bench VHDL code. + * - Changed sleep() to nanosleep(). + * 10.Feb.2017 - Raj Mohan - Log messages with timestamp/code clean up. + * Added the following functions: + * o curtim() + * o print_hash_table() + *********************************************************************************/ + +#include +#include "ghdlserver.h" +#include "uthash.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#include +#endif + +#ifdef __linux__ +#include +#include +#include +#include +#include +#endif + +#define _XOPEN_SOURCE 500 +#define MAX_NUMBER_PORT 100 +#define NGSPICE "ngspice" // 17.Mar.2017 - RM + +static FILE *pid_file; +static char pid_filename[80]; +static char *Out_Port_Array[MAX_NUMBER_PORT]; +static int out_port_num = 0; + +static int server_socket_id = -1; + +static int sendto_sock; // 22.Feb.2017 - RM - Kludge +static int prev_sendto_sock; // 22.Feb.2017 - RM - Kludge +static int pid_file_created; // 10.Mar.2017 - RM + +#ifdef __linux__ +extern char *__progname; // 26.Feb.2017 May not be portable to non-GNU systems. +#endif + +void Vhpi_Exit(int sig); + +struct my_struct +{ + char val[1024]; + char key[1024]; + UT_hash_handle hh; //Makes this structure hashable. +}; + +static struct my_struct *s, *users, *tmp = NULL; + +#ifdef DEBUG +static char *curtim(void) +{ + static char ct[50]; + struct timeval tv; + struct tm *ptm; + long milliseconds; + char time_string[40]; + + gettimeofday(&tv, NULL); + ptm = localtime(&tv.tv_sec); + strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); + milliseconds = tv.tv_usec / 1000; + sprintf(ct, "%s.%03ld", time_string, milliseconds); + return (ct); +} +#endif + +#ifdef DEBUG +static void print_hash_table(void) +{ + struct my_struct *sptr; + + for (sptr = users; sptr != NULL; sptr = sptr->hh.next) + //syslog(LOG_INFO, "Hash table:val:%s: key: %s", sptr->val, sptr->key); +} +#endif + +static void parse_buffer(int sock_id, char *receive_buffer) +{ + static int rcvnum; + +#ifdef __linux__ + //syslog(LOG_INFO, "RCVD RCVN:%d from CLT:%d buffer : %s", rcvnum++, sock_id, receive_buffer); +#endif + + /*Parsing buffer to store in hash table */ + char *rest; + char *token; + char *ptr1 = receive_buffer; + char *var; + char *value; + + // Processing tokens. + while (token = strtok_r(ptr1, ",", &rest)) + { + ptr1 = rest; + while (var = strtok_r(token, ":", &value)) + { + s = (struct my_struct *)malloc(sizeof(struct my_struct)); + strncpy(s->key, var, 64); + strncpy(s->val, value, 64); + HASH_ADD_STR(users, key, s); + break; + } + } + + s = (struct my_struct *)malloc(sizeof(struct my_struct)); + strncpy(s->key, "sock_id", 64); + snprintf(s->val, 64, "%d", sock_id); + HASH_ADD_STR(users, key, s); +} + +//Create Server and listen for client connections. +// 26.Sept.2019 - RP - added parameter of socket ip + +static int create_server(int port_number, char my_ip[], int max_connections) +{ + int sockfd, reuse = 1; + struct sockaddr_in serv_addr; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + if (sockfd < 0) + { +#ifdef __linux__ + fprintf(stderr, "%s- Error: in opening socket at server \n", __progname); +#endif +#ifdef _WIN32 + fprintf(stderr, "Error: in opening socket at server \n"); +#endif + //exit(1); + return -1; + } + + //18.May.2020 - BM - typecast optval field to char * + /* 20.Mar.2017 - RM - SO_REUSEADDR option. To take care of TIME_WAIT state.*/ + int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)); + +/* 08.Nov.2019 - RP - SO_REUSEPORT and SO_DONTROUTE option.*/ +/* 08.June.2020 - B< - SO_REUSEPORT only available in Linux*/ +#ifdef __linux__ + ret += setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)); +#endif + + ret += setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, (char *)&reuse, sizeof(int)); + + if (ret < 0) + { +#ifdef __linux__ + //syslog(LOG_ERR, "create_server:setsockopt() failed...."); +#endif + // close(sockfd); + // return -1; + } + + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = inet_addr(my_ip); // 26.Sept.2019 - RP - Bind to specific IP only + serv_addr.sin_port = htons(port_number); + + if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { +#ifdef __linux__ + fprintf(stderr, "%s- Error: could not bind socket to port %d\n", __progname, port_number); + //syslog(LOG_ERR, "Error: could not bind socket to port %d", port_number); + close(sockfd); +#endif +#ifdef _WIN32 + fprintf(stderr, "Error: could not bind socket to port %d\n", port_number); + closesocket(sockfd); +#endif + exit(1); + } + + // Start listening on the server. + listen(sockfd, max_connections); + + return sockfd; +} + +// The server to wait (blocking) for a client connection. +static int connect_to_client(int server_fd) +{ + int ret_val = 0; + int newsockfd = -1; + socklen_t clilen; + struct sockaddr_in cli_addr; + + clilen = sizeof(cli_addr); + + /* 08.Nov.2019 - RP - Blocking Socket (Accept) */ + newsockfd = accept(server_fd, (struct sockaddr *)&cli_addr, &clilen); + if (newsockfd >= 0) + { +#ifdef _linux_ + //syslog(LOG_INFO, "SRV:%d New Client Connection CLT:%d", server_fd, newsockfd); +#endif + } + else + { +#ifdef __linux__ + //syslog(LOG_ERR, "Error: failed in accept(), socket=%d", server_fd); +#endif + + exit(1); + } + + return newsockfd; +} + +//Receive string from socket and put it inside buffer. +static void receive_string(int sock_id, char *buffer) +{ + int nbytes = 0; + + /* 08.Nov.2019 - RP - Blocking Socket - Receive */ + nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); + if (nbytes <= 0) + { + perror("receive_string() - READ FAILURE "); + exit(1); + } + /* 08.June.2020 - BM - Added condition to close on recieving close message + from outitf.c patch after simulation is over*/ + char *compstr = "CLOSE_FROM_NGSPICE"; + if (strcmp(buffer, compstr) == 0) + { + Vhpi_Exit(1); + } +} + +static void Data_Send(int sockid) +{ + static int trnum; + char *out; + + int i; + char colon = ':'; + char semicolon = ';'; + int wrt_retries = 0; + int ret; + + s = NULL; + + out = calloc(1, 2048); + + // 5.July.2019 - RP - loop to send all ports at once for an event + for (i = 0; i < out_port_num; i++) + { + HASH_FIND_STR(users, Out_Port_Array[i], s); + if (strcmp(Out_Port_Array[i], s->key) == 0) + { + strncat(out, s->key, strlen(s->key)); + strncat(out, &colon, 1); + strncat(out, s->val, strlen(s->val)); + strncat(out, &semicolon, 1); + } + else + { +#ifdef __linux__ + //syslog(LOG_ERR, "The %s's value not found in the table.", Out_Port_Array[i]); +#endif + free(out); + return; + } + } + + /* 08.Nov.2019 - RP - Blocking Socket (Send) */ + if ((send(sockid, out, strlen(out), 0)) == -1) + { +#ifdef __linux__ + //syslog(LOG_ERR, "Failure sending to CLT:%d buffer:%s", sockid, out); +#endif + exit(1); + } +#ifdef __linux__ + //syslog(LOG_INFO, "SNT:TRNUM:%d to CLT:%d buffer: %s", trnum++, sockid, out); +#endif + free(out); +} + +// 26.Sept.2019 - RP - added parameter of socket ip +void Vhpi_Initialize(int sock_port, char sock_ip[]) +{ + DEFAULT_SERVER_PORT = sock_port; + + signal(SIGINT, Vhpi_Exit); + signal(SIGTERM, Vhpi_Exit); + //signal(SIGUSR1, Vhpi_Exit); //10.Mar.2017 - RM + +#ifdef _WIN32 + WSADATA WSAData; + WSAStartup(MAKEWORD(2, 2), &WSAData); +#endif + + int try_limit = 100; + + while (try_limit > 0) + { + // 26.Sept.2019 - RP + server_socket_id = create_server(DEFAULT_SERVER_PORT, sock_ip, DEFAULT_MAX_CONNECTIONS); + + if (server_socket_id >= 0) + { +#ifdef __linux__ + //syslog(LOG_INFO, "Started the server on port %d SRV:%d", DEFAULT_SERVER_PORT, server_socket_id); +#endif + goto whileout; + } +#ifdef __linux__ + //syslog(LOG_ERR, "Could not start server on port %d,will try again", DEFAULT_SERVER_PORT); +#endif + usleep(1000); + try_limit--; + + if (try_limit == 0) + { +#ifdef __linux__ + //syslog(LOG_ERR, "Error:Tried to start server on port %d, failed..giving up.", DEFAULT_SERVER_PORT); +#endif + exit(1); + } + } + +whileout: + printf(""); + //Reading Output Port name and storing in Out_Port_Array; + char *line = NULL; + size_t len = 0; + ssize_t read; + char *token; + FILE *fp; + struct timespec ts; + + fp = fopen("connection_info.txt", "r"); + if (!fp) + { +#ifdef __linux__ + //syslog(LOG_ERR, "Vhpi_Initialize: Failed to open connection_info.txt. Exiting..."); +#endif + exit(1); + } + + line = (char *)malloc(80); +#ifdef __linux__ + while ((read = getline(&line, &len, fp)) != -1) + { + if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) + { + strtok_r(line, " ", &token); + Out_Port_Array[out_port_num] = line; + out_port_num++; + } + line = (char *)malloc(80); + } +#endif +#ifdef _WIN32 + while (fgets(line, sizeof(line), fp) != NULL) + { + if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) + { + strtok_r(line, " ", &token); + Out_Port_Array[out_port_num] = line; + printf("%s \n", line); + out_port_num++; + } + line = (char *)malloc(80); + } +#endif + fclose(fp); + free(line); + + ts.tv_sec = 2; + ts.tv_nsec = 0; + nanosleep(&ts, NULL); +} + +void Vhpi_Set_Port_Value(char *port_name, char *port_value, int port_width) +{ + s = (struct my_struct *)malloc(sizeof(struct my_struct)); + strncpy(s->key, port_name, 64); + strncpy(s->val, port_value, 64); + HASH_ADD_STR(users, key, s); +} + +void Vhpi_Get_Port_Value(char *port_name, char *port_value, int port_width) +{ + HASH_FIND_STR(users, port_name, s); + if (s) + { + snprintf(port_value, sizeof(port_value), "%s", s->val); + HASH_DEL(users, s); + free(s); + s = NULL; + } +} + +void Vhpi_Listen() +{ + sendto_sock = connect_to_client(server_socket_id); // 22.Feb.2017 - RM - Kludge + char receive_buffer[MAX_BUF_SIZE]; + receive_string(sendto_sock, receive_buffer); + +#ifdef __linux__ + //syslog(LOG_INFO, "Vhpi_Listen:New socket connection CLT:%d", sendto_sock); +#endif + + if (strcmp(receive_buffer, "END") == 0) + { +#ifdef __linux__ + //syslog(LOG_INFO, "RCVD:CLOSE REQUEST from CLT:%d", sendto_sock); +#endif + Vhpi_Exit(0); + } + + parse_buffer(sendto_sock, receive_buffer); +} + +void Vhpi_Send() +{ + // 22.Feb.2017 - RM - Kludge + if (prev_sendto_sock != sendto_sock) + { + Data_Send(sendto_sock); +#ifdef __linux__ + close(prev_sendto_sock); // 08.Nov.2019 - RP - Close previous socket +#endif +#ifdef _WIN32 + closesocket(prev_sendto_sock); +#endif + + prev_sendto_sock = sendto_sock; + } + // 22.Feb.2017 End kludge +} + +void Vhpi_Exit(int sig) +{ +#ifdef __linux__ + close(server_socket_id); // 08.Nov.2019 - RP - Close previous socket + //syslog(LOG_INFO, "*** Closed VHPI link. Exiting... ***"); +#endif +#ifdef _WIN32 + closesocket(server_socket_id); +#endif + exit(0); +} \ No newline at end of file diff --git a/src/ghdlserver/ghdlserver.h b/src/ghdlserver/ghdlserver.h index 9f23f0b..0011d00 100644 --- a/src/ghdlserver/ghdlserver.h +++ b/src/ghdlserver/ghdlserver.h @@ -1,13 +1,31 @@ /* 18.Mar.2017 - RM - Cleaned up.*/ +/* 20.June.2020 - BM - Added OS dependent includes*/ +#define _GNU_SOURCE +#include #include #include -#include + #include #include +#include + +#ifdef __linux__ #include #include #include +#endif + +#ifdef _WIN32 +#include +#include +#include +#include +#endif + + + + // Should be enough.. #define MAX_BUF_SIZE 4096 -- cgit From 5a693f43f8deaacad72fc4cbfa391e1a13f09fa1 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Mon, 8 Jun 2020 21:59:57 +0530 Subject: patch for closing server, in Windows and Linux --- src/outitf.c | 3987 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 1993 insertions(+), 1994 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index 45bbe23..6e7f5bf 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -1,1994 +1,1993 @@ -/********** -Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1988 Wayne A. Christopher, U. C. Berkeley CAD Group -Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski -**********/ -/************************************************************************** - * 10.Mar.2017 - RM - Added a dirty fix to handle orphan FOSSEE test bench - * processes. The following static functions were added in the process: - * o nghdl_orphan_tb() - * o nghdl_tb_SIGUSR1() - **************************************************************************/ -/************************************************************************** - * 22.Oct.2019 - RP - Read all the PIDs and send kill signal to all those - * processes. Also, Remove the common file of used IPs and PIDs for this - * Ngspice's instance rather than depending on GHDLServer to do the same. - **************************************************************************/ -/* - * This module replaces the old "writedata" routines in nutmeg. - * Unlike the writedata routines, the OUT routines are only called by - * the simulator routines, and only call routines in nutmeg. The rest - * of nutmeg doesn't deal with OUT at all. - */ - -#include "ngspice/ngspice.h" -#ifdef _WIN32 - #undef BOOLEAN //05.Jue.2020 - BM - Undefine BOOLEAN due to clashing definition in WIndows -#endif -#include "ngspice/cpdefs.h" -#include "ngspice/ftedefs.h" -#include "ngspice/dvec.h" -#include "ngspice/plot.h" -#include "ngspice/sim.h" -#include "ngspice/inpdefs.h" /* for INPtables */ -#include "ngspice/ifsim.h" -#include "ngspice/jobdefs.h" -#include "ngspice/iferrmsg.h" -#include "circuits.h" -#include "outitf.h" -#include "variable.h" -#include -#include "ngspice/cktdefs.h" -#include "ngspice/inpdefs.h" -#include "breakp2.h" -#include "runcoms.h" -#include "plotting/graf.h" -#include "../misc/misc_time.h" - -/* 10.Mar.2917 - RM - Added the following #include */ -#include -#include -#include -#include -#include -#include - -//05.June.2020 - BM - Added follwing includes for Windows -#ifdef _WIN32 - #include - #include -#endif - -/* 27.May.2020 - BM - Added the following #include */ -#ifdef __linux__ - #include - #include - #include - #include -#endif - -extern char *spice_analysis_get_name(int index); -extern char *spice_analysis_get_description(int index); - -static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, - char *refName, int refType, int numNames, char **dataNames, int dataType, - bool windowed, runDesc **runp); -static int addDataDesc(runDesc *run, char *name, int type, int ind, int meminit); -static int addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit); -static void fileInit(runDesc *run); -static void fileInit_pass2(runDesc *run); -static void fileStartPoint(FILE *fp, bool bin, int num); -static void fileAddRealValue(FILE *fp, bool bin, double value); -static void fileAddComplexValue(FILE *fp, bool bin, IFcomplex value); -static void fileEndPoint(FILE *fp, bool bin); -static void fileEnd(runDesc *run); -static void plotInit(runDesc *run); -static void plotAddRealValue(dataDesc *desc, double value); -static void plotAddComplexValue(dataDesc *desc, IFcomplex value); -static void plotEnd(runDesc *run); -static bool parseSpecial(char *name, char *dev, char *param, char *ind); -static bool name_eq(char *n1, char *n2); -static bool getSpecial(dataDesc *desc, runDesc *run, IFvalue *val); -static void freeRun(runDesc *run); -static int InterpFileAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); -static int InterpPlotAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); - -/*Output data to spice module*/ -#ifdef TCL_MODULE -#include "ngspice/tclspice.h" -#elif defined SHARED_MODULE -extern int sh_ExecutePerLoop(void); -extern void sh_vecinit(runDesc *run); -#endif - -/*Suppressing progress info in -o option */ -#ifndef HAS_WINGUI -extern bool orflag; -#endif - -// fixme -// ugly hack to work around missing api to specify the "type" of signals -int fixme_onoise_type = SV_NOTYPE; -int fixme_inoise_type = SV_NOTYPE; - -#define DOUBLE_PRECISION 15 - -static clock_t lastclock, currclock; -static double *rowbuf; -static size_t column, rowbuflen; - -static bool shouldstop = FALSE; /* Tell simulator to stop next time it asks. */ - -static bool interpolated = FALSE; -static double *valueold, *valuenew; - -#ifdef SHARED_MODULE -static bool savenone = FALSE; -#endif - -/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ - -#ifdef __linux__ -static void close_server() -{ - FILE *fptr; - char ip_filename[48]; - sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - - if(fptr) - { - char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; - int port = -1, sock = -1, try_limit = 0, skip_flag = 0; - struct sockaddr_in serv_addr; - serv_addr.sin_family = AF_INET; - - /* scan server ip and port to send close message */ - while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) - { - /* Create socket descriptor */ - try_limit = 10, skip_flag = 0; - while(try_limit > 0) - { - if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - sleep(0.2); - try_limit--; - if(try_limit == 0) - { - perror("\nClient Termination - Socket Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - - serv_addr.sin_port = htons(port); - serv_addr.sin_addr.s_addr = inet_addr(server_ip); - - /* connect with the server */ - try_limit = 10, skip_flag = 0; - while(try_limit > 0) - { - if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - sleep(0.2); - try_limit--; - if(try_limit == 0) - { - perror("\nClient Termination - Connection Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - - /* send close message to the server */ - send(sock, message, strlen(message)+1, 0); - close(sock); - } - } - - remove(ip_filename); -} -#endif - -#ifdef _WIN32 -static void close_server() -{ - WSADATA WSAData; - SOCKADDR_IN addr; - WSAStartup(MAKEWORD(2, 2), &WSAData); - FILE *fptr; - char ip_filename[48]; - sprintf(ip_filename, "C:\Windows\Temp\NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - if(fptr) - { - char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; - int port = -1, sock = -1, try_limit = 0, skip_flag = 0; - struct sockaddr_in serv_addr; - serv_addr.sin_family = AF_INET; - - /* scan server ip and port to send close message */ - while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) - { - /* Create socket descriptor */ - try_limit = 10, skip_flag = 0; - while(try_limit > 0) - { - if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - sleep(0.2); - try_limit--; - if(try_limit == 0) - { - perror("\nClient Termination - Socket Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - serv_addr.sin_port = htons(port); - serv_addr.sin_addr.s_addr = inet_addr(server_ip); - /* connect with the server */ - try_limit = 10, skip_flag = 0; - while(try_limit > 0) - { - if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - sleep(0.2); - try_limit--; - if(try_limit == 0) - { - perror("\nClient Termination - Connection Failed: "); - skip_flag = 1; - } - } - else - break; - } - if (skip_flag) - continue; - /* send close message to the server */ - send(sock, message, strlen(message)+1, 0); - closesocket(sock); - WSACleanup(); - } - } - remove(ip_filename); -} -#endif - - - /* The two "begin plot" routines share all their internals... */ - - int OUTpBeginPlot(CKTcircuit * circuitPtr, JOB * analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) - { - char *name; - - if (ft_curckt->ci_ckt == circuitPtr) - name = ft_curckt->ci_name; - else - name = "circuit name"; - - return (beginPlot(analysisPtr, circuitPtr, name, - analName, refName, refType, numNames, - dataNames, dataType, FALSE, - plotPtr)); - } - - int OUTwBeginPlot(CKTcircuit * circuitPtr, JOB * analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) - { - - return (beginPlot(analysisPtr, circuitPtr, "circuit name", - analName, refName, refType, numNames, - dataNames, dataType, TRUE, - plotPtr)); - } - - static int - beginPlot(JOB * analysisPtr, CKTcircuit * circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) - { - runDesc *run; - struct save_info *saves; - bool *savesused = NULL; - int numsaves; - int i, j, depind = 0; - char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; - char *ch, tmpname[BSIZE_SP]; - bool saveall = TRUE; - bool savealli = FALSE; - char *an_name; - int initmem; - /*to resume a run saj - *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) - */ - - if (dataType == 666 && numNames == 666) - { - run = *runp; - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); - } - else - { - /*end saj*/ - - /* Check to see if we want to print informational data. */ - if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) - fprintf(cp_err, "(debug printing enabled)\n"); - - /* Check to see if we want to save only interpolated data. */ - if (cp_getvar("interp", CP_BOOL, NULL, 0)) - { - interpolated = TRUE; - fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); - } - - *runp = run = TMALLOC(struct runDesc, 1); - - /* First fill in some general information. */ - run->analysis = analysisPtr; - run->circuit = circuitPtr; - run->name = copy(cktName); - run->type = copy(analName); - run->windowed = windowed; - run->numData = 0; - - an_name = spice_analysis_get_name(analysisPtr->JOBtype); - ft_curckt->ci_last_an = an_name; - - /* Now let's see which of these things we need. First toss in the - * reference vector. Then toss in anything that getSaves() tells - * us to save that we can find in the name list. Finally unpack - * the remaining saves into parameters. - */ - numsaves = ft_getSaves(&saves); - if (numsaves) - { - savesused = TMALLOC(bool, numsaves); - saveall = FALSE; - for (i = 0; i < numsaves; i++) - { - if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) - { - /* ignore this one this time around */ - savesused[i] = TRUE; - continue; - } - - /* Check for ".save all" and new synonym ".save allv" */ - - if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) - { - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } - - /* And now for the new ".save alli" option */ - - if (cieq(saves[i].name, "alli")) - { - savealli = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } -#ifdef SHARED_MODULE - /* this may happen if shared ngspice*/ - if (cieq(saves[i].name, "none")) - { - savenone = TRUE; - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } -#endif - } - } - - if (numsaves && !saveall) - initmem = numsaves; - else - initmem = numNames; - - /* Pass 0. */ - if (refName) - { - addDataDesc(run, refName, refType, -1, initmem); - for (i = 0; i < numsaves; i++) - if (!savesused[i] && name_eq(saves[i].name, refName)) - { - savesused[i] = TRUE; - saves[i].used = 1; - } - } - else - { - run->refIndex = -1; - } - - /* Pass 1. */ - if (numsaves && !saveall) - { - for (i = 0; i < numsaves; i++) - if (!savesused[i]) - for (j = 0; j < numNames; j++) - if (name_eq(saves[i].name, dataNames[j])) - { - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - break; - } - } - else - { - for (i = 0; i < numNames; i++) - if (!refName || !name_eq(dataNames[i], refName)) - /* Save the node as long as it's an internal device node */ - if (!strstr(dataNames[i], "#internal") && - !strstr(dataNames[i], "#source") && - !strstr(dataNames[i], "#drain") && - !strstr(dataNames[i], "#collector") && - !strstr(dataNames[i], "#emitter") && - !strstr(dataNames[i], "#base")) - { - addDataDesc(run, dataNames[i], dataType, i, initmem); - } - } - - /* Pass 1 and a bit. - This is a new pass which searches for all the internal device - nodes, and saves the terminal currents instead */ - - if (savealli) - { - depind = 0; - for (i = 0; i < numNames; i++) - { - if (strstr(dataNames[i], "#internal") || - strstr(dataNames[i], "#source") || - strstr(dataNames[i], "#drain") || - strstr(dataNames[i], "#collector") || - strstr(dataNames[i], "#emitter") || - strstr(dataNames[i], "#base")) - { - tmpname[0] = '@'; - tmpname[1] = '\0'; - strncat(tmpname, dataNames[i], BSIZE_SP - 1); - ch = strchr(tmpname, '#'); - - if (strstr(ch, "#collector")) - { - strcpy(ch, "[ic]"); - } - else if (strstr(ch, "#base")) - { - strcpy(ch, "[ib]"); - } - else if (strstr(ch, "#emitter")) - { - strcpy(ch, "[ie]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[is]"); - } - else if (strstr(ch, "#drain")) - { - strcpy(ch, "[id]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ig]"); - } - else if (strstr(ch, "#source")) - { - strcpy(ch, "[is]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ib]"); - } - else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) - { - strcpy(ch, "[id]"); - } - else - { - fprintf(cp_err, - "Debug: could output current for %s\n", tmpname); - continue; - } - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - { - if (*depbuf) - { - fprintf(stderr, - "Warning : unexpected dependent variable on %s\n", tmpname); - } - else - { - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - } - } - } - } - } - - /* Pass 2. */ - for (i = 0; i < numsaves; i++) - { - - if (savesused[i]) - continue; - - if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) - { - if (saves[i].analysis) - fprintf(cp_err, "Warning: can't parse '%s': ignored\n", - saves[i].name); - continue; - } - - /* Now, if there's a dep variable, do we already have it? */ - if (*depbuf) - { - for (j = 0; j < run->numData; j++) - if (name_eq(depbuf, run->data[j].name)) - break; - if (j == run->numData) - { - /* Better add it. */ - for (j = 0; j < numNames; j++) - if (name_eq(depbuf, dataNames[j])) - break; - if (j == numNames) - { - fprintf(cp_err, - "Warning: can't find '%s': value '%s' ignored\n", - depbuf, saves[i].name); - continue; - } - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - depind = j; - } - else - { - depind = run->data[j].outIndex; - } - } - - addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); - } - - if (numsaves) - { - for (i = 0; i < numsaves; i++) - { - tfree(saves[i].analysis); - tfree(saves[i].name); - } - tfree(saves); - tfree(savesused); - } - - if (numNames && - ((run->numData == 1 && run->refIndex != -1) || - (run->numData == 0 && run->refIndex == -1))) - { - fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", - spice_analysis_get_description(analysisPtr->JOBtype)); - return E_NOTFOUND; - } - - /* Now that we have our own data structures built up, let's see what - * nutmeg wants us to do. - */ - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); - - if (run->writeOut) - { - fileInit(run); - } - else - { - plotInit(run); - if (refName) - run->runPlot->pl_ndims = 1; - } - } - - /* define storage for old and new data, to allow interpolation */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) - { - valueold = TMALLOC(double, run->numData); - for (i = 0; i < run->numData; i++) - valueold[i] = 0.0; - valuenew = TMALLOC(double, run->numData); - } - - /*Start BLT, initilises the blt vectors saj*/ -#ifdef TCL_MODULE - blt_init(run); -#elif defined SHARED_MODULE - sh_vecinit(run); -#endif - - return (OK); - } - - /* Initialze memory for the list of all vectors in the current plot. - Add a standard vector to this plot */ - static int - addDataDesc(runDesc * run, char *name, int type, int ind, int meminit) - { - dataDesc *data; - - /* initialize memory (for all vectors or given by 'save') */ - if (!run->numData) - { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - /* If there is need for more memory */ - else if (run->numData == run->maxData) - { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); - } - - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); - - data->name = copy(name); - data->type = type; - data->gtype = GRID_LIN; - data->regular = TRUE; - data->outIndex = ind; - - /* It's the reference vector. */ - if (ind == -1) - run->refIndex = run->numData; - - run->numData++; - - return (OK); - } - - /* Initialze memory for the list of all vectors in the current plot. - Add a special vector (e.g. @q1[ib]) to this plot */ - static int - addSpecialDesc(runDesc * run, char *name, char *devname, char *param, int depind, int meminit) - { - dataDesc *data; - char *unique, *freeunique; /* unique char * from back-end */ - int ret; - - if (!run->numData) - { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - else if (run->numData == run->maxData) - { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); - } - - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); - - data->name = copy(name); - - freeunique = unique = copy(devname); - - /* unique will be overridden, if it already exists */ - ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); - data->specName = unique; - - if (ret == E_EXISTS) - tfree(freeunique); - - data->specParamName = copy(param); - - data->specIndex = depind; - data->specType = -1; - data->specFast = NULL; - data->regular = FALSE; - - run->numData++; - - return (OK); - } - - static void - OUTpD_memory(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) - { - int i, n = run->numData; - - for (i = 0; i < n; i++) - { - - dataDesc *d; - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); -#endif - - d = &run->data[i]; - - if (d->outIndex == -1) - { - if (d->type == IF_REAL) - plotAddRealValue(d, refValue->rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, refValue->cValue); - } - else if (d->regular) - { - if (d->type == IF_REAL) - plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); - } - else - { - IFvalue val; - - /* should pre-check instance */ - if (!getSpecial(d, run, &val)) - continue; - - if (d->type == IF_REAL) - plotAddRealValue(d, val.rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, val.cValue); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, d->vec); -#endif - } - } - - int OUTpData(runDesc * plotPtr, IFvalue * refValue, IFvalue * valuePtr) - { - runDesc *run = plotPtr; // FIXME - int i; - - run->pointCount++; - -#ifdef TCL_MODULE - steps_completed = run->pointCount; -#endif - /* interpolated batch mode output to file in transient analysis */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) - { - InterpFileAdd(run, refValue, valuePtr); - return (OK); - } - /* interpolated interactive or control mode output to plot in transient analysis */ - else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) - { - InterpPlotAdd(run, refValue, valuePtr); - return (OK); - } - /* standard batch mode output to file */ - else if (run->writeOut) - { - - if (run->pointCount == 1) - fileInit_pass2(run); - - fileStartPoint(run->fp, run->binary, run->pointCount); - - if (run->refIndex != -1) - { - if (run->isComplex) - { - fileAddComplexValue(run->fp, run->binary, refValue->cValue); - - /* While we're looking at the reference value, print it to the screen - every quarter of a second, to give some feedback without using - too much CPU time */ -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->cValue.real); - lastclock = currclock; - } - } -#endif - } - else - { - - /* And the same for a non-complex value */ - - fileAddRealValue(run->fp, run->binary, refValue->rValue); -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - } - } - - for (i = 0; i < run->numData; i++) - { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; - -#ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); -#endif - - if (run->data[i].regular) - { - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, - valuePtr->v.vec.rVec[run->data[i].outIndex]); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, - valuePtr->v.vec.cVec[run->data[i].outIndex]); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - { - - /* If this is the first data point, print a warning for any unrecognized - variables, since this has not already been checked */ - - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); - - if (run->isComplex) - { - val.cValue.real = 0; - val.cValue.imag = 0; - fileAddComplexValue(run->fp, run->binary, val.cValue); - } - else - { - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); - } - - continue; - } - - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, val.rValue); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, val.cValue); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - -#ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); -#endif - } - - fileEndPoint(run->fp, run->binary); - - /* Check that the write to disk completed successfully, otherwise abort */ - - if (ferror(run->fp)) - { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; - } - } - else - { - - OUTpD_memory(run, refValue, valuePtr); - - /* This is interactive mode. Update the screen with the reference - variable just the same */ - -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - if (run->isComplex) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->cValue.real : NAN); - } - else - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->rValue : NAN); - } - lastclock = currclock; - } - } -#endif - - gr_iplot(run->runPlot); - } - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - - return (OK); - } - - int OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) - { - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(plotPtr); - - return (OK); - } - - int OUTwData(runDesc * plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) - { - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(dataIndex); - NG_IGNORE(plotPtr); - - return (OK); - } - - int OUTwEnd(runDesc * plotPtr) - { - NG_IGNORE(plotPtr); - - return (OK); - } - - int OUTendPlot(runDesc * plotPtr) - { - if (plotPtr->writeOut) - { - fileEnd(plotPtr); - } - else - { - gr_end_iplot(); - plotEnd(plotPtr); - } - - tfree(valueold); - tfree(valuenew); - - freeRun(plotPtr); - - return (OK); - } - - int OUTbeginDomain(runDesc * plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) - { - NG_IGNORE(outerRefValue); - NG_IGNORE(refType); - NG_IGNORE(refName); - NG_IGNORE(plotPtr); - - return (OK); - } - - int OUTendDomain(runDesc * plotPtr) - { - NG_IGNORE(plotPtr); - - return (OK); - } - - int OUTattributes(runDesc * plotPtr, IFuid varName, int param, IFvalue *value) - { - runDesc *run = plotPtr; // FIXME - GRIDTYPE type; - - struct dvec *d; - - NG_IGNORE(value); - - if (param == OUT_SCALE_LIN) - type = GRID_LIN; - else if (param == OUT_SCALE_LOG) - type = GRID_XLOG; - else - return E_UNSUPP; - - if (run->writeOut) - { - if (varName) - { - int i; - for (i = 0; i < run->numData; i++) - if (!strcmp(varName, run->data[i].name)) - run->data[i].gtype = type; - } - else - { - run->data[run->refIndex].gtype = type; - } - } - else - { - if (varName) - { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - if (!strcmp(varName, d->v_name)) - d->v_gridtype = type; - } - else if (param == PLOT_COMB) - { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - d->v_plottype = PLOT_COMB; - } - else - { - run->runPlot->pl_scale->v_gridtype = type; - } - } - - return (OK); - } - - /* The file writing routines. */ - - static void - fileInit(runDesc * run) - { - char buf[513]; - int i; - size_t n; - - lastclock = clock(); - - /* This is a hack. */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - n = 0; - sprintf(buf, "Title: %s\n", run->name); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Date: %s\n", datestring()); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Plotname: %s\n", run->type); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Variables: %d\n", run->numData); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Points: "); - n += strlen(buf); - fputs(buf, run->fp); - - fflush(run->fp); /* Gotta do this for LATTICE. */ - if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) - run->pointPos = (long)n; - fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ - - /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ - fprintf(run->fp, "Variables:\n"); - - printf("No. of Data Columns : %d \n", run->numData); - } - - static int - guess_type(const char *name) - { - int type; - - if (substring("#branch", name)) - type = SV_CURRENT; - else if (cieq(name, "time")) - type = SV_TIME; - else if (cieq(name, "frequency")) - type = SV_FREQUENCY; - else if (ciprefix("inoise", name)) - type = fixme_inoise_type; - else if (ciprefix("onoise", name)) - type = fixme_onoise_type; - else if (cieq(name, "temp-sweep")) - type = SV_TEMP; - else if (cieq(name, "res-sweep")) - type = SV_RES; - else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ - type = SV_ADMITTANCE; - else if ((*name == '@') && substring("[c", name)) - type = SV_CAPACITANCE; - else if ((*name == '@') && substring("[i", name)) - type = SV_CURRENT; - else if ((*name == '@') && substring("[q", name)) - type = SV_CHARGE; - else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ - type = SV_POWER; - else - type = SV_VOLTAGE; - - return type; - } - - static void - fileInit_pass2(runDesc * run) - { - int i, type; - - for (i = 0; i < run->numData; i++) - { - - char *name = run->data[i].name; - - type = guess_type(name); - - if (type == SV_CURRENT) - { - char *branch = strstr(name, "#branch"); - if (branch) - *branch = '\0'; - fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); - if (branch) - *branch = '#'; - } - else if (type == SV_VOLTAGE) - { - fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); - } - else - { - fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); - } - - if (run->data[i].gtype == GRID_XLOG) - fprintf(run->fp, "\tgrid=3"); - - fprintf(run->fp, "\n"); - } - - fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); - fflush(run->fp); - - /* Allocate Row buffer */ - - if (run->binary) - { - rowbuflen = (size_t)(run->numData); - if (run->isComplex) - rowbuflen *= 2; - rowbuf = TMALLOC(double, rowbuflen); - } - else - { - rowbuflen = 0; - rowbuf = NULL; - } - } - - static void - fileStartPoint(FILE * fp, bool bin, int num) - { - if (!bin) - fprintf(fp, "%d\t", num - 1); - - /* reset buffer pointer to zero */ - - column = 0; - } - - static void - fileAddRealValue(FILE * fp, bool bin, double value) - { - if (bin) - rowbuf[column++] = value; - else - fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); - } - - static void - fileAddComplexValue(FILE * fp, bool bin, IFcomplex value) - { - if (bin) - { - rowbuf[column++] = value.real; - rowbuf[column++] = value.imag; - } - else - { - fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, - DOUBLE_PRECISION, value.imag); - } - } - - static void - fileEndPoint(FILE * fp, bool bin) - { - /* write row buffer to file */ - /* otherwise the data has already been written */ - - if (bin) - fwrite(rowbuf, sizeof(double), rowbuflen, fp); - } - - /* Here's the hack... Run back and fill in the number of points. */ - - static void - fileEnd(runDesc * run) - { - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any arefound, force them to exit.*/ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - - /* 28.MaY.2020 - BM */ - close_server(); - /* End 28.MaY.2020 */ - - if (run->fp != stdout) - { - long place = ftell(run->fp); - fseek(run->fp, run->pointPos, SEEK_SET); - fprintf(run->fp, "%d", run->pointCount); - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); - fseek(run->fp, place, SEEK_SET); - } - else - { - /* Yet another hack-around */ - fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); - } - - fflush(run->fp); - - tfree(rowbuf); - } - - /* The plot maintenance routines. */ - - static void - plotInit(runDesc * run) - { - struct plot *pl = plot_alloc(run->type); - struct dvec *v; - int i; - - pl->pl_title = copy(run->name); - pl->pl_name = copy(run->type); - pl->pl_date = copy(datestring()); - pl->pl_ndims = 0; - plot_new(pl); - plot_setcur(pl->pl_typename); - run->runPlot = pl; - - /* This is a hack. */ - /* if any of them complex, make them all complex */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - for (i = 0; i < run->numData; i++) - { - dataDesc *dd = &run->data[i]; - char *name; - - if (isdigit_c(dd->name[0])) - name = tprintf("V(%s)", dd->name); - else - name = copy(dd->name); - - v = dvec_alloc(name, - guess_type(name), - run->isComplex - ? (VF_COMPLEX | VF_PERMANENT) - : (VF_REAL | VF_PERMANENT), - 0, NULL); - - vec_new(v); - dd->vec = v; - } - } - - /* prepare the vector length data for memory allocation - If new, and tran or pss, length is TSTOP / TSTEP plus some margin. - If allocated length is exceeded, check progress. When > 20% then extrapolate memory needed, - if less than 20% then just double the size. - If not tran or pss, return fixed value (1024) of memory to be added. - */ - static inline int - vlength2delta(int len) - { -#ifdef SHARED_MODULE - if (savenone) - /* We need just a vector length of 1 */ - return 1; -#endif - /* TSTOP / TSTEP */ - int points = ft_curckt->ci_ckt->CKTtimeListSize; - /* transient and pss analysis (points > 0) upon start */ - if (len == 0 && points > 0) - { - /* number of timesteps plus some overhead */ - return points + 100; - } - /* transient and pss if original estimate is exceeded */ - else if (points > 0) - { - /* check where we are */ - double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; - /* return an estimate of the appropriate number of time points, if more than 20% of - the anticipated total time has passed */ - if (timerel > 0.2) - return (int)(len / timerel) - len + 1; - /* If not, just double the available memory */ - else - return len; - } - /* other analysis types that do not set CKTtimeListSize */ - else - return 1024; - } - - static void - plotAddRealValue(dataDesc * desc, double value) - { - struct dvec *v = desc->vec; - -#ifdef SHARED_MODULE - if (savenone) - /* always save new data to same location */ - v->v_length = 0; -#endif - - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - if (isreal(v)) - { - v->v_realdata[v->v_length] = value; - } - else - { - /* a real parading as a VF_COMPLEX */ - v->v_compdata[v->v_length].cx_real = value; - v->v_compdata[v->v_length].cx_imag = 0.0; - } - - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ - } - - static void - plotAddComplexValue(dataDesc * desc, IFcomplex value) - { - struct dvec *v = desc->vec; - -#ifdef SHARED_MODULE - if (savenone) - v->v_length = 0; -#endif - - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - v->v_compdata[v->v_length].cx_real = value.real; - v->v_compdata[v->v_length].cx_imag = value.imag; - - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ - } - - static void - plotEnd(runDesc * run) - { - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are*/ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - - /* 28.MaY.2020 - BM */ - close_server(); - /* End 28.MaY.2020 */ - - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); - } - - /* ParseSpecial takes something of the form "@name[param,index]" and rips - * out name, param, andstrchr. - */ - - static bool - parseSpecial(char *name, char *dev, char *param, char *ind) - { - char *s; - - *dev = *param = *ind = '\0'; - - if (*name != '@') - return FALSE; - name++; - - s = dev; - while (*name && (*name != '[')) - *s++ = *name++; - *s = '\0'; - - if (!*name) - return TRUE; - name++; - - s = param; - while (*name && (*name != ',') && (*name != ']')) - *s++ = *name++; - *s = '\0'; - - if (*name == ']') - return (!name[1] ? TRUE : FALSE); - else if (!*name) - return FALSE; - name++; - - s = ind; - while (*name && (*name != ']')) - *s++ = *name++; - *s = '\0'; - - if (*name && !name[1]) - return TRUE; - else - return FALSE; - } - - /* This routine must match two names with or without a V() around them. */ - - static bool - name_eq(char *n1, char *n2) - { - char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; - - if ((s = strchr(n1, '(')) != NULL) - { - strcpy(buf1, s); - if ((s = strchr(buf1, ')')) == NULL) - return FALSE; - *s = '\0'; - n1 = buf1; - } - - if ((s = strchr(n2, '(')) != NULL) - { - strcpy(buf2, s); - if ((s = strchr(buf2, ')')) == NULL) - return FALSE; - *s = '\0'; - n2 = buf2; - } - - return (strcmp(n1, n2) ? FALSE : TRUE); - } - - static bool - getSpecial(dataDesc * desc, runDesc * run, IFvalue * val) - { - IFvalue selector; - struct variable *vv; - - selector.iValue = desc->specIndex; - if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, - desc->specName, &desc->specFast, ft_sim, &desc->type, - &selector) == OK) - { - desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ - return TRUE; - } - - if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) - { - /* skip @ sign */ - desc->type = IF_REAL; - if (vv->va_type == CP_REAL) - val->rValue = vv->va_real; - else if (vv->va_type == CP_NUM) - val->rValue = vv->va_num; - else if (vv->va_type == CP_BOOL) - val->rValue = (vv->va_bool ? 1.0 : 0.0); - else - return FALSE; /* not a real */ - tfree(vv); - return TRUE; - } - - return FALSE; - } - - static void - freeRun(runDesc * run) - { - int i; - - for (i = 0; i < run->numData; i++) - { - tfree(run->data[i].name); - tfree(run->data[i].specParamName); - } - - tfree(run->data); - tfree(run->type); - tfree(run->name); - - tfree(run); - } - - int OUTstopnow(void) - { - if (ft_intrpt || shouldstop) - { - ft_intrpt = shouldstop = FALSE; - return (1); - } - - return (0); - } - - /* Print out error messages. */ - - static struct mesg - { - char *string; - long flag; - } msgs[] = { - {"Warning", ERR_WARNING}, - {"Fatal error", ERR_FATAL}, - {"Panic", ERR_PANIC}, - {"Note", ERR_INFO}, - {NULL, 0}}; - - void OUTerror(int flags, char *format, IFuid *names) - { - struct mesg *m; - char buf[BSIZE_SP], *s, *bptr; - int nindex = 0; - - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; - - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); - - for (s = format, bptr = buf; *s; s++) - { - if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') - { - if (names[nindex]) - strcpy(bptr, names[nindex]); - else - strcpy(bptr, "(null)"); - bptr += strlen(bptr); - s++; - nindex++; - } - else - { - *bptr++ = *s; - } - } - - *bptr = '\0'; - fprintf(cp_err, "%s\n", buf); - fflush(cp_err); - } - - void OUTerrorf(int flags, const char *format, ...) - { - struct mesg *m; - va_list args; - - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; - - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); - - va_start(args, format); - - vfprintf(cp_err, format, args); - fputc('\n', cp_err); - - fflush(cp_err); - - va_end(args); - } - - static int - InterpFileAdd(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) - { - int i; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; - - if (run->pointCount == 1) - { - fileInit_pass2(run); - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - } - - if (run->refIndex != -1) - { - /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); - interpolatenow = nodata = FALSE; - } - /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); - interpolatenow = nodata = FALSE; - } - /* Save exact point */ - else if (refValue->rValue == timestep) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, timestep); - timestep += run->circuit->CKTstep; - interpolatenow = nodata = FALSE; - } - else if (refValue->rValue > timestep) - { - /* add the next time step value to the vector */ - fileStartPoint(run->fp, run->binary, run->pointCount); - timenew = refValue->rValue; - fileAddRealValue(run->fp, run->binary, timestep); - timestep += run->circuit->CKTstep; - nodata = FALSE; - interpolatenow = TRUE; - } - else - { - /* Do not save this step */ - run->pointCount--; - timeold = refValue->rValue; - nodata = TRUE; - interpolatenow = FALSE; - } -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - } - - for (i = 0; i < run->numData; i++) - { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; - -#ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); -#endif - - if (run->data[i].regular) - { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - { - - /* If this is the first data point, print a warning for any unrecognized - variables, since this has not already been checked */ - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); - continue; - } - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = val.rValue; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = val.rValue; - } - -#ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); -#endif - } - - fileEndPoint(run->fp, run->binary); - - /* Check that the write to disk completed successfully, otherwise abort */ - if (ferror(run->fp)) - { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; - } - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - return (OK); - } - - static int - InterpPlotAdd(runDesc * run, IFvalue * refValue, IFvalue * valuePtr) - { - int i, iscale = -1; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; - - if (run->pointCount == 1) - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - - /* find the scale vector */ - for (i = 0; i < run->numData; i++) - if (run->data[i].outIndex == -1) - { - iscale = i; - break; - } - if (iscale == -1) - fprintf(stderr, "Error: no scale vector found\n"); - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(iscale); -#endif - - /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], refValue->rValue); - interpolatenow = nodata = FALSE; - } - /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); - interpolatenow = nodata = FALSE; - } - /* Save exact point */ - else if (refValue->rValue == timestep) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - interpolatenow = nodata = FALSE; - } - else if (refValue->rValue > timestep) - { - /* add the next time step value to the vector */ - timenew = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - nodata = FALSE; - interpolatenow = TRUE; - } - else - { - /* Do not save this step */ - run->pointCount--; - timeold = refValue->rValue; - nodata = TRUE; - interpolatenow = FALSE; - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(iscale, (run->data[iscale]).vec); -#endif - -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - - for (i = 0; i < run->numData; i++) - { - if (i == iscale) - continue; - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); -#endif - - if (run->data[i].regular) - { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - continue; - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = val.rValue; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = val.rValue; - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, (run->data[i]).vec); -#endif - } - - gr_iplot(run->runPlot); - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - - return (OK); - } +/********** +Copyright 1990 Regents of the University of California. All rights reserved. +Author: 1988 Wayne A. Christopher, U. C. Berkeley CAD Group +Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski +**********/ +/************************************************************************** + * 10.Mar.2017 - RM - Added a dirty fix to handle orphan FOSSEE test bench + * processes. The following static functions were added in the process: + * o nghdl_orphan_tb() + * o nghdl_tb_SIGUSR1() + **************************************************************************/ +/************************************************************************** + * 22.Oct.2019 - RP - Read all the PIDs and send kill signal to all those + * processes. Also, Remove the common file of used IPs and PIDs for this + * Ngspice's instance rather than depending on GHDLServer to do the same. + **************************************************************************/ +/* + * This module replaces the old "writedata" routines in nutmeg. + * Unlike the writedata routines, the OUT routines are only called by + * the simulator routines, and only call routines in nutmeg. The rest + * of nutmeg doesn't deal with OUT at all. + */ + +#include "ngspice/ngspice.h" +#ifdef _WIN32 +#undef BOOLEAN //05.Jue.2020 - BM - Undefine BOOLEAN due to clashing definition in WIndows +#endif +#include "ngspice/cpdefs.h" +#include "ngspice/ftedefs.h" +#include "ngspice/dvec.h" +#include "ngspice/plot.h" +#include "ngspice/sim.h" +#include "ngspice/inpdefs.h" /* for INPtables */ +#include "ngspice/ifsim.h" +#include "ngspice/jobdefs.h" +#include "ngspice/iferrmsg.h" +#include "circuits.h" +#include "outitf.h" +#include "variable.h" +#include +#include "ngspice/cktdefs.h" +#include "ngspice/inpdefs.h" +#include "breakp2.h" +#include "runcoms.h" +#include "plotting/graf.h" +#include "../misc/misc_time.h" + +/* 10.Mar.2917 - RM - Added the following #include */ +#include +#include +#include +#include +#include +#include + +//05.June.2020 - BM - Added follwing includes for Windows +#ifdef _WIN32 +#include +#include +#endif + +/* 27.May.2020 - BM - Added the following #include */ +#ifdef __linux__ +#include +#include +#include +#include +#endif + +extern char *spice_analysis_get_name(int index); +extern char *spice_analysis_get_description(int index); + +static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, + char *refName, int refType, int numNames, char **dataNames, int dataType, + bool windowed, runDesc **runp); +static int addDataDesc(runDesc *run, char *name, int type, int ind, int meminit); +static int addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit); +static void fileInit(runDesc *run); +static void fileInit_pass2(runDesc *run); +static void fileStartPoint(FILE *fp, bool bin, int num); +static void fileAddRealValue(FILE *fp, bool bin, double value); +static void fileAddComplexValue(FILE *fp, bool bin, IFcomplex value); +static void fileEndPoint(FILE *fp, bool bin); +static void fileEnd(runDesc *run); +static void plotInit(runDesc *run); +static void plotAddRealValue(dataDesc *desc, double value); +static void plotAddComplexValue(dataDesc *desc, IFcomplex value); +static void plotEnd(runDesc *run); +static bool parseSpecial(char *name, char *dev, char *param, char *ind); +static bool name_eq(char *n1, char *n2); +static bool getSpecial(dataDesc *desc, runDesc *run, IFvalue *val); +static void freeRun(runDesc *run); +static int InterpFileAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); +static int InterpPlotAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); + +/*Output data to spice module*/ +#ifdef TCL_MODULE +#include "ngspice/tclspice.h" +#elif defined SHARED_MODULE +extern int sh_ExecutePerLoop(void); +extern void sh_vecinit(runDesc *run); +#endif + +/*Suppressing progress info in -o option */ +#ifndef HAS_WINGUI +extern bool orflag; +#endif + +// fixme +// ugly hack to work around missing api to specify the "type" of signals +int fixme_onoise_type = SV_NOTYPE; +int fixme_inoise_type = SV_NOTYPE; + +#define DOUBLE_PRECISION 15 + +static clock_t lastclock, currclock; +static double *rowbuf; +static size_t column, rowbuflen; + +static bool shouldstop = FALSE; /* Tell simulator to stop next time it asks. */ + +static bool interpolated = FALSE; +static double *valueold, *valuenew; + +#ifdef SHARED_MODULE +static bool savenone = FALSE; +#endif + +/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ + +#ifdef __linux__ +static void close_server() +{ + FILE *fptr; + char ip_filename[48]; + sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); + fptr = fopen(ip_filename, "r"); + + if (fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while (fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while (try_limit > 0) + { + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if (try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while (try_limit > 0) + { + if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if (try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + /* send close message to the server */ + send(sock, message, strlen(message) + 1, 0); + close(sock); + } + } + + remove(ip_filename); +} +#endif + +#ifdef _WIN32 +static void close_server() +{ + WSADATA WSAData; + SOCKADDR_IN addr; + WSAStartup(MAKEWORD(2, 2), &WSAData); + FILE *fptr; + char ip_filename[48]; + sprintf(ip_filename, "C:\Windows\Temp\NGHDL_COMMON_IP_%d.txt", getpid()); + fptr = fopen(ip_filename, "r"); + if (fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while (fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while (try_limit > 0) + { + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if (try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while (try_limit > 0) + { + if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if (try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + if (skip_flag) + continue; + /* send close message to the server */ + send(sock, message, strlen(message) + 1, 0); + closesocket(sock); + } + } + WSACleanup(); + remove(ip_filename); +} +#endif + +/* The two "begin plot" routines share all their internals... */ + +int OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) +{ + char *name; + + if (ft_curckt->ci_ckt == circuitPtr) + name = ft_curckt->ci_name; + else + name = "circuit name"; + + return (beginPlot(analysisPtr, circuitPtr, name, + analName, refName, refType, numNames, + dataNames, dataType, FALSE, + plotPtr)); +} + +int OUTwBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) +{ + + return (beginPlot(analysisPtr, circuitPtr, "circuit name", + analName, refName, refType, numNames, + dataNames, dataType, TRUE, + plotPtr)); +} + +static int +beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) +{ + runDesc *run; + struct save_info *saves; + bool *savesused = NULL; + int numsaves; + int i, j, depind = 0; + char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; + char *ch, tmpname[BSIZE_SP]; + bool saveall = TRUE; + bool savealli = FALSE; + char *an_name; + int initmem; + /*to resume a run saj + *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) + */ + + if (dataType == 666 && numNames == 666) + { + run = *runp; + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); + } + else + { + /*end saj*/ + + /* Check to see if we want to print informational data. */ + if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) + fprintf(cp_err, "(debug printing enabled)\n"); + + /* Check to see if we want to save only interpolated data. */ + if (cp_getvar("interp", CP_BOOL, NULL, 0)) + { + interpolated = TRUE; + fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); + } + + *runp = run = TMALLOC(struct runDesc, 1); + + /* First fill in some general information. */ + run->analysis = analysisPtr; + run->circuit = circuitPtr; + run->name = copy(cktName); + run->type = copy(analName); + run->windowed = windowed; + run->numData = 0; + + an_name = spice_analysis_get_name(analysisPtr->JOBtype); + ft_curckt->ci_last_an = an_name; + + /* Now let's see which of these things we need. First toss in the + * reference vector. Then toss in anything that getSaves() tells + * us to save that we can find in the name list. Finally unpack + * the remaining saves into parameters. + */ + numsaves = ft_getSaves(&saves); + if (numsaves) + { + savesused = TMALLOC(bool, numsaves); + saveall = FALSE; + for (i = 0; i < numsaves; i++) + { + if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) + { + /* ignore this one this time around */ + savesused[i] = TRUE; + continue; + } + + /* Check for ".save all" and new synonym ".save allv" */ + + if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) + { + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } + + /* And now for the new ".save alli" option */ + + if (cieq(saves[i].name, "alli")) + { + savealli = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } +#ifdef SHARED_MODULE + /* this may happen if shared ngspice*/ + if (cieq(saves[i].name, "none")) + { + savenone = TRUE; + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } +#endif + } + } + + if (numsaves && !saveall) + initmem = numsaves; + else + initmem = numNames; + + /* Pass 0. */ + if (refName) + { + addDataDesc(run, refName, refType, -1, initmem); + for (i = 0; i < numsaves; i++) + if (!savesused[i] && name_eq(saves[i].name, refName)) + { + savesused[i] = TRUE; + saves[i].used = 1; + } + } + else + { + run->refIndex = -1; + } + + /* Pass 1. */ + if (numsaves && !saveall) + { + for (i = 0; i < numsaves; i++) + if (!savesused[i]) + for (j = 0; j < numNames; j++) + if (name_eq(saves[i].name, dataNames[j])) + { + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + break; + } + } + else + { + for (i = 0; i < numNames; i++) + if (!refName || !name_eq(dataNames[i], refName)) + /* Save the node as long as it's an internal device node */ + if (!strstr(dataNames[i], "#internal") && + !strstr(dataNames[i], "#source") && + !strstr(dataNames[i], "#drain") && + !strstr(dataNames[i], "#collector") && + !strstr(dataNames[i], "#emitter") && + !strstr(dataNames[i], "#base")) + { + addDataDesc(run, dataNames[i], dataType, i, initmem); + } + } + + /* Pass 1 and a bit. + This is a new pass which searches for all the internal device + nodes, and saves the terminal currents instead */ + + if (savealli) + { + depind = 0; + for (i = 0; i < numNames; i++) + { + if (strstr(dataNames[i], "#internal") || + strstr(dataNames[i], "#source") || + strstr(dataNames[i], "#drain") || + strstr(dataNames[i], "#collector") || + strstr(dataNames[i], "#emitter") || + strstr(dataNames[i], "#base")) + { + tmpname[0] = '@'; + tmpname[1] = '\0'; + strncat(tmpname, dataNames[i], BSIZE_SP - 1); + ch = strchr(tmpname, '#'); + + if (strstr(ch, "#collector")) + { + strcpy(ch, "[ic]"); + } + else if (strstr(ch, "#base")) + { + strcpy(ch, "[ib]"); + } + else if (strstr(ch, "#emitter")) + { + strcpy(ch, "[ie]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[is]"); + } + else if (strstr(ch, "#drain")) + { + strcpy(ch, "[id]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ig]"); + } + else if (strstr(ch, "#source")) + { + strcpy(ch, "[is]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ib]"); + } + else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) + { + strcpy(ch, "[id]"); + } + else + { + fprintf(cp_err, + "Debug: could output current for %s\n", tmpname); + continue; + } + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + { + if (*depbuf) + { + fprintf(stderr, + "Warning : unexpected dependent variable on %s\n", tmpname); + } + else + { + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + } + } + } + } + } + + /* Pass 2. */ + for (i = 0; i < numsaves; i++) + { + + if (savesused[i]) + continue; + + if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) + { + if (saves[i].analysis) + fprintf(cp_err, "Warning: can't parse '%s': ignored\n", + saves[i].name); + continue; + } + + /* Now, if there's a dep variable, do we already have it? */ + if (*depbuf) + { + for (j = 0; j < run->numData; j++) + if (name_eq(depbuf, run->data[j].name)) + break; + if (j == run->numData) + { + /* Better add it. */ + for (j = 0; j < numNames; j++) + if (name_eq(depbuf, dataNames[j])) + break; + if (j == numNames) + { + fprintf(cp_err, + "Warning: can't find '%s': value '%s' ignored\n", + depbuf, saves[i].name); + continue; + } + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + depind = j; + } + else + { + depind = run->data[j].outIndex; + } + } + + addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); + } + + if (numsaves) + { + for (i = 0; i < numsaves; i++) + { + tfree(saves[i].analysis); + tfree(saves[i].name); + } + tfree(saves); + tfree(savesused); + } + + if (numNames && + ((run->numData == 1 && run->refIndex != -1) || + (run->numData == 0 && run->refIndex == -1))) + { + fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", + spice_analysis_get_description(analysisPtr->JOBtype)); + return E_NOTFOUND; + } + + /* Now that we have our own data structures built up, let's see what + * nutmeg wants us to do. + */ + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); + + if (run->writeOut) + { + fileInit(run); + } + else + { + plotInit(run); + if (refName) + run->runPlot->pl_ndims = 1; + } + } + + /* define storage for old and new data, to allow interpolation */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) + { + valueold = TMALLOC(double, run->numData); + for (i = 0; i < run->numData; i++) + valueold[i] = 0.0; + valuenew = TMALLOC(double, run->numData); + } + + /*Start BLT, initilises the blt vectors saj*/ +#ifdef TCL_MODULE + blt_init(run); +#elif defined SHARED_MODULE + sh_vecinit(run); +#endif + + return (OK); +} + +/* Initialze memory for the list of all vectors in the current plot. + Add a standard vector to this plot */ +static int +addDataDesc(runDesc *run, char *name, int type, int ind, int meminit) +{ + dataDesc *data; + + /* initialize memory (for all vectors or given by 'save') */ + if (!run->numData) + { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + /* If there is need for more memory */ + else if (run->numData == run->maxData) + { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } + + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); + + data->name = copy(name); + data->type = type; + data->gtype = GRID_LIN; + data->regular = TRUE; + data->outIndex = ind; + + /* It's the reference vector. */ + if (ind == -1) + run->refIndex = run->numData; + + run->numData++; + + return (OK); +} + +/* Initialze memory for the list of all vectors in the current plot. + Add a special vector (e.g. @q1[ib]) to this plot */ +static int +addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit) +{ + dataDesc *data; + char *unique, *freeunique; /* unique char * from back-end */ + int ret; + + if (!run->numData) + { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + else if (run->numData == run->maxData) + { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } + + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); + + data->name = copy(name); + + freeunique = unique = copy(devname); + + /* unique will be overridden, if it already exists */ + ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); + data->specName = unique; + + if (ret == E_EXISTS) + tfree(freeunique); + + data->specParamName = copy(param); + + data->specIndex = depind; + data->specType = -1; + data->specFast = NULL; + data->regular = FALSE; + + run->numData++; + + return (OK); +} + +static void +OUTpD_memory(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i, n = run->numData; + + for (i = 0; i < n; i++) + { + + dataDesc *d; + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(i); +#endif + + d = &run->data[i]; + + if (d->outIndex == -1) + { + if (d->type == IF_REAL) + plotAddRealValue(d, refValue->rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, refValue->cValue); + } + else if (d->regular) + { + if (d->type == IF_REAL) + plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); + } + else + { + IFvalue val; + + /* should pre-check instance */ + if (!getSpecial(d, run, &val)) + continue; + + if (d->type == IF_REAL) + plotAddRealValue(d, val.rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(i, d->vec); +#endif + } +} + +int OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) +{ + runDesc *run = plotPtr; // FIXME + int i; + + run->pointCount++; + +#ifdef TCL_MODULE + steps_completed = run->pointCount; +#endif + /* interpolated batch mode output to file in transient analysis */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) + { + InterpFileAdd(run, refValue, valuePtr); + return (OK); + } + /* interpolated interactive or control mode output to plot in transient analysis */ + else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) + { + InterpPlotAdd(run, refValue, valuePtr); + return (OK); + } + /* standard batch mode output to file */ + else if (run->writeOut) + { + + if (run->pointCount == 1) + fileInit_pass2(run); + + fileStartPoint(run->fp, run->binary, run->pointCount); + + if (run->refIndex != -1) + { + if (run->isComplex) + { + fileAddComplexValue(run->fp, run->binary, refValue->cValue); + + /* While we're looking at the reference value, print it to the screen + every quarter of a second, to give some feedback without using + too much CPU time */ +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->cValue.real); + lastclock = currclock; + } + } +#endif + } + else + { + + /* And the same for a non-complex value */ + + fileAddRealValue(run->fp, run->binary, refValue->rValue); +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + } + } + + for (i = 0; i < run->numData; i++) + { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; + +#ifdef TCL_MODULE + blt_add(i, refValue ? refValue->rValue : NAN); +#endif + + if (run->data[i].regular) + { + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, + valuePtr->v.vec.rVec[run->data[i].outIndex]); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, + valuePtr->v.vec.cVec[run->data[i].outIndex]); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } + else + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + { + + /* If this is the first data point, print a warning for any unrecognized + variables, since this has not already been checked */ + + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); + + if (run->isComplex) + { + val.cValue.real = 0; + val.cValue.imag = 0; + fileAddComplexValue(run->fp, run->binary, val.cValue); + } + else + { + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + } + + continue; + } + + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, val.rValue); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } + +#ifdef TCL_MODULE + blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); +#endif + } + + fileEndPoint(run->fp, run->binary); + + /* Check that the write to disk completed successfully, otherwise abort */ + + if (ferror(run->fp)) + { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } + } + else + { + + OUTpD_memory(run, refValue, valuePtr); + + /* This is interactive mode. Update the screen with the reference + variable just the same */ + +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + if (run->isComplex) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->cValue.real : NAN); + } + else + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->rValue : NAN); + } + lastclock = currclock; + } + } +#endif + + gr_iplot(run->runPlot); + } + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + + return (OK); +} + +int OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) +{ + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(plotPtr); + + return (OK); +} + +int OUTwData(runDesc *plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) +{ + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(dataIndex); + NG_IGNORE(plotPtr); + + return (OK); +} + +int OUTwEnd(runDesc *plotPtr) +{ + NG_IGNORE(plotPtr); + + return (OK); +} + +int OUTendPlot(runDesc *plotPtr) +{ + if (plotPtr->writeOut) + { + fileEnd(plotPtr); + } + else + { + gr_end_iplot(); + plotEnd(plotPtr); + } + + tfree(valueold); + tfree(valuenew); + + freeRun(plotPtr); + + return (OK); +} + +int OUTbeginDomain(runDesc *plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) +{ + NG_IGNORE(outerRefValue); + NG_IGNORE(refType); + NG_IGNORE(refName); + NG_IGNORE(plotPtr); + + return (OK); +} + +int OUTendDomain(runDesc *plotPtr) +{ + NG_IGNORE(plotPtr); + + return (OK); +} + +int OUTattributes(runDesc *plotPtr, IFuid varName, int param, IFvalue *value) +{ + runDesc *run = plotPtr; // FIXME + GRIDTYPE type; + + struct dvec *d; + + NG_IGNORE(value); + + if (param == OUT_SCALE_LIN) + type = GRID_LIN; + else if (param == OUT_SCALE_LOG) + type = GRID_XLOG; + else + return E_UNSUPP; + + if (run->writeOut) + { + if (varName) + { + int i; + for (i = 0; i < run->numData; i++) + if (!strcmp(varName, run->data[i].name)) + run->data[i].gtype = type; + } + else + { + run->data[run->refIndex].gtype = type; + } + } + else + { + if (varName) + { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + if (!strcmp(varName, d->v_name)) + d->v_gridtype = type; + } + else if (param == PLOT_COMB) + { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + d->v_plottype = PLOT_COMB; + } + else + { + run->runPlot->pl_scale->v_gridtype = type; + } + } + + return (OK); +} + +/* The file writing routines. */ + +static void +fileInit(runDesc *run) +{ + char buf[513]; + int i; + size_t n; + + lastclock = clock(); + + /* This is a hack. */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; + + n = 0; + sprintf(buf, "Title: %s\n", run->name); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Date: %s\n", datestring()); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Plotname: %s\n", run->type); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Variables: %d\n", run->numData); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Points: "); + n += strlen(buf); + fputs(buf, run->fp); + + fflush(run->fp); /* Gotta do this for LATTICE. */ + if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) + run->pointPos = (long)n; + fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ + + /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ + fprintf(run->fp, "Variables:\n"); + + printf("No. of Data Columns : %d \n", run->numData); +} + +static int +guess_type(const char *name) +{ + int type; + + if (substring("#branch", name)) + type = SV_CURRENT; + else if (cieq(name, "time")) + type = SV_TIME; + else if (cieq(name, "frequency")) + type = SV_FREQUENCY; + else if (ciprefix("inoise", name)) + type = fixme_inoise_type; + else if (ciprefix("onoise", name)) + type = fixme_onoise_type; + else if (cieq(name, "temp-sweep")) + type = SV_TEMP; + else if (cieq(name, "res-sweep")) + type = SV_RES; + else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ + type = SV_ADMITTANCE; + else if ((*name == '@') && substring("[c", name)) + type = SV_CAPACITANCE; + else if ((*name == '@') && substring("[i", name)) + type = SV_CURRENT; + else if ((*name == '@') && substring("[q", name)) + type = SV_CHARGE; + else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ + type = SV_POWER; + else + type = SV_VOLTAGE; + + return type; +} + +static void +fileInit_pass2(runDesc *run) +{ + int i, type; + + for (i = 0; i < run->numData; i++) + { + + char *name = run->data[i].name; + + type = guess_type(name); + + if (type == SV_CURRENT) + { + char *branch = strstr(name, "#branch"); + if (branch) + *branch = '\0'; + fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); + if (branch) + *branch = '#'; + } + else if (type == SV_VOLTAGE) + { + fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); + } + else + { + fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); + } + + if (run->data[i].gtype == GRID_XLOG) + fprintf(run->fp, "\tgrid=3"); + + fprintf(run->fp, "\n"); + } + + fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); + fflush(run->fp); + + /* Allocate Row buffer */ + + if (run->binary) + { + rowbuflen = (size_t)(run->numData); + if (run->isComplex) + rowbuflen *= 2; + rowbuf = TMALLOC(double, rowbuflen); + } + else + { + rowbuflen = 0; + rowbuf = NULL; + } +} + +static void +fileStartPoint(FILE *fp, bool bin, int num) +{ + if (!bin) + fprintf(fp, "%d\t", num - 1); + + /* reset buffer pointer to zero */ + + column = 0; +} + +static void +fileAddRealValue(FILE *fp, bool bin, double value) +{ + if (bin) + rowbuf[column++] = value; + else + fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); +} + +static void +fileAddComplexValue(FILE *fp, bool bin, IFcomplex value) +{ + if (bin) + { + rowbuf[column++] = value.real; + rowbuf[column++] = value.imag; + } + else + { + fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, + DOUBLE_PRECISION, value.imag); + } +} + +static void +fileEndPoint(FILE *fp, bool bin) +{ + /* write row buffer to file */ + /* otherwise the data has already been written */ + + if (bin) + fwrite(rowbuf, sizeof(double), rowbuflen, fp); +} + +/* Here's the hack... Run back and fill in the number of points. */ + +static void +fileEnd(runDesc *run) +{ + /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any arefound, force them to exit.*/ + //nghdl_orphan_tb(); + /* End 10.Mar.2017 */ + + /* 28.May.2020 - BM - Patch for closing ghdlserver */ + close_server(); + /* End 28.May.2020 */ + + if (run->fp != stdout) + { + long place = ftell(run->fp); + fseek(run->fp, run->pointPos, SEEK_SET); + fprintf(run->fp, "%d", run->pointCount); + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); + fseek(run->fp, place, SEEK_SET); + } + else + { + /* Yet another hack-around */ + fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); + } + + fflush(run->fp); + + tfree(rowbuf); +} + +/* The plot maintenance routines. */ + +static void +plotInit(runDesc *run) +{ + struct plot *pl = plot_alloc(run->type); + struct dvec *v; + int i; + + pl->pl_title = copy(run->name); + pl->pl_name = copy(run->type); + pl->pl_date = copy(datestring()); + pl->pl_ndims = 0; + plot_new(pl); + plot_setcur(pl->pl_typename); + run->runPlot = pl; + + /* This is a hack. */ + /* if any of them complex, make them all complex */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; + + for (i = 0; i < run->numData; i++) + { + dataDesc *dd = &run->data[i]; + char *name; + + if (isdigit_c(dd->name[0])) + name = tprintf("V(%s)", dd->name); + else + name = copy(dd->name); + + v = dvec_alloc(name, + guess_type(name), + run->isComplex + ? (VF_COMPLEX | VF_PERMANENT) + : (VF_REAL | VF_PERMANENT), + 0, NULL); + + vec_new(v); + dd->vec = v; + } +} + +/* prepare the vector length data for memory allocation + If new, and tran or pss, length is TSTOP / TSTEP plus some margin. + If allocated length is exceeded, check progress. When > 20% then extrapolate memory needed, + if less than 20% then just double the size. + If not tran or pss, return fixed value (1024) of memory to be added. + */ +static inline int +vlength2delta(int len) +{ +#ifdef SHARED_MODULE + if (savenone) + /* We need just a vector length of 1 */ + return 1; +#endif + /* TSTOP / TSTEP */ + int points = ft_curckt->ci_ckt->CKTtimeListSize; + /* transient and pss analysis (points > 0) upon start */ + if (len == 0 && points > 0) + { + /* number of timesteps plus some overhead */ + return points + 100; + } + /* transient and pss if original estimate is exceeded */ + else if (points > 0) + { + /* check where we are */ + double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; + /* return an estimate of the appropriate number of time points, if more than 20% of + the anticipated total time has passed */ + if (timerel > 0.2) + return (int)(len / timerel) - len + 1; + /* If not, just double the available memory */ + else + return len; + } + /* other analysis types that do not set CKTtimeListSize */ + else + return 1024; +} + +static void +plotAddRealValue(dataDesc *desc, double value) +{ + struct dvec *v = desc->vec; + +#ifdef SHARED_MODULE + if (savenone) + /* always save new data to same location */ + v->v_length = 0; +#endif + + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); + + if (isreal(v)) + { + v->v_realdata[v->v_length] = value; + } + else + { + /* a real parading as a VF_COMPLEX */ + v->v_compdata[v->v_length].cx_real = value; + v->v_compdata[v->v_length].cx_imag = 0.0; + } + + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ +} + +static void +plotAddComplexValue(dataDesc *desc, IFcomplex value) +{ + struct dvec *v = desc->vec; + +#ifdef SHARED_MODULE + if (savenone) + v->v_length = 0; +#endif + + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); + + v->v_compdata[v->v_length].cx_real = value.real; + v->v_compdata[v->v_length].cx_imag = value.imag; + + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ +} + +static void +plotEnd(runDesc *run) +{ + /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are*/ + //nghdl_orphan_tb(); + /* End 10.Mar.2017 */ + + /* 28.May.2020 - BM - Patch for closing ghdlserver */ + close_server(); + /* End 28.May.2020 */ + + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); +} + +/* ParseSpecial takes something of the form "@name[param,index]" and rips + * out name, param, andstrchr. + */ + +static bool +parseSpecial(char *name, char *dev, char *param, char *ind) +{ + char *s; + + *dev = *param = *ind = '\0'; + + if (*name != '@') + return FALSE; + name++; + + s = dev; + while (*name && (*name != '[')) + *s++ = *name++; + *s = '\0'; + + if (!*name) + return TRUE; + name++; + + s = param; + while (*name && (*name != ',') && (*name != ']')) + *s++ = *name++; + *s = '\0'; + + if (*name == ']') + return (!name[1] ? TRUE : FALSE); + else if (!*name) + return FALSE; + name++; + + s = ind; + while (*name && (*name != ']')) + *s++ = *name++; + *s = '\0'; + + if (*name && !name[1]) + return TRUE; + else + return FALSE; +} + +/* This routine must match two names with or without a V() around them. */ + +static bool +name_eq(char *n1, char *n2) +{ + char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; + + if ((s = strchr(n1, '(')) != NULL) + { + strcpy(buf1, s); + if ((s = strchr(buf1, ')')) == NULL) + return FALSE; + *s = '\0'; + n1 = buf1; + } + + if ((s = strchr(n2, '(')) != NULL) + { + strcpy(buf2, s); + if ((s = strchr(buf2, ')')) == NULL) + return FALSE; + *s = '\0'; + n2 = buf2; + } + + return (strcmp(n1, n2) ? FALSE : TRUE); +} + +static bool +getSpecial(dataDesc *desc, runDesc *run, IFvalue *val) +{ + IFvalue selector; + struct variable *vv; + + selector.iValue = desc->specIndex; + if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, + desc->specName, &desc->specFast, ft_sim, &desc->type, + &selector) == OK) + { + desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ + return TRUE; + } + + if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) + { + /* skip @ sign */ + desc->type = IF_REAL; + if (vv->va_type == CP_REAL) + val->rValue = vv->va_real; + else if (vv->va_type == CP_NUM) + val->rValue = vv->va_num; + else if (vv->va_type == CP_BOOL) + val->rValue = (vv->va_bool ? 1.0 : 0.0); + else + return FALSE; /* not a real */ + tfree(vv); + return TRUE; + } + + return FALSE; +} + +static void +freeRun(runDesc *run) +{ + int i; + + for (i = 0; i < run->numData; i++) + { + tfree(run->data[i].name); + tfree(run->data[i].specParamName); + } + + tfree(run->data); + tfree(run->type); + tfree(run->name); + + tfree(run); +} + +int OUTstopnow(void) +{ + if (ft_intrpt || shouldstop) + { + ft_intrpt = shouldstop = FALSE; + return (1); + } + + return (0); +} + +/* Print out error messages. */ + +static struct mesg +{ + char *string; + long flag; +} msgs[] = { + {"Warning", ERR_WARNING}, + {"Fatal error", ERR_FATAL}, + {"Panic", ERR_PANIC}, + {"Note", ERR_INFO}, + {NULL, 0}}; + +void OUTerror(int flags, char *format, IFuid *names) +{ + struct mesg *m; + char buf[BSIZE_SP], *s, *bptr; + int nindex = 0; + + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; + + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); + + for (s = format, bptr = buf; *s; s++) + { + if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') + { + if (names[nindex]) + strcpy(bptr, names[nindex]); + else + strcpy(bptr, "(null)"); + bptr += strlen(bptr); + s++; + nindex++; + } + else + { + *bptr++ = *s; + } + } + + *bptr = '\0'; + fprintf(cp_err, "%s\n", buf); + fflush(cp_err); +} + +void OUTerrorf(int flags, const char *format, ...) +{ + struct mesg *m; + va_list args; + + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; + + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); + + va_start(args, format); + + vfprintf(cp_err, format, args); + fputc('\n', cp_err); + + fflush(cp_err); + + va_end(args); +} + +static int +InterpFileAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; + + if (run->pointCount == 1) + { + fileInit_pass2(run); + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; + } + + if (run->refIndex != -1) + { + /* Save first time step */ + if (refValue->rValue == run->circuit->CKTinitTime) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); + interpolatenow = nodata = FALSE; + } + /* Save last time step */ + else if (refValue->rValue == run->circuit->CKTfinalTime) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); + interpolatenow = nodata = FALSE; + } + /* Save exact point */ + else if (refValue->rValue == timestep) + { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + interpolatenow = nodata = FALSE; + } + else if (refValue->rValue > timestep) + { + /* add the next time step value to the vector */ + fileStartPoint(run->fp, run->binary, run->pointCount); + timenew = refValue->rValue; + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + nodata = FALSE; + interpolatenow = TRUE; + } + else + { + /* Do not save this step */ + run->pointCount--; + timeold = refValue->rValue; + nodata = TRUE; + interpolatenow = FALSE; + } +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + } + + for (i = 0; i < run->numData; i++) + { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; + +#ifdef TCL_MODULE + blt_add(i, refValue ? refValue->rValue : NAN); +#endif + + if (run->data[i].regular) + { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + } + else + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + { + + /* If this is the first data point, print a warning for any unrecognized + variables, since this has not already been checked */ + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + continue; + } + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = val.rValue; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = val.rValue; + } + +#ifdef TCL_MODULE + blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); +#endif + } + + fileEndPoint(run->fp, run->binary); + + /* Check that the write to disk completed successfully, otherwise abort */ + if (ferror(run->fp)) + { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + return (OK); +} + +static int +InterpPlotAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i, iscale = -1; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; + + if (run->pointCount == 1) + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; + + /* find the scale vector */ + for (i = 0; i < run->numData; i++) + if (run->data[i].outIndex == -1) + { + iscale = i; + break; + } + if (iscale == -1) + fprintf(stderr, "Error: no scale vector found\n"); + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(iscale); +#endif + + /* Save first time step */ + if (refValue->rValue == run->circuit->CKTinitTime) + { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], refValue->rValue); + interpolatenow = nodata = FALSE; + } + /* Save last time step */ + else if (refValue->rValue == run->circuit->CKTfinalTime) + { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); + interpolatenow = nodata = FALSE; + } + /* Save exact point */ + else if (refValue->rValue == timestep) + { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], timestep); + timestep += run->circuit->CKTstep; + interpolatenow = nodata = FALSE; + } + else if (refValue->rValue > timestep) + { + /* add the next time step value to the vector */ + timenew = refValue->rValue; + plotAddRealValue(&run->data[iscale], timestep); + timestep += run->circuit->CKTstep; + nodata = FALSE; + interpolatenow = TRUE; + } + else + { + /* Do not save this step */ + run->pointCount--; + timeold = refValue->rValue; + nodata = TRUE; + interpolatenow = FALSE; + } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(iscale, (run->data[iscale]).vec); +#endif + +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) + { + currclock = clock(); + if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) + { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + + for (i = 0; i < run->numData; i++) + { + if (i == iscale) + continue; + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(i); +#endif + + if (run->data[i].regular) + { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; + } + else + { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + continue; + if (!interpolatenow && !nodata) + { + /* store the first or last value */ + valueold[i] = val.rValue; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) + { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = val.rValue; + } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(i, (run->data[i]).vec); +#endif + } + + gr_iplot(run->runPlot); + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + + return (OK); +} -- cgit From 9a99050e47456aca81767b8de6bc31c7229d6eda Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Tue, 14 Jul 2020 11:39:09 +0530 Subject: bug fixes and restructured code --- src/outitf.c | 3812 ++++++++++++++++++++++++++++------------------------------ 1 file changed, 1819 insertions(+), 1993 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index 6e7f5bf..fe60f7a 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -1,1993 +1,1819 @@ -/********** -Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1988 Wayne A. Christopher, U. C. Berkeley CAD Group -Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski -**********/ -/************************************************************************** - * 10.Mar.2017 - RM - Added a dirty fix to handle orphan FOSSEE test bench - * processes. The following static functions were added in the process: - * o nghdl_orphan_tb() - * o nghdl_tb_SIGUSR1() - **************************************************************************/ -/************************************************************************** - * 22.Oct.2019 - RP - Read all the PIDs and send kill signal to all those - * processes. Also, Remove the common file of used IPs and PIDs for this - * Ngspice's instance rather than depending on GHDLServer to do the same. - **************************************************************************/ -/* - * This module replaces the old "writedata" routines in nutmeg. - * Unlike the writedata routines, the OUT routines are only called by - * the simulator routines, and only call routines in nutmeg. The rest - * of nutmeg doesn't deal with OUT at all. - */ - -#include "ngspice/ngspice.h" -#ifdef _WIN32 -#undef BOOLEAN //05.Jue.2020 - BM - Undefine BOOLEAN due to clashing definition in WIndows -#endif -#include "ngspice/cpdefs.h" -#include "ngspice/ftedefs.h" -#include "ngspice/dvec.h" -#include "ngspice/plot.h" -#include "ngspice/sim.h" -#include "ngspice/inpdefs.h" /* for INPtables */ -#include "ngspice/ifsim.h" -#include "ngspice/jobdefs.h" -#include "ngspice/iferrmsg.h" -#include "circuits.h" -#include "outitf.h" -#include "variable.h" -#include -#include "ngspice/cktdefs.h" -#include "ngspice/inpdefs.h" -#include "breakp2.h" -#include "runcoms.h" -#include "plotting/graf.h" -#include "../misc/misc_time.h" - -/* 10.Mar.2917 - RM - Added the following #include */ -#include -#include -#include -#include -#include -#include - -//05.June.2020 - BM - Added follwing includes for Windows -#ifdef _WIN32 -#include -#include -#endif - -/* 27.May.2020 - BM - Added the following #include */ -#ifdef __linux__ -#include -#include -#include -#include -#endif - -extern char *spice_analysis_get_name(int index); -extern char *spice_analysis_get_description(int index); - -static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, - char *refName, int refType, int numNames, char **dataNames, int dataType, - bool windowed, runDesc **runp); -static int addDataDesc(runDesc *run, char *name, int type, int ind, int meminit); -static int addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit); -static void fileInit(runDesc *run); -static void fileInit_pass2(runDesc *run); -static void fileStartPoint(FILE *fp, bool bin, int num); -static void fileAddRealValue(FILE *fp, bool bin, double value); -static void fileAddComplexValue(FILE *fp, bool bin, IFcomplex value); -static void fileEndPoint(FILE *fp, bool bin); -static void fileEnd(runDesc *run); -static void plotInit(runDesc *run); -static void plotAddRealValue(dataDesc *desc, double value); -static void plotAddComplexValue(dataDesc *desc, IFcomplex value); -static void plotEnd(runDesc *run); -static bool parseSpecial(char *name, char *dev, char *param, char *ind); -static bool name_eq(char *n1, char *n2); -static bool getSpecial(dataDesc *desc, runDesc *run, IFvalue *val); -static void freeRun(runDesc *run); -static int InterpFileAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); -static int InterpPlotAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); - -/*Output data to spice module*/ -#ifdef TCL_MODULE -#include "ngspice/tclspice.h" -#elif defined SHARED_MODULE -extern int sh_ExecutePerLoop(void); -extern void sh_vecinit(runDesc *run); -#endif - -/*Suppressing progress info in -o option */ -#ifndef HAS_WINGUI -extern bool orflag; -#endif - -// fixme -// ugly hack to work around missing api to specify the "type" of signals -int fixme_onoise_type = SV_NOTYPE; -int fixme_inoise_type = SV_NOTYPE; - -#define DOUBLE_PRECISION 15 - -static clock_t lastclock, currclock; -static double *rowbuf; -static size_t column, rowbuflen; - -static bool shouldstop = FALSE; /* Tell simulator to stop next time it asks. */ - -static bool interpolated = FALSE; -static double *valueold, *valuenew; - -#ifdef SHARED_MODULE -static bool savenone = FALSE; -#endif - -/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ - -#ifdef __linux__ -static void close_server() -{ - FILE *fptr; - char ip_filename[48]; - sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - - if (fptr) - { - char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; - int port = -1, sock = -1, try_limit = 0, skip_flag = 0; - struct sockaddr_in serv_addr; - serv_addr.sin_family = AF_INET; - - /* scan server ip and port to send close message */ - while (fscanf(fptr, "%s %d\n", server_ip, &port) == 2) - { - /* Create socket descriptor */ - try_limit = 10, skip_flag = 0; - while (try_limit > 0) - { - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - sleep(0.2); - try_limit--; - if (try_limit == 0) - { - perror("\nClient Termination - Socket Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - - serv_addr.sin_port = htons(port); - serv_addr.sin_addr.s_addr = inet_addr(server_ip); - - /* connect with the server */ - try_limit = 10, skip_flag = 0; - while (try_limit > 0) - { - if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - sleep(0.2); - try_limit--; - if (try_limit == 0) - { - perror("\nClient Termination - Connection Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - - /* send close message to the server */ - send(sock, message, strlen(message) + 1, 0); - close(sock); - } - } - - remove(ip_filename); -} -#endif - -#ifdef _WIN32 -static void close_server() -{ - WSADATA WSAData; - SOCKADDR_IN addr; - WSAStartup(MAKEWORD(2, 2), &WSAData); - FILE *fptr; - char ip_filename[48]; - sprintf(ip_filename, "C:\Windows\Temp\NGHDL_COMMON_IP_%d.txt", getpid()); - fptr = fopen(ip_filename, "r"); - if (fptr) - { - char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; - int port = -1, sock = -1, try_limit = 0, skip_flag = 0; - struct sockaddr_in serv_addr; - serv_addr.sin_family = AF_INET; - - /* scan server ip and port to send close message */ - while (fscanf(fptr, "%s %d\n", server_ip, &port) == 2) - { - /* Create socket descriptor */ - try_limit = 10, skip_flag = 0; - while (try_limit > 0) - { - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - sleep(0.2); - try_limit--; - if (try_limit == 0) - { - perror("\nClient Termination - Socket Failed: "); - skip_flag = 1; - } - } - else - break; - } - - if (skip_flag) - continue; - serv_addr.sin_port = htons(port); - serv_addr.sin_addr.s_addr = inet_addr(server_ip); - /* connect with the server */ - try_limit = 10, skip_flag = 0; - while (try_limit > 0) - { - if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - sleep(0.2); - try_limit--; - if (try_limit == 0) - { - perror("\nClient Termination - Connection Failed: "); - skip_flag = 1; - } - } - else - break; - } - if (skip_flag) - continue; - /* send close message to the server */ - send(sock, message, strlen(message) + 1, 0); - closesocket(sock); - } - } - WSACleanup(); - remove(ip_filename); -} -#endif - -/* The two "begin plot" routines share all their internals... */ - -int OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) -{ - char *name; - - if (ft_curckt->ci_ckt == circuitPtr) - name = ft_curckt->ci_name; - else - name = "circuit name"; - - return (beginPlot(analysisPtr, circuitPtr, name, - analName, refName, refType, numNames, - dataNames, dataType, FALSE, - plotPtr)); -} - -int OUTwBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, - IFuid analName, - IFuid refName, int refType, - int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) -{ - - return (beginPlot(analysisPtr, circuitPtr, "circuit name", - analName, refName, refType, numNames, - dataNames, dataType, TRUE, - plotPtr)); -} - -static int -beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) -{ - runDesc *run; - struct save_info *saves; - bool *savesused = NULL; - int numsaves; - int i, j, depind = 0; - char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; - char *ch, tmpname[BSIZE_SP]; - bool saveall = TRUE; - bool savealli = FALSE; - char *an_name; - int initmem; - /*to resume a run saj - *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) - */ - - if (dataType == 666 && numNames == 666) - { - run = *runp; - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); - } - else - { - /*end saj*/ - - /* Check to see if we want to print informational data. */ - if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) - fprintf(cp_err, "(debug printing enabled)\n"); - - /* Check to see if we want to save only interpolated data. */ - if (cp_getvar("interp", CP_BOOL, NULL, 0)) - { - interpolated = TRUE; - fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); - } - - *runp = run = TMALLOC(struct runDesc, 1); - - /* First fill in some general information. */ - run->analysis = analysisPtr; - run->circuit = circuitPtr; - run->name = copy(cktName); - run->type = copy(analName); - run->windowed = windowed; - run->numData = 0; - - an_name = spice_analysis_get_name(analysisPtr->JOBtype); - ft_curckt->ci_last_an = an_name; - - /* Now let's see which of these things we need. First toss in the - * reference vector. Then toss in anything that getSaves() tells - * us to save that we can find in the name list. Finally unpack - * the remaining saves into parameters. - */ - numsaves = ft_getSaves(&saves); - if (numsaves) - { - savesused = TMALLOC(bool, numsaves); - saveall = FALSE; - for (i = 0; i < numsaves; i++) - { - if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) - { - /* ignore this one this time around */ - savesused[i] = TRUE; - continue; - } - - /* Check for ".save all" and new synonym ".save allv" */ - - if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) - { - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } - - /* And now for the new ".save alli" option */ - - if (cieq(saves[i].name, "alli")) - { - savealli = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } -#ifdef SHARED_MODULE - /* this may happen if shared ngspice*/ - if (cieq(saves[i].name, "none")) - { - savenone = TRUE; - saveall = TRUE; - savesused[i] = TRUE; - saves[i].used = 1; - continue; - } -#endif - } - } - - if (numsaves && !saveall) - initmem = numsaves; - else - initmem = numNames; - - /* Pass 0. */ - if (refName) - { - addDataDesc(run, refName, refType, -1, initmem); - for (i = 0; i < numsaves; i++) - if (!savesused[i] && name_eq(saves[i].name, refName)) - { - savesused[i] = TRUE; - saves[i].used = 1; - } - } - else - { - run->refIndex = -1; - } - - /* Pass 1. */ - if (numsaves && !saveall) - { - for (i = 0; i < numsaves; i++) - if (!savesused[i]) - for (j = 0; j < numNames; j++) - if (name_eq(saves[i].name, dataNames[j])) - { - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - break; - } - } - else - { - for (i = 0; i < numNames; i++) - if (!refName || !name_eq(dataNames[i], refName)) - /* Save the node as long as it's an internal device node */ - if (!strstr(dataNames[i], "#internal") && - !strstr(dataNames[i], "#source") && - !strstr(dataNames[i], "#drain") && - !strstr(dataNames[i], "#collector") && - !strstr(dataNames[i], "#emitter") && - !strstr(dataNames[i], "#base")) - { - addDataDesc(run, dataNames[i], dataType, i, initmem); - } - } - - /* Pass 1 and a bit. - This is a new pass which searches for all the internal device - nodes, and saves the terminal currents instead */ - - if (savealli) - { - depind = 0; - for (i = 0; i < numNames; i++) - { - if (strstr(dataNames[i], "#internal") || - strstr(dataNames[i], "#source") || - strstr(dataNames[i], "#drain") || - strstr(dataNames[i], "#collector") || - strstr(dataNames[i], "#emitter") || - strstr(dataNames[i], "#base")) - { - tmpname[0] = '@'; - tmpname[1] = '\0'; - strncat(tmpname, dataNames[i], BSIZE_SP - 1); - ch = strchr(tmpname, '#'); - - if (strstr(ch, "#collector")) - { - strcpy(ch, "[ic]"); - } - else if (strstr(ch, "#base")) - { - strcpy(ch, "[ib]"); - } - else if (strstr(ch, "#emitter")) - { - strcpy(ch, "[ie]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[is]"); - } - else if (strstr(ch, "#drain")) - { - strcpy(ch, "[id]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ig]"); - } - else if (strstr(ch, "#source")) - { - strcpy(ch, "[is]"); - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - strcpy(ch, "[ib]"); - } - else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) - { - strcpy(ch, "[id]"); - } - else - { - fprintf(cp_err, - "Debug: could output current for %s\n", tmpname); - continue; - } - if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) - { - if (*depbuf) - { - fprintf(stderr, - "Warning : unexpected dependent variable on %s\n", tmpname); - } - else - { - addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); - } - } - } - } - } - - /* Pass 2. */ - for (i = 0; i < numsaves; i++) - { - - if (savesused[i]) - continue; - - if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) - { - if (saves[i].analysis) - fprintf(cp_err, "Warning: can't parse '%s': ignored\n", - saves[i].name); - continue; - } - - /* Now, if there's a dep variable, do we already have it? */ - if (*depbuf) - { - for (j = 0; j < run->numData; j++) - if (name_eq(depbuf, run->data[j].name)) - break; - if (j == run->numData) - { - /* Better add it. */ - for (j = 0; j < numNames; j++) - if (name_eq(depbuf, dataNames[j])) - break; - if (j == numNames) - { - fprintf(cp_err, - "Warning: can't find '%s': value '%s' ignored\n", - depbuf, saves[i].name); - continue; - } - addDataDesc(run, dataNames[j], dataType, j, initmem); - savesused[i] = TRUE; - saves[i].used = 1; - depind = j; - } - else - { - depind = run->data[j].outIndex; - } - } - - addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); - } - - if (numsaves) - { - for (i = 0; i < numsaves; i++) - { - tfree(saves[i].analysis); - tfree(saves[i].name); - } - tfree(saves); - tfree(savesused); - } - - if (numNames && - ((run->numData == 1 && run->refIndex != -1) || - (run->numData == 0 && run->refIndex == -1))) - { - fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", - spice_analysis_get_description(analysisPtr->JOBtype)); - return E_NOTFOUND; - } - - /* Now that we have our own data structures built up, let's see what - * nutmeg wants us to do. - */ - run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, - run->type, run->name); - - if (run->writeOut) - { - fileInit(run); - } - else - { - plotInit(run); - if (refName) - run->runPlot->pl_ndims = 1; - } - } - - /* define storage for old and new data, to allow interpolation */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) - { - valueold = TMALLOC(double, run->numData); - for (i = 0; i < run->numData; i++) - valueold[i] = 0.0; - valuenew = TMALLOC(double, run->numData); - } - - /*Start BLT, initilises the blt vectors saj*/ -#ifdef TCL_MODULE - blt_init(run); -#elif defined SHARED_MODULE - sh_vecinit(run); -#endif - - return (OK); -} - -/* Initialze memory for the list of all vectors in the current plot. - Add a standard vector to this plot */ -static int -addDataDesc(runDesc *run, char *name, int type, int ind, int meminit) -{ - dataDesc *data; - - /* initialize memory (for all vectors or given by 'save') */ - if (!run->numData) - { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - /* If there is need for more memory */ - else if (run->numData == run->maxData) - { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); - } - - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); - - data->name = copy(name); - data->type = type; - data->gtype = GRID_LIN; - data->regular = TRUE; - data->outIndex = ind; - - /* It's the reference vector. */ - if (ind == -1) - run->refIndex = run->numData; - - run->numData++; - - return (OK); -} - -/* Initialze memory for the list of all vectors in the current plot. - Add a special vector (e.g. @q1[ib]) to this plot */ -static int -addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit) -{ - dataDesc *data; - char *unique, *freeunique; /* unique char * from back-end */ - int ret; - - if (!run->numData) - { - /* even if input 0, do a malloc */ - run->data = TMALLOC(dataDesc, ++meminit); - run->maxData = meminit; - } - else if (run->numData == run->maxData) - { - run->maxData = (int)(run->maxData * 1.1) + 1; - run->data = TREALLOC(dataDesc, run->data, run->maxData); - } - - data = &run->data[run->numData]; - /* so freeRun will get nice NULL pointers for the fields we don't set */ - memset(data, 0, sizeof(dataDesc)); - - data->name = copy(name); - - freeunique = unique = copy(devname); - - /* unique will be overridden, if it already exists */ - ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); - data->specName = unique; - - if (ret == E_EXISTS) - tfree(freeunique); - - data->specParamName = copy(param); - - data->specIndex = depind; - data->specType = -1; - data->specFast = NULL; - data->regular = FALSE; - - run->numData++; - - return (OK); -} - -static void -OUTpD_memory(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i, n = run->numData; - - for (i = 0; i < n; i++) - { - - dataDesc *d; - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); -#endif - - d = &run->data[i]; - - if (d->outIndex == -1) - { - if (d->type == IF_REAL) - plotAddRealValue(d, refValue->rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, refValue->cValue); - } - else if (d->regular) - { - if (d->type == IF_REAL) - plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); - } - else - { - IFvalue val; - - /* should pre-check instance */ - if (!getSpecial(d, run, &val)) - continue; - - if (d->type == IF_REAL) - plotAddRealValue(d, val.rValue); - else if (d->type == IF_COMPLEX) - plotAddComplexValue(d, val.cValue); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, d->vec); -#endif - } -} - -int OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) -{ - runDesc *run = plotPtr; // FIXME - int i; - - run->pointCount++; - -#ifdef TCL_MODULE - steps_completed = run->pointCount; -#endif - /* interpolated batch mode output to file in transient analysis */ - if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) - { - InterpFileAdd(run, refValue, valuePtr); - return (OK); - } - /* interpolated interactive or control mode output to plot in transient analysis */ - else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) - { - InterpPlotAdd(run, refValue, valuePtr); - return (OK); - } - /* standard batch mode output to file */ - else if (run->writeOut) - { - - if (run->pointCount == 1) - fileInit_pass2(run); - - fileStartPoint(run->fp, run->binary, run->pointCount); - - if (run->refIndex != -1) - { - if (run->isComplex) - { - fileAddComplexValue(run->fp, run->binary, refValue->cValue); - - /* While we're looking at the reference value, print it to the screen - every quarter of a second, to give some feedback without using - too much CPU time */ -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->cValue.real); - lastclock = currclock; - } - } -#endif - } - else - { - - /* And the same for a non-complex value */ - - fileAddRealValue(run->fp, run->binary, refValue->rValue); -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - } - } - - for (i = 0; i < run->numData; i++) - { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; - -#ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); -#endif - - if (run->data[i].regular) - { - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, - valuePtr->v.vec.rVec[run->data[i].outIndex]); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, - valuePtr->v.vec.cVec[run->data[i].outIndex]); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - { - - /* If this is the first data point, print a warning for any unrecognized - variables, since this has not already been checked */ - - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); - - if (run->isComplex) - { - val.cValue.real = 0; - val.cValue.imag = 0; - fileAddComplexValue(run->fp, run->binary, val.cValue); - } - else - { - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); - } - - continue; - } - - if (run->data[i].type == IF_REAL) - fileAddRealValue(run->fp, run->binary, val.rValue); - else if (run->data[i].type == IF_COMPLEX) - fileAddComplexValue(run->fp, run->binary, val.cValue); - else - fprintf(stderr, "OUTpData: unsupported data type\n"); - } - -#ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); -#endif - } - - fileEndPoint(run->fp, run->binary); - - /* Check that the write to disk completed successfully, otherwise abort */ - - if (ferror(run->fp)) - { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; - } - } - else - { - - OUTpD_memory(run, refValue, valuePtr); - - /* This is interactive mode. Update the screen with the reference - variable just the same */ - -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - if (run->isComplex) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->cValue.real : NAN); - } - else - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue ? refValue->rValue : NAN); - } - lastclock = currclock; - } - } -#endif - - gr_iplot(run->runPlot); - } - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - - return (OK); -} - -int OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) -{ - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(plotPtr); - - return (OK); -} - -int OUTwData(runDesc *plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) -{ - NG_IGNORE(refPtr); - NG_IGNORE(valuePtr); - NG_IGNORE(dataIndex); - NG_IGNORE(plotPtr); - - return (OK); -} - -int OUTwEnd(runDesc *plotPtr) -{ - NG_IGNORE(plotPtr); - - return (OK); -} - -int OUTendPlot(runDesc *plotPtr) -{ - if (plotPtr->writeOut) - { - fileEnd(plotPtr); - } - else - { - gr_end_iplot(); - plotEnd(plotPtr); - } - - tfree(valueold); - tfree(valuenew); - - freeRun(plotPtr); - - return (OK); -} - -int OUTbeginDomain(runDesc *plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) -{ - NG_IGNORE(outerRefValue); - NG_IGNORE(refType); - NG_IGNORE(refName); - NG_IGNORE(plotPtr); - - return (OK); -} - -int OUTendDomain(runDesc *plotPtr) -{ - NG_IGNORE(plotPtr); - - return (OK); -} - -int OUTattributes(runDesc *plotPtr, IFuid varName, int param, IFvalue *value) -{ - runDesc *run = plotPtr; // FIXME - GRIDTYPE type; - - struct dvec *d; - - NG_IGNORE(value); - - if (param == OUT_SCALE_LIN) - type = GRID_LIN; - else if (param == OUT_SCALE_LOG) - type = GRID_XLOG; - else - return E_UNSUPP; - - if (run->writeOut) - { - if (varName) - { - int i; - for (i = 0; i < run->numData; i++) - if (!strcmp(varName, run->data[i].name)) - run->data[i].gtype = type; - } - else - { - run->data[run->refIndex].gtype = type; - } - } - else - { - if (varName) - { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - if (!strcmp(varName, d->v_name)) - d->v_gridtype = type; - } - else if (param == PLOT_COMB) - { - for (d = run->runPlot->pl_dvecs; d; d = d->v_next) - d->v_plottype = PLOT_COMB; - } - else - { - run->runPlot->pl_scale->v_gridtype = type; - } - } - - return (OK); -} - -/* The file writing routines. */ - -static void -fileInit(runDesc *run) -{ - char buf[513]; - int i; - size_t n; - - lastclock = clock(); - - /* This is a hack. */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - n = 0; - sprintf(buf, "Title: %s\n", run->name); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Date: %s\n", datestring()); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Plotname: %s\n", run->type); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Variables: %d\n", run->numData); - n += strlen(buf); - fputs(buf, run->fp); - sprintf(buf, "No. Points: "); - n += strlen(buf); - fputs(buf, run->fp); - - fflush(run->fp); /* Gotta do this for LATTICE. */ - if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) - run->pointPos = (long)n; - fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ - - /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ - fprintf(run->fp, "Variables:\n"); - - printf("No. of Data Columns : %d \n", run->numData); -} - -static int -guess_type(const char *name) -{ - int type; - - if (substring("#branch", name)) - type = SV_CURRENT; - else if (cieq(name, "time")) - type = SV_TIME; - else if (cieq(name, "frequency")) - type = SV_FREQUENCY; - else if (ciprefix("inoise", name)) - type = fixme_inoise_type; - else if (ciprefix("onoise", name)) - type = fixme_onoise_type; - else if (cieq(name, "temp-sweep")) - type = SV_TEMP; - else if (cieq(name, "res-sweep")) - type = SV_RES; - else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ - type = SV_ADMITTANCE; - else if ((*name == '@') && substring("[c", name)) - type = SV_CAPACITANCE; - else if ((*name == '@') && substring("[i", name)) - type = SV_CURRENT; - else if ((*name == '@') && substring("[q", name)) - type = SV_CHARGE; - else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ - type = SV_POWER; - else - type = SV_VOLTAGE; - - return type; -} - -static void -fileInit_pass2(runDesc *run) -{ - int i, type; - - for (i = 0; i < run->numData; i++) - { - - char *name = run->data[i].name; - - type = guess_type(name); - - if (type == SV_CURRENT) - { - char *branch = strstr(name, "#branch"); - if (branch) - *branch = '\0'; - fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); - if (branch) - *branch = '#'; - } - else if (type == SV_VOLTAGE) - { - fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); - } - else - { - fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); - } - - if (run->data[i].gtype == GRID_XLOG) - fprintf(run->fp, "\tgrid=3"); - - fprintf(run->fp, "\n"); - } - - fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); - fflush(run->fp); - - /* Allocate Row buffer */ - - if (run->binary) - { - rowbuflen = (size_t)(run->numData); - if (run->isComplex) - rowbuflen *= 2; - rowbuf = TMALLOC(double, rowbuflen); - } - else - { - rowbuflen = 0; - rowbuf = NULL; - } -} - -static void -fileStartPoint(FILE *fp, bool bin, int num) -{ - if (!bin) - fprintf(fp, "%d\t", num - 1); - - /* reset buffer pointer to zero */ - - column = 0; -} - -static void -fileAddRealValue(FILE *fp, bool bin, double value) -{ - if (bin) - rowbuf[column++] = value; - else - fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); -} - -static void -fileAddComplexValue(FILE *fp, bool bin, IFcomplex value) -{ - if (bin) - { - rowbuf[column++] = value.real; - rowbuf[column++] = value.imag; - } - else - { - fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, - DOUBLE_PRECISION, value.imag); - } -} - -static void -fileEndPoint(FILE *fp, bool bin) -{ - /* write row buffer to file */ - /* otherwise the data has already been written */ - - if (bin) - fwrite(rowbuf, sizeof(double), rowbuflen, fp); -} - -/* Here's the hack... Run back and fill in the number of points. */ - -static void -fileEnd(runDesc *run) -{ - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any arefound, force them to exit.*/ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - - /* 28.May.2020 - BM - Patch for closing ghdlserver */ - close_server(); - /* End 28.May.2020 */ - - if (run->fp != stdout) - { - long place = ftell(run->fp); - fseek(run->fp, run->pointPos, SEEK_SET); - fprintf(run->fp, "%d", run->pointCount); - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); - fseek(run->fp, place, SEEK_SET); - } - else - { - /* Yet another hack-around */ - fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); - } - - fflush(run->fp); - - tfree(rowbuf); -} - -/* The plot maintenance routines. */ - -static void -plotInit(runDesc *run) -{ - struct plot *pl = plot_alloc(run->type); - struct dvec *v; - int i; - - pl->pl_title = copy(run->name); - pl->pl_name = copy(run->type); - pl->pl_date = copy(datestring()); - pl->pl_ndims = 0; - plot_new(pl); - plot_setcur(pl->pl_typename); - run->runPlot = pl; - - /* This is a hack. */ - /* if any of them complex, make them all complex */ - run->isComplex = FALSE; - for (i = 0; i < run->numData; i++) - if (run->data[i].type == IF_COMPLEX) - run->isComplex = TRUE; - - for (i = 0; i < run->numData; i++) - { - dataDesc *dd = &run->data[i]; - char *name; - - if (isdigit_c(dd->name[0])) - name = tprintf("V(%s)", dd->name); - else - name = copy(dd->name); - - v = dvec_alloc(name, - guess_type(name), - run->isComplex - ? (VF_COMPLEX | VF_PERMANENT) - : (VF_REAL | VF_PERMANENT), - 0, NULL); - - vec_new(v); - dd->vec = v; - } -} - -/* prepare the vector length data for memory allocation - If new, and tran or pss, length is TSTOP / TSTEP plus some margin. - If allocated length is exceeded, check progress. When > 20% then extrapolate memory needed, - if less than 20% then just double the size. - If not tran or pss, return fixed value (1024) of memory to be added. - */ -static inline int -vlength2delta(int len) -{ -#ifdef SHARED_MODULE - if (savenone) - /* We need just a vector length of 1 */ - return 1; -#endif - /* TSTOP / TSTEP */ - int points = ft_curckt->ci_ckt->CKTtimeListSize; - /* transient and pss analysis (points > 0) upon start */ - if (len == 0 && points > 0) - { - /* number of timesteps plus some overhead */ - return points + 100; - } - /* transient and pss if original estimate is exceeded */ - else if (points > 0) - { - /* check where we are */ - double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; - /* return an estimate of the appropriate number of time points, if more than 20% of - the anticipated total time has passed */ - if (timerel > 0.2) - return (int)(len / timerel) - len + 1; - /* If not, just double the available memory */ - else - return len; - } - /* other analysis types that do not set CKTtimeListSize */ - else - return 1024; -} - -static void -plotAddRealValue(dataDesc *desc, double value) -{ - struct dvec *v = desc->vec; - -#ifdef SHARED_MODULE - if (savenone) - /* always save new data to same location */ - v->v_length = 0; -#endif - - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - if (isreal(v)) - { - v->v_realdata[v->v_length] = value; - } - else - { - /* a real parading as a VF_COMPLEX */ - v->v_compdata[v->v_length].cx_real = value; - v->v_compdata[v->v_length].cx_imag = 0.0; - } - - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ -} - -static void -plotAddComplexValue(dataDesc *desc, IFcomplex value) -{ - struct dvec *v = desc->vec; - -#ifdef SHARED_MODULE - if (savenone) - v->v_length = 0; -#endif - - if (v->v_length >= v->v_alloc_length) - dvec_extend(v, v->v_length + vlength2delta(v->v_length)); - - v->v_compdata[v->v_length].cx_real = value.real; - v->v_compdata[v->v_length].cx_imag = value.imag; - - v->v_length++; - v->v_dims[0] = v->v_length; /* va, must be updated */ -} - -static void -plotEnd(runDesc *run) -{ - /* 10.Mar.2017 - RM - Check if any orphan test benches are running. If any are*/ - //nghdl_orphan_tb(); - /* End 10.Mar.2017 */ - - /* 28.May.2020 - BM - Patch for closing ghdlserver */ - close_server(); - /* End 28.May.2020 */ - - fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); -} - -/* ParseSpecial takes something of the form "@name[param,index]" and rips - * out name, param, andstrchr. - */ - -static bool -parseSpecial(char *name, char *dev, char *param, char *ind) -{ - char *s; - - *dev = *param = *ind = '\0'; - - if (*name != '@') - return FALSE; - name++; - - s = dev; - while (*name && (*name != '[')) - *s++ = *name++; - *s = '\0'; - - if (!*name) - return TRUE; - name++; - - s = param; - while (*name && (*name != ',') && (*name != ']')) - *s++ = *name++; - *s = '\0'; - - if (*name == ']') - return (!name[1] ? TRUE : FALSE); - else if (!*name) - return FALSE; - name++; - - s = ind; - while (*name && (*name != ']')) - *s++ = *name++; - *s = '\0'; - - if (*name && !name[1]) - return TRUE; - else - return FALSE; -} - -/* This routine must match two names with or without a V() around them. */ - -static bool -name_eq(char *n1, char *n2) -{ - char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; - - if ((s = strchr(n1, '(')) != NULL) - { - strcpy(buf1, s); - if ((s = strchr(buf1, ')')) == NULL) - return FALSE; - *s = '\0'; - n1 = buf1; - } - - if ((s = strchr(n2, '(')) != NULL) - { - strcpy(buf2, s); - if ((s = strchr(buf2, ')')) == NULL) - return FALSE; - *s = '\0'; - n2 = buf2; - } - - return (strcmp(n1, n2) ? FALSE : TRUE); -} - -static bool -getSpecial(dataDesc *desc, runDesc *run, IFvalue *val) -{ - IFvalue selector; - struct variable *vv; - - selector.iValue = desc->specIndex; - if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, - desc->specName, &desc->specFast, ft_sim, &desc->type, - &selector) == OK) - { - desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ - return TRUE; - } - - if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) - { - /* skip @ sign */ - desc->type = IF_REAL; - if (vv->va_type == CP_REAL) - val->rValue = vv->va_real; - else if (vv->va_type == CP_NUM) - val->rValue = vv->va_num; - else if (vv->va_type == CP_BOOL) - val->rValue = (vv->va_bool ? 1.0 : 0.0); - else - return FALSE; /* not a real */ - tfree(vv); - return TRUE; - } - - return FALSE; -} - -static void -freeRun(runDesc *run) -{ - int i; - - for (i = 0; i < run->numData; i++) - { - tfree(run->data[i].name); - tfree(run->data[i].specParamName); - } - - tfree(run->data); - tfree(run->type); - tfree(run->name); - - tfree(run); -} - -int OUTstopnow(void) -{ - if (ft_intrpt || shouldstop) - { - ft_intrpt = shouldstop = FALSE; - return (1); - } - - return (0); -} - -/* Print out error messages. */ - -static struct mesg -{ - char *string; - long flag; -} msgs[] = { - {"Warning", ERR_WARNING}, - {"Fatal error", ERR_FATAL}, - {"Panic", ERR_PANIC}, - {"Note", ERR_INFO}, - {NULL, 0}}; - -void OUTerror(int flags, char *format, IFuid *names) -{ - struct mesg *m; - char buf[BSIZE_SP], *s, *bptr; - int nindex = 0; - - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; - - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); - - for (s = format, bptr = buf; *s; s++) - { - if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') - { - if (names[nindex]) - strcpy(bptr, names[nindex]); - else - strcpy(bptr, "(null)"); - bptr += strlen(bptr); - s++; - nindex++; - } - else - { - *bptr++ = *s; - } - } - - *bptr = '\0'; - fprintf(cp_err, "%s\n", buf); - fflush(cp_err); -} - -void OUTerrorf(int flags, const char *format, ...) -{ - struct mesg *m; - va_list args; - - if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) - return; - - for (m = msgs; m->flag; m++) - if (flags & m->flag) - fprintf(cp_err, "%s: ", m->string); - - va_start(args, format); - - vfprintf(cp_err, format, args); - fputc('\n', cp_err); - - fflush(cp_err); - - va_end(args); -} - -static int -InterpFileAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; - - if (run->pointCount == 1) - { - fileInit_pass2(run); - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - } - - if (run->refIndex != -1) - { - /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); - interpolatenow = nodata = FALSE; - } - /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); - interpolatenow = nodata = FALSE; - } - /* Save exact point */ - else if (refValue->rValue == timestep) - { - timeold = refValue->rValue; - fileStartPoint(run->fp, run->binary, run->pointCount); - fileAddRealValue(run->fp, run->binary, timestep); - timestep += run->circuit->CKTstep; - interpolatenow = nodata = FALSE; - } - else if (refValue->rValue > timestep) - { - /* add the next time step value to the vector */ - fileStartPoint(run->fp, run->binary, run->pointCount); - timenew = refValue->rValue; - fileAddRealValue(run->fp, run->binary, timestep); - timestep += run->circuit->CKTstep; - nodata = FALSE; - interpolatenow = TRUE; - } - else - { - /* Do not save this step */ - run->pointCount--; - timeold = refValue->rValue; - nodata = TRUE; - interpolatenow = FALSE; - } -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - } - - for (i = 0; i < run->numData; i++) - { - /* we've already printed reference vec first */ - if (run->data[i].outIndex == -1) - continue; - -#ifdef TCL_MODULE - blt_add(i, refValue ? refValue->rValue : NAN); -#endif - - if (run->data[i].regular) - { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - { - - /* If this is the first data point, print a warning for any unrecognized - variables, since this has not already been checked */ - if (run->pointCount == 1) - fprintf(stderr, "Warning: unrecognized variable - %s\n", - run->data[i].name); - val.rValue = 0; - fileAddRealValue(run->fp, run->binary, val.rValue); - continue; - } - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = val.rValue; - fileAddRealValue(run->fp, run->binary, valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - fileAddRealValue(run->fp, run->binary, newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = val.rValue; - } - -#ifdef TCL_MODULE - blt_add(i, valuePtr->v.vec.rVec[run->data[i].outIndex]); -#endif - } - - fileEndPoint(run->fp, run->binary); - - /* Check that the write to disk completed successfully, otherwise abort */ - if (ferror(run->fp)) - { - fprintf(stderr, "Warning: rawfile write error !!\n"); - shouldstop = TRUE; - } - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - return (OK); -} - -static int -InterpPlotAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) -{ - int i, iscale = -1; - static double timeold = 0.0, timenew = 0.0, timestep = 0.0; - bool nodata = FALSE; - bool interpolatenow = FALSE; - - if (run->pointCount == 1) - timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; - - /* find the scale vector */ - for (i = 0; i < run->numData; i++) - if (run->data[i].outIndex == -1) - { - iscale = i; - break; - } - if (iscale == -1) - fprintf(stderr, "Error: no scale vector found\n"); - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(iscale); -#endif - - /* Save first time step */ - if (refValue->rValue == run->circuit->CKTinitTime) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], refValue->rValue); - interpolatenow = nodata = FALSE; - } - /* Save last time step */ - else if (refValue->rValue == run->circuit->CKTfinalTime) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); - interpolatenow = nodata = FALSE; - } - /* Save exact point */ - else if (refValue->rValue == timestep) - { - timeold = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - interpolatenow = nodata = FALSE; - } - else if (refValue->rValue > timestep) - { - /* add the next time step value to the vector */ - timenew = refValue->rValue; - plotAddRealValue(&run->data[iscale], timestep); - timestep += run->circuit->CKTstep; - nodata = FALSE; - interpolatenow = TRUE; - } - else - { - /* Do not save this step */ - run->pointCount--; - timeold = refValue->rValue; - nodata = TRUE; - interpolatenow = FALSE; - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(iscale, (run->data[iscale]).vec); -#endif - -#ifndef HAS_WINGUI - if (!orflag && !ft_norefprint) - { - currclock = clock(); - if ((currclock - lastclock) > (0.25 * CLOCKS_PER_SEC)) - { - fprintf(stderr, " Reference value : % 12.5e\r", - refValue->rValue); - lastclock = currclock; - } - } -#endif - - for (i = 0; i < run->numData; i++) - { - if (i == iscale) - continue; - -#ifdef TCL_MODULE - /*Locks the blt vector to stop access*/ - blt_lockvec(i); -#endif - - if (run->data[i].regular) - { - /* Store value or interpolate and store or do not store any value to file */ - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = valuePtr->v.vec.rVec[run->data[i].outIndex]; - } - else - { - IFvalue val; - /* should pre-check instance */ - if (!getSpecial(&run->data[i], run, &val)) - continue; - if (!interpolatenow && !nodata) - { - /* store the first or last value */ - valueold[i] = val.rValue; - plotAddRealValue(&run->data[i], valueold[i]); - } - else if (interpolatenow) - { - /* Interpolate time if actual time is greater than proposed next time step */ - double newval; - valuenew[i] = val.rValue; - newval = (timestep - run->circuit->CKTstep - timeold) / (timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; - plotAddRealValue(&run->data[i], newval); - valueold[i] = valuenew[i]; - } - else if (nodata) - /* Just keep the transient output value corresponding to timeold, - but do not store to file */ - valueold[i] = val.rValue; - } - -#ifdef TCL_MODULE - /*relinks and unlocks vector*/ - blt_relink(i, (run->data[i]).vec); -#endif - } - - gr_iplot(run->runPlot); - - if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) - shouldstop = TRUE; - -#ifdef TCL_MODULE - Tcl_ExecutePerLoop(); -#elif defined SHARED_MODULE - sh_ExecutePerLoop(); -#endif - - return (OK); -} +/********** +Copyright 1990 Regents of the University of California. All rights reserved. +Author: 1988 Wayne A. Christopher, U. C. Berkeley CAD Group +Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski +**********/ +/* + * This module replaces the old "writedata" routines in nutmeg. + * Unlike the writedata routines, the OUT routines are only called by + * the simulator routines, and only call routines in nutmeg. The rest + * of nutmeg doesn't deal with OUT at all. + */ + +/************************************************************************** + * 08.June.2020 - RP, BM - Added OS (Windows and Linux) dependent + * preprocessors and sockets + ************************************************************************** + * 29.May.2020 - RP, BM - Read all the IPs and ports from NGHDL_COMMON_IP + * file from /tmp folder. It connects to each of the ghdlserver and sends + * CLOSE_FROM_NGSPICE message to terminate themselves + **************************************************************************/ + +#include "ngspice/ngspice.h" + +/*05.June.2020 - BM - Added follwing includes for Windows OS */ +#ifdef _WIN32 + #undef BOOLEAN /* Undefine it due to conflicting definitions in Windows OS */ + + #include + #include +#endif + +#include "ngspice/cpdefs.h" +#include "ngspice/ftedefs.h" +#include "ngspice/dvec.h" +#include "ngspice/plot.h" +#include "ngspice/sim.h" +#include "ngspice/inpdefs.h" /* for INPtables */ +#include "ngspice/ifsim.h" +#include "ngspice/jobdefs.h" +#include "ngspice/iferrmsg.h" +#include "circuits.h" +#include "outitf.h" +#include "variable.h" +#include "ngspice/cktdefs.h" +#include "ngspice/inpdefs.h" +#include "breakp2.h" +#include "runcoms.h" +#include "plotting/graf.h" +#include "../misc/misc_time.h" + +/* 10.Mar.2917 - RM - Added the following #include */ +#include +#include +#include +#include +#include +#include + +/* 27.May.2020 - BM - Added the following #include */ +#ifdef __linux__ + #include + #include + #include + #include +#endif + +extern char *spice_analysis_get_name(int index); +extern char *spice_analysis_get_description(int index); + + +static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, + char *refName, int refType, int numNames, char **dataNames, int dataType, + bool windowed, runDesc **runp); +static int addDataDesc(runDesc *run, char *name, int type, int ind, int meminit); +static int addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit); +static void fileInit(runDesc *run); +static void fileInit_pass2(runDesc *run); +static void fileStartPoint(FILE *fp, bool bin, int num); +static void fileAddRealValue(FILE *fp, bool bin, double value); +static void fileAddComplexValue(FILE *fp, bool bin, IFcomplex value); +static void fileEndPoint(FILE *fp, bool bin); +static void fileEnd(runDesc *run); +static void plotInit(runDesc *run); +static void plotAddRealValue(dataDesc *desc, double value); +static void plotAddComplexValue(dataDesc *desc, IFcomplex value); +static void plotEnd(runDesc *run); +static bool parseSpecial(char *name, char *dev, char *param, char *ind); +static bool name_eq(char *n1, char *n2); +static bool getSpecial(dataDesc *desc, runDesc *run, IFvalue *val); +static void freeRun(runDesc *run); +static int InterpFileAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); +static int InterpPlotAdd(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr); + +/*Output data to spice module*/ +#ifdef TCL_MODULE +#include "ngspice/tclspice.h" +#elif defined SHARED_MODULE +extern int sh_ExecutePerLoop(void); +extern void sh_vecinit(runDesc *run); +#endif + +/*Suppressing progress info in -o option */ +#ifndef HAS_WINGUI +extern bool orflag; +#endif + +// fixme +// ugly hack to work around missing api to specify the "type" of signals +int fixme_onoise_type = SV_NOTYPE; +int fixme_inoise_type = SV_NOTYPE; + +#define DOUBLE_PRECISION 15 + +static clock_t lastclock, currclock; +static double *rowbuf; +static size_t column, rowbuflen; + +static bool shouldstop = FALSE; /* Tell simulator to stop next time it asks. */ + +static bool interpolated = FALSE; +static double *valueold, *valuenew; + +#ifdef SHARED_MODULE +static bool savenone = FALSE; +#endif + + +/* 28.May.2020 - RP, BM - Closing the GHDL server after simulation is over */ +static void close_server() +{ + FILE *fptr; + char ip_filename[48]; + + #ifdef __linux__ + sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); + #elif _WIN32 + WSADATA WSAData; + SOCKADDR_IN addr; + WSAStartup(MAKEWORD(2, 2), &WSAData); + sprintf(ip_filename, "C:\\Windows\\Temp\\NGHDL_COMMON_IP_%d.txt", getpid()); + #endif + + fptr = fopen(ip_filename, "r"); + + if(fptr) + { + char server_ip[20], *message = "CLOSE_FROM_NGSPICE"; + int port = -1, sock = -1, try_limit = 0, skip_flag = 0; + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + + /* scan server ip and port to send close message */ + while(fscanf(fptr, "%s %d\n", server_ip, &port) == 2) + { + /* Create socket descriptor */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Socket Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + serv_addr.sin_port = htons(port); + serv_addr.sin_addr.s_addr = inet_addr(server_ip); + + /* connect with the server */ + try_limit = 10, skip_flag = 0; + while(try_limit > 0) + { + if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + sleep(0.2); + try_limit--; + if(try_limit == 0) + { + perror("\nClient Termination - Connection Failed: "); + skip_flag = 1; + } + } + else + break; + } + + if (skip_flag) + continue; + + /* send close message to the server */ + #ifdef __linux__ + send(sock, message, strlen(message), 0); + close(sock); + #elif _WIN32 + send(sock, message, strlen(message) + 1, 0); + closesocket(sock); + #endif + } + } + + #ifdef _WIN32 + WSACleanup(); + #endif + fclose(fptr); + remove(ip_filename); +} + + +// The two "begin plot" routines share all their internals... + +int +OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) +{ + char *name; + + if (ft_curckt->ci_ckt == circuitPtr) + name = ft_curckt->ci_name; + else + name = "circuit name"; + + return (beginPlot(analysisPtr, circuitPtr, name, + analName, refName, refType, numNames, + dataNames, dataType, FALSE, + plotPtr)); +} + + +int +OUTwBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, + IFuid analName, + IFuid refName, int refType, + int numNames, IFuid *dataNames, int dataType, runDesc **plotPtr) +{ + + return (beginPlot(analysisPtr, circuitPtr, "circuit name", + analName, refName, refType, numNames, + dataNames, dataType, TRUE, + plotPtr)); +} + + +static int +beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp) +{ + runDesc *run; + struct save_info *saves; + bool *savesused = NULL; + int numsaves; + int i, j, depind = 0; + char namebuf[BSIZE_SP], parambuf[BSIZE_SP], depbuf[BSIZE_SP]; + char *ch, tmpname[BSIZE_SP]; + bool saveall = TRUE; + bool savealli = FALSE; + char *an_name; + int initmem; + /*to resume a run saj + *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) + */ + + if (dataType == 666 && numNames == 666) { + run = *runp; + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); + + } else { + /*end saj*/ + + /* Check to see if we want to print informational data. */ + if (cp_getvar("printinfo", CP_BOOL, NULL, 0)) + fprintf(cp_err, "(debug printing enabled)\n"); + + /* Check to see if we want to save only interpolated data. */ + if (cp_getvar("interp", CP_BOOL, NULL, 0)) { + interpolated = TRUE; + fprintf(cp_out, "Warning: Interpolated raw file data!\n\n"); + } + + *runp = run = TMALLOC(struct runDesc, 1); + + /* First fill in some general information. */ + run->analysis = analysisPtr; + run->circuit = circuitPtr; + run->name = copy(cktName); + run->type = copy(analName); + run->windowed = windowed; + run->numData = 0; + + an_name = spice_analysis_get_name(analysisPtr->JOBtype); + ft_curckt->ci_last_an = an_name; + + /* Now let's see which of these things we need. First toss in the + * reference vector. Then toss in anything that getSaves() tells + * us to save that we can find in the name list. Finally unpack + * the remaining saves into parameters. + */ + numsaves = ft_getSaves(&saves); + if (numsaves) { + savesused = TMALLOC(bool, numsaves); + saveall = FALSE; + for (i = 0; i < numsaves; i++) { + if (saves[i].analysis && !cieq(saves[i].analysis, an_name)) { + /* ignore this one this time around */ + savesused[i] = TRUE; + continue; + } + + /* Check for ".save all" and new synonym ".save allv" */ + + if (cieq(saves[i].name, "all") || cieq(saves[i].name, "allv")) { + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } + + /* And now for the new ".save alli" option */ + + if (cieq(saves[i].name, "alli")) { + savealli = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } +#ifdef SHARED_MODULE + /* this may happen if shared ngspice*/ + if (cieq(saves[i].name, "none")) { + savenone = TRUE; + saveall = TRUE; + savesused[i] = TRUE; + saves[i].used = 1; + continue; + } +#endif + } + } + + if (numsaves && !saveall) + initmem = numsaves; + else + initmem = numNames; + + /* Pass 0. */ + if (refName) { + addDataDesc(run, refName, refType, -1, initmem); + for (i = 0; i < numsaves; i++) + if (!savesused[i] && name_eq(saves[i].name, refName)) { + savesused[i] = TRUE; + saves[i].used = 1; + } + } else { + run->refIndex = -1; + } + + /* Pass 1. */ + if (numsaves && !saveall) { + for (i = 0; i < numsaves; i++) + if (!savesused[i]) + for (j = 0; j < numNames; j++) + if (name_eq(saves[i].name, dataNames[j])) { + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + break; + } + } else { + for (i = 0; i < numNames; i++) + if (!refName || !name_eq(dataNames[i], refName)) + /* Save the node as long as it's an internal device node */ + if (!strstr(dataNames[i], "#internal") && + !strstr(dataNames[i], "#source") && + !strstr(dataNames[i], "#drain") && + !strstr(dataNames[i], "#collector") && + !strstr(dataNames[i], "#emitter") && + !strstr(dataNames[i], "#base")) + { + addDataDesc(run, dataNames[i], dataType, i, initmem); + } + } + + /* Pass 1 and a bit. + This is a new pass which searches for all the internal device + nodes, and saves the terminal currents instead */ + + if (savealli) { + depind = 0; + for (i = 0; i < numNames; i++) { + if (strstr(dataNames[i], "#internal") || + strstr(dataNames[i], "#source") || + strstr(dataNames[i], "#drain") || + strstr(dataNames[i], "#collector") || + strstr(dataNames[i], "#emitter") || + strstr(dataNames[i], "#base")) + { + tmpname[0] = '@'; + tmpname[1] = '\0'; + strncat(tmpname, dataNames[i], BSIZE_SP-1); + ch = strchr(tmpname, '#'); + + if (strstr(ch, "#collector")) { + strcpy(ch, "[ic]"); + } else if (strstr(ch, "#base")) { + strcpy(ch, "[ib]"); + } else if (strstr(ch, "#emitter")) { + strcpy(ch, "[ie]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[is]"); + } else if (strstr(ch, "#drain")) { + strcpy(ch, "[id]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ig]"); + } else if (strstr(ch, "#source")) { + strcpy(ch, "[is]"); + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + strcpy(ch, "[ib]"); + } else if (strstr(ch, "#internal") && (tmpname[1] == 'd')) { + strcpy(ch, "[id]"); + } else { + fprintf(cp_err, + "Debug: could output current for %s\n", tmpname); + continue; + } + if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) { + if (*depbuf) { + fprintf(stderr, + "Warning : unexpected dependent variable on %s\n", tmpname); + } else { + addSpecialDesc(run, tmpname, namebuf, parambuf, depind, initmem); + } + } + } + } + } + + /* Pass 2. */ + for (i = 0; i < numsaves; i++) { + + if (savesused[i]) + continue; + + if (!parseSpecial(saves[i].name, namebuf, parambuf, depbuf)) { + if (saves[i].analysis) + fprintf(cp_err, "Warning: can't parse '%s': ignored\n", + saves[i].name); + continue; + } + + /* Now, if there's a dep variable, do we already have it? */ + if (*depbuf) { + for (j = 0; j < run->numData; j++) + if (name_eq(depbuf, run->data[j].name)) + break; + if (j == run->numData) { + /* Better add it. */ + for (j = 0; j < numNames; j++) + if (name_eq(depbuf, dataNames[j])) + break; + if (j == numNames) { + fprintf(cp_err, + "Warning: can't find '%s': value '%s' ignored\n", + depbuf, saves[i].name); + continue; + } + addDataDesc(run, dataNames[j], dataType, j, initmem); + savesused[i] = TRUE; + saves[i].used = 1; + depind = j; + } else { + depind = run->data[j].outIndex; + } + } + + addSpecialDesc(run, saves[i].name, namebuf, parambuf, depind, initmem); + } + + if (numsaves) { + for (i = 0; i < numsaves; i++) { + tfree(saves[i].analysis); + tfree(saves[i].name); + } + tfree(saves); + tfree(savesused); + } + + if (numNames && + ((run->numData == 1 && run->refIndex != -1) || + (run->numData == 0 && run->refIndex == -1))) + { + fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", + spice_analysis_get_description(analysisPtr->JOBtype)); + return E_NOTFOUND; + } + + /* Now that we have our own data structures built up, let's see what + * nutmeg wants us to do. + */ + run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, + run->type, run->name); + + if (run->writeOut) { + fileInit(run); + } else { + plotInit(run); + if (refName) + run->runPlot->pl_ndims = 1; + } + } + + /* define storage for old and new data, to allow interpolation */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4) { + valueold = TMALLOC(double, run->numData); + for (i = 0; i < run->numData; i++) + valueold[i] = 0.0; + valuenew = TMALLOC(double, run->numData); + } + + /*Start BLT, initilises the blt vectors saj*/ +#ifdef TCL_MODULE + blt_init(run); +#elif defined SHARED_MODULE + sh_vecinit(run); +#endif + + return (OK); +} + +/* Initialze memory for the list of all vectors in the current plot. + Add a standard vector to this plot */ +static int +addDataDesc(runDesc *run, char *name, int type, int ind, int meminit) +{ + dataDesc *data; + + /* initialize memory (for all vectors or given by 'save') */ + if (!run->numData) { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + /* If there is need for more memory */ + else if (run->numData == run->maxData) { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } + + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); + + data->name = copy(name); + data->type = type; + data->gtype = GRID_LIN; + data->regular = TRUE; + data->outIndex = ind; + + /* It's the reference vector. */ + if (ind == -1) + run->refIndex = run->numData; + + run->numData++; + + return (OK); +} + +/* Initialze memory for the list of all vectors in the current plot. + Add a special vector (e.g. @q1[ib]) to this plot */ +static int +addSpecialDesc(runDesc *run, char *name, char *devname, char *param, int depind, int meminit) +{ + dataDesc *data; + char *unique, *freeunique; /* unique char * from back-end */ + int ret; + + if (!run->numData) { + /* even if input 0, do a malloc */ + run->data = TMALLOC(dataDesc, ++meminit); + run->maxData = meminit; + } + else if (run->numData == run->maxData) { + run->maxData = (int)(run->maxData * 1.1) + 1; + run->data = TREALLOC(dataDesc, run->data, run->maxData); + } + + data = &run->data[run->numData]; + /* so freeRun will get nice NULL pointers for the fields we don't set */ + memset(data, 0, sizeof(dataDesc)); + + data->name = copy(name); + + freeunique = unique = copy(devname); + + /* unique will be overridden, if it already exists */ + ret = INPinsertNofree(&unique, ft_curckt->ci_symtab); + data->specName = unique; + + if (ret == E_EXISTS) + tfree(freeunique); + + data->specParamName = copy(param); + + data->specIndex = depind; + data->specType = -1; + data->specFast = NULL; + data->regular = FALSE; + + run->numData++; + + return (OK); +} + + +static void +OUTpD_memory(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i, n = run->numData; + + for (i = 0; i < n; i++) { + + dataDesc *d; + + #ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(i); + #endif + + d = &run->data[i]; + + if (d->outIndex == -1) { + if (d->type == IF_REAL) + plotAddRealValue(d, refValue->rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, refValue->cValue); + } else if (d->regular) { + if (d->type == IF_REAL) + plotAddRealValue(d, valuePtr->v.vec.rVec[d->outIndex]); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, valuePtr->v.vec.cVec[d->outIndex]); + } else { + IFvalue val; + + /* should pre-check instance */ + if (!getSpecial(d, run, &val)) + continue; + + if (d->type == IF_REAL) + plotAddRealValue(d, val.rValue); + else if (d->type == IF_COMPLEX) + plotAddComplexValue(d, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } + + #ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(i, d->vec); + #endif + + } +} + + +int +OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) +{ + runDesc *run = plotPtr; // FIXME + int i; + + run->pointCount++; + +#ifdef TCL_MODULE + steps_completed = run->pointCount; +#endif + /* interpolated batch mode output to file in transient analysis */ + if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && run->writeOut) { + InterpFileAdd(run, refValue, valuePtr); + return (OK); + } + /* interpolated interactive or control mode output to plot in transient analysis */ + else if (interpolated && run->circuit->CKTcurJob->JOBtype == 4 && !(run->writeOut)) { + InterpPlotAdd(run, refValue, valuePtr); + return (OK); + } + /* standard batch mode output to file */ + else if (run->writeOut) { + + if (run->pointCount == 1) + fileInit_pass2(run); + + fileStartPoint(run->fp, run->binary, run->pointCount); + + if (run->refIndex != -1) { + if (run->isComplex) { + fileAddComplexValue(run->fp, run->binary, refValue->cValue); + + /* While we're looking at the reference value, print it to the screen + every quarter of a second, to give some feedback without using + too much CPU time */ +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) { + currclock = clock(); + if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->cValue.real); + lastclock = currclock; + } + } +#endif + } else { + + /* And the same for a non-complex value */ + + fileAddRealValue(run->fp, run->binary, refValue->rValue); +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) { + currclock = clock(); + if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + } + } + + for (i = 0; i < run->numData; i++) { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; + +#ifdef TCL_MODULE + blt_add(i, refValue ? refValue->rValue : NAN); +#endif + + if (run->data[i].regular) { + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, + valuePtr->v.vec.rVec [run->data[i].outIndex]); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, + valuePtr->v.vec.cVec [run->data[i].outIndex]); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } else { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) { + + /* If this is the first data point, print a warning for any unrecognized + variables, since this has not already been checked */ + + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); + + if (run->isComplex) { + val.cValue.real = 0; + val.cValue.imag = 0; + fileAddComplexValue(run->fp, run->binary, val.cValue); + } else { + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + } + + continue; + } + + if (run->data[i].type == IF_REAL) + fileAddRealValue(run->fp, run->binary, val.rValue); + else if (run->data[i].type == IF_COMPLEX) + fileAddComplexValue(run->fp, run->binary, val.cValue); + else + fprintf(stderr, "OUTpData: unsupported data type\n"); + } + +#ifdef TCL_MODULE + blt_add(i, valuePtr->v.vec.rVec [run->data[i].outIndex]); +#endif + + } + + fileEndPoint(run->fp, run->binary); + + /* Check that the write to disk completed successfully, otherwise abort */ + + if (ferror(run->fp)) { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } + + } else { + + OUTpD_memory(run, refValue, valuePtr); + + /* This is interactive mode. Update the screen with the reference + variable just the same */ + +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) { + currclock = clock(); + if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + if (run->isComplex) { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->cValue.real : NAN); + } else { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue ? refValue->rValue : NAN); + } + lastclock = currclock; + } + } +#endif + + gr_iplot(run->runPlot); + } + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + + return (OK); +} + + +int +OUTwReference(void *plotPtr, IFvalue *valuePtr, void **refPtr) +{ + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(plotPtr); + + return (OK); +} + + +int +OUTwData(runDesc *plotPtr, int dataIndex, IFvalue *valuePtr, void *refPtr) +{ + NG_IGNORE(refPtr); + NG_IGNORE(valuePtr); + NG_IGNORE(dataIndex); + NG_IGNORE(plotPtr); + + return (OK); +} + + +int +OUTwEnd(runDesc *plotPtr) +{ + NG_IGNORE(plotPtr); + + return (OK); +} + + +int +OUTendPlot(runDesc *plotPtr) +{ + if (plotPtr->writeOut) { + fileEnd(plotPtr); + } else { + gr_end_iplot(); + plotEnd(plotPtr); + } + + tfree(valueold); + tfree(valuenew); + + freeRun(plotPtr); + + return (OK); +} + + +int +OUTbeginDomain(runDesc *plotPtr, IFuid refName, int refType, IFvalue *outerRefValue) +{ + NG_IGNORE(outerRefValue); + NG_IGNORE(refType); + NG_IGNORE(refName); + NG_IGNORE(plotPtr); + + return (OK); +} + + +int +OUTendDomain(runDesc *plotPtr) +{ + NG_IGNORE(plotPtr); + + return (OK); +} + + +int +OUTattributes(runDesc *plotPtr, IFuid varName, int param, IFvalue *value) +{ + runDesc *run = plotPtr; // FIXME + GRIDTYPE type; + + struct dvec *d; + + NG_IGNORE(value); + + if (param == OUT_SCALE_LIN) + type = GRID_LIN; + else if (param == OUT_SCALE_LOG) + type = GRID_XLOG; + else + return E_UNSUPP; + + if (run->writeOut) { + if (varName) { + int i; + for (i = 0; i < run->numData; i++) + if (!strcmp(varName, run->data[i].name)) + run->data[i].gtype = type; + } else { + run->data[run->refIndex].gtype = type; + } + } else { + if (varName) { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + if (!strcmp(varName, d->v_name)) + d->v_gridtype = type; + } else if (param == PLOT_COMB) { + for (d = run->runPlot->pl_dvecs; d; d = d->v_next) + d->v_plottype = PLOT_COMB; + } else { + run->runPlot->pl_scale->v_gridtype = type; + } + } + + return (OK); +} + + +/* The file writing routines. */ + +static void +fileInit(runDesc *run) +{ + char buf[513]; + int i; + size_t n; + + lastclock = clock(); + + /* This is a hack. */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; + + n = 0; + sprintf(buf, "Title: %s\n", run->name); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Date: %s\n", datestring()); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Plotname: %s\n", run->type); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "Flags: %s\n", run->isComplex ? "complex" : "real"); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Variables: %d\n", run->numData); + n += strlen(buf); + fputs(buf, run->fp); + sprintf(buf, "No. Points: "); + n += strlen(buf); + fputs(buf, run->fp); + + fflush(run->fp); /* Gotta do this for LATTICE. */ + if (run->fp == stdout || (run->pointPos = ftell(run->fp)) <= 0) + run->pointPos = (long) n; + fprintf(run->fp, "0 \n"); /* Save 8 spaces here. */ + + /*fprintf(run->fp, "Command: version %s\n", ft_sim->version);*/ + fprintf(run->fp, "Variables:\n"); + + printf("No. of Data Columns : %d \n", run->numData); +} + + +static int +guess_type(const char *name) +{ + int type; + + if (substring("#branch", name)) + type = SV_CURRENT; + else if (cieq(name, "time")) + type = SV_TIME; + else if (cieq(name, "frequency")) + type = SV_FREQUENCY; + else if (ciprefix("inoise", name)) + type = fixme_inoise_type; + else if (ciprefix("onoise", name)) + type = fixme_onoise_type; + else if (cieq(name, "temp-sweep")) + type = SV_TEMP; + else if (cieq(name, "res-sweep")) + type = SV_RES; + else if ((*name == '@') && substring("[g", name)) /* token starting with [g */ + type = SV_ADMITTANCE; + else if ((*name == '@') && substring("[c", name)) + type = SV_CAPACITANCE; + else if ((*name == '@') && substring("[i", name)) + type = SV_CURRENT; + else if ((*name == '@') && substring("[q", name)) + type = SV_CHARGE; + else if ((*name == '@') && substring("[p]", name)) /* token is exactly [p] */ + type = SV_POWER; + else + type = SV_VOLTAGE; + + return type; +} + + +static void +fileInit_pass2(runDesc *run) +{ + int i, type; + + for (i = 0; i < run->numData; i++) { + + char *name = run->data[i].name; + + type = guess_type(name); + + if (type == SV_CURRENT) { + char *branch = strstr(name, "#branch"); + if (branch) + *branch = '\0'; + fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); + if (branch) + *branch = '#'; + } else if (type == SV_VOLTAGE) { + fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); + } else { + fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); + } + + if (run->data[i].gtype == GRID_XLOG) + fprintf(run->fp, "\tgrid=3"); + + fprintf(run->fp, "\n"); + } + + fprintf(run->fp, "%s:\n", run->binary ? "Binary" : "Values"); + fflush(run->fp); + + /* Allocate Row buffer */ + + if (run->binary) { + rowbuflen = (size_t) (run->numData); + if (run->isComplex) + rowbuflen *= 2; + rowbuf = TMALLOC(double, rowbuflen); + } else { + rowbuflen = 0; + rowbuf = NULL; + } +} + + +static void +fileStartPoint(FILE *fp, bool bin, int num) +{ + if (!bin) + fprintf(fp, "%d\t", num - 1); + + /* reset buffer pointer to zero */ + + column = 0; +} + + +static void +fileAddRealValue(FILE *fp, bool bin, double value) +{ + if (bin) + rowbuf[column++] = value; + else + fprintf(fp, "\t%.*e\n", DOUBLE_PRECISION, value); +} + + +static void +fileAddComplexValue(FILE *fp, bool bin, IFcomplex value) +{ + if (bin) { + rowbuf[column++] = value.real; + rowbuf[column++] = value.imag; + } else { + fprintf(fp, "\t%.*e,%.*e\n", DOUBLE_PRECISION, value.real, + DOUBLE_PRECISION, value.imag); + } +} + + +static void +fileEndPoint(FILE *fp, bool bin) +{ + /* write row buffer to file */ + /* otherwise the data has already been written */ + + if (bin) + fwrite(rowbuf, sizeof(double), rowbuflen, fp); +} + + +/* Here's the hack... Run back and fill in the number of points. */ + +static void +fileEnd(runDesc *run) +{ + /* 28.May.2020 - RP, BM - Check if any orphan test benches are running. If any are + * found, force them to exit. + */ + + /* 28.May.2020 - BM */ + close_server(); + /* End 28.May.2020 */ + + + if (run->fp != stdout) { + long place = ftell(run->fp); + fseek(run->fp, run->pointPos, SEEK_SET); + fprintf(run->fp, "%d", run->pointCount); + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); + fseek(run->fp, place, SEEK_SET); + } else { + /* Yet another hack-around */ + fprintf(stderr, "@@@ %ld %d\n", run->pointPos, run->pointCount); + } + + fflush(run->fp); + + tfree(rowbuf); +} + + +/* The plot maintenance routines. */ + +static void +plotInit(runDesc *run) +{ + struct plot *pl = plot_alloc(run->type); + struct dvec *v; + int i; + + pl->pl_title = copy(run->name); + pl->pl_name = copy(run->type); + pl->pl_date = copy(datestring()); + pl->pl_ndims = 0; + plot_new(pl); + plot_setcur(pl->pl_typename); + run->runPlot = pl; + + /* This is a hack. */ + /* if any of them complex, make them all complex */ + run->isComplex = FALSE; + for (i = 0; i < run->numData; i++) + if (run->data[i].type == IF_COMPLEX) + run->isComplex = TRUE; + + for (i = 0; i < run->numData; i++) { + dataDesc *dd = &run->data[i]; + char *name; + + if (isdigit_c(dd->name[0])) + name = tprintf("V(%s)", dd->name); + else + name = copy(dd->name); + + v = dvec_alloc(name, + guess_type(name), + run->isComplex + ? (VF_COMPLEX | VF_PERMANENT) + : (VF_REAL | VF_PERMANENT), + 0, NULL); + + vec_new(v); + dd->vec = v; + } +} + +/* prepare the vector length data for memory allocation + If new, and tran or pss, length is TSTOP / TSTEP plus some margin. + If allocated length is exceeded, check progress. When > 20% then extrapolate memory needed, + if less than 20% then just double the size. + If not tran or pss, return fixed value (1024) of memory to be added. + */ +static inline int +vlength2delta(int len) +{ +#ifdef SHARED_MODULE + if (savenone) + /* We need just a vector length of 1 */ + return 1; +#endif + /* TSTOP / TSTEP */ + int points = ft_curckt->ci_ckt->CKTtimeListSize; + /* transient and pss analysis (points > 0) upon start */ + if (len == 0 && points > 0) { + /* number of timesteps plus some overhead */ + return points + 100; + } + /* transient and pss if original estimate is exceeded */ + else if (points > 0) { + /* check where we are */ + double timerel = ft_curckt->ci_ckt->CKTtime / ft_curckt->ci_ckt->CKTfinalTime; + /* return an estimate of the appropriate number of time points, if more than 20% of + the anticipated total time has passed */ + if (timerel > 0.2) + return (int)(len / timerel) - len + 1; + /* If not, just double the available memory */ + else + return len; + } + /* other analysis types that do not set CKTtimeListSize */ + else + return 1024; +} + + +static void +plotAddRealValue(dataDesc *desc, double value) +{ + struct dvec *v = desc->vec; + +#ifdef SHARED_MODULE + if (savenone) + /* always save new data to same location */ + v->v_length = 0; +#endif + + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); + + if (isreal(v)) { + v->v_realdata[v->v_length] = value; + } else { + /* a real parading as a VF_COMPLEX */ + v->v_compdata[v->v_length].cx_real = value; + v->v_compdata[v->v_length].cx_imag = 0.0; + } + + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ +} + + +static void +plotAddComplexValue(dataDesc *desc, IFcomplex value) +{ + struct dvec *v = desc->vec; + +#ifdef SHARED_MODULE + if (savenone) + v->v_length = 0; +#endif + + if (v->v_length >= v->v_alloc_length) + dvec_extend(v, v->v_length + vlength2delta(v->v_length)); + + v->v_compdata[v->v_length].cx_real = value.real; + v->v_compdata[v->v_length].cx_imag = value.imag; + + v->v_length++; + v->v_dims[0] = v->v_length; /* va, must be updated */ +} + + +static void +plotEnd(runDesc *run) +{ + /* 28.May.2020 - BM, RP */ + close_server(); + /* End 28.May.2020 */ + + fprintf(stdout, "\nNo. of Data Rows : %d\n", run->pointCount); +} + + +/* ParseSpecial takes something of the form "@name[param,index]" and rips + * out name, param, andstrchr. + */ + +static bool +parseSpecial(char *name, char *dev, char *param, char *ind) +{ + char *s; + + *dev = *param = *ind = '\0'; + + if (*name != '@') + return FALSE; + name++; + + s = dev; + while (*name && (*name != '[')) + *s++ = *name++; + *s = '\0'; + + if (!*name) + return TRUE; + name++; + + s = param; + while (*name && (*name != ',') && (*name != ']')) + *s++ = *name++; + *s = '\0'; + + if (*name == ']') + return (!name[1] ? TRUE : FALSE); + else if (!*name) + return FALSE; + name++; + + s = ind; + while (*name && (*name != ']')) + *s++ = *name++; + *s = '\0'; + + if (*name && !name[1]) + return TRUE; + else + return FALSE; +} + + +/* This routine must match two names with or without a V() around them. */ + +static bool +name_eq(char *n1, char *n2) +{ + char buf1[BSIZE_SP], buf2[BSIZE_SP], *s; + + if ((s = strchr(n1, '(')) != NULL) { + strcpy(buf1, s); + if ((s = strchr(buf1, ')')) == NULL) + return FALSE; + *s = '\0'; + n1 = buf1; + } + + if ((s = strchr(n2, '(')) != NULL) { + strcpy(buf2, s); + if ((s = strchr(buf2, ')')) == NULL) + return FALSE; + *s = '\0'; + n2 = buf2; + } + + return (strcmp(n1, n2) ? FALSE : TRUE); +} + + +static bool +getSpecial(dataDesc *desc, runDesc *run, IFvalue *val) +{ + IFvalue selector; + struct variable *vv; + + selector.iValue = desc->specIndex; + if (INPaName(desc->specParamName, val, run->circuit, &desc->specType, + desc->specName, &desc->specFast, ft_sim, &desc->type, + &selector) == OK) { + desc->type &= (IF_REAL | IF_COMPLEX); /* mask out other bits */ + return TRUE; + } + + if ((vv = if_getstat(run->circuit, &desc->name[1])) != NULL) { + /* skip @ sign */ + desc->type = IF_REAL; + if (vv->va_type == CP_REAL) + val->rValue = vv->va_real; + else if (vv->va_type == CP_NUM) + val->rValue = vv->va_num; + else if (vv->va_type == CP_BOOL) + val->rValue = (vv->va_bool ? 1.0 : 0.0); + else + return FALSE; /* not a real */ + tfree(vv); + return TRUE; + } + + return FALSE; +} + + +static void +freeRun(runDesc *run) +{ + int i; + + for (i = 0; i < run->numData; i++) { + tfree(run->data[i].name); + tfree(run->data[i].specParamName); + } + + tfree(run->data); + tfree(run->type); + tfree(run->name); + + tfree(run); +} + + +int +OUTstopnow(void) +{ + if (ft_intrpt || shouldstop) { + ft_intrpt = shouldstop = FALSE; + return (1); + } + + return (0); +} + + +/* Print out error messages. */ + +static struct mesg { + char *string; + long flag; +} msgs[] = { + { "Warning", ERR_WARNING } , + { "Fatal error", ERR_FATAL } , + { "Panic", ERR_PANIC } , + { "Note", ERR_INFO } , + { NULL, 0 } +}; + + +void +OUTerror(int flags, char *format, IFuid *names) +{ + struct mesg *m; + char buf[BSIZE_SP], *s, *bptr; + int nindex = 0; + + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; + + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); + + for (s = format, bptr = buf; *s; s++) { + if (*s == '%' && (s == format || s[-1] != '%') && s[1] == 's') { + if (names[nindex]) + strcpy(bptr, names[nindex]); + else + strcpy(bptr, "(null)"); + bptr += strlen(bptr); + s++; + nindex++; + } else { + *bptr++ = *s; + } + } + + *bptr = '\0'; + fprintf(cp_err, "%s\n", buf); + fflush(cp_err); +} + + +void +OUTerrorf(int flags, const char *format, ...) +{ + struct mesg *m; + va_list args; + + if ((flags == ERR_INFO) && cp_getvar("printinfo", CP_BOOL, NULL, 0)) + return; + + for (m = msgs; m->flag; m++) + if (flags & m->flag) + fprintf(cp_err, "%s: ", m->string); + + va_start (args, format); + + vfprintf(cp_err, format, args); + fputc('\n', cp_err); + + fflush(cp_err); + + va_end(args); +} + + +static int +InterpFileAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; + + if (run->pointCount == 1) { + fileInit_pass2(run); + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; + } + + if (run->refIndex != -1) { + /* Save first time step */ + if (refValue->rValue == run->circuit->CKTinitTime) { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTinitTime); + interpolatenow = nodata = FALSE; + } + /* Save last time step */ + else if (refValue->rValue == run->circuit->CKTfinalTime) { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, run->circuit->CKTfinalTime); + interpolatenow = nodata = FALSE; + } + /* Save exact point */ + else if (refValue->rValue == timestep) { + timeold = refValue->rValue; + fileStartPoint(run->fp, run->binary, run->pointCount); + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + interpolatenow = nodata = FALSE; + } + else if (refValue->rValue > timestep) { + /* add the next time step value to the vector */ + fileStartPoint(run->fp, run->binary, run->pointCount); + timenew = refValue->rValue; + fileAddRealValue(run->fp, run->binary, timestep); + timestep += run->circuit->CKTstep; + nodata = FALSE; + interpolatenow = TRUE; + } + else { + /* Do not save this step */ + run->pointCount--; + timeold = refValue->rValue; + nodata = TRUE; + interpolatenow = FALSE; + } +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) { + currclock = clock(); + if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + + } + + for (i = 0; i < run->numData; i++) { + /* we've already printed reference vec first */ + if (run->data[i].outIndex == -1) + continue; + +#ifdef TCL_MODULE + blt_add(i, refValue ? refValue->rValue : NAN); +#endif + + if (run->data[i].regular) { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + } else { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) { + + /* If this is the first data point, print a warning for any unrecognized + variables, since this has not already been checked */ + if (run->pointCount == 1) + fprintf(stderr, "Warning: unrecognized variable - %s\n", + run->data[i].name); + val.rValue = 0; + fileAddRealValue(run->fp, run->binary, val.rValue); + continue; + } + if (!interpolatenow && !nodata) { + /* store the first or last value */ + valueold[i] = val.rValue; + fileAddRealValue(run->fp, run->binary, valueold[i]); + } + else if (interpolatenow) { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + fileAddRealValue(run->fp, run->binary, newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = val.rValue; + } + +#ifdef TCL_MODULE + blt_add(i, valuePtr->v.vec.rVec [run->data[i].outIndex]); +#endif + + } + + fileEndPoint(run->fp, run->binary); + + /* Check that the write to disk completed successfully, otherwise abort */ + if (ferror(run->fp)) { + fprintf(stderr, "Warning: rawfile write error !!\n"); + shouldstop = TRUE; + } + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + return(OK); +} + +static int +InterpPlotAdd(runDesc *run, IFvalue *refValue, IFvalue *valuePtr) +{ + int i, iscale = -1; + static double timeold = 0.0, timenew = 0.0, timestep = 0.0; + bool nodata = FALSE; + bool interpolatenow = FALSE; + + if (run->pointCount == 1) + timestep = run->circuit->CKTinitTime + run->circuit->CKTstep; + + /* find the scale vector */ + for (i = 0; i < run->numData; i++) + if (run->data[i].outIndex == -1) { + iscale = i; + break; + } + if (iscale == -1) + fprintf(stderr, "Error: no scale vector found\n"); + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(iscale); +#endif + + /* Save first time step */ + if (refValue->rValue == run->circuit->CKTinitTime) { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], refValue->rValue); + interpolatenow = nodata = FALSE; + } + /* Save last time step */ + else if (refValue->rValue == run->circuit->CKTfinalTime) { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], run->circuit->CKTfinalTime); + interpolatenow = nodata = FALSE; + } + /* Save exact point */ + else if (refValue->rValue == timestep) { + timeold = refValue->rValue; + plotAddRealValue(&run->data[iscale], timestep); + timestep += run->circuit->CKTstep; + interpolatenow = nodata = FALSE; + } + else if (refValue->rValue > timestep) { + /* add the next time step value to the vector */ + timenew = refValue->rValue; + plotAddRealValue(&run->data[iscale], timestep); + timestep += run->circuit->CKTstep; + nodata = FALSE; + interpolatenow = TRUE; + } + else { + /* Do not save this step */ + run->pointCount--; + timeold = refValue->rValue; + nodata = TRUE; + interpolatenow = FALSE; + } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(iscale, (run->data[iscale]).vec); +#endif + +#ifndef HAS_WINGUI + if (!orflag && !ft_norefprint) { + currclock = clock(); + if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); + lastclock = currclock; + } + } +#endif + + for (i = 0; i < run->numData; i++) { + if (i == iscale) + continue; + +#ifdef TCL_MODULE + /*Locks the blt vector to stop access*/ + blt_lockvec(i); +#endif + + if (run->data[i].regular) { + /* Store value or interpolate and store or do not store any value to file */ + if (!interpolatenow && !nodata) { + /* store the first or last value */ + valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = valuePtr->v.vec.rVec [run->data[i].outIndex]; + } else { + IFvalue val; + /* should pre-check instance */ + if (!getSpecial(&run->data[i], run, &val)) + continue; + if (!interpolatenow && !nodata) { + /* store the first or last value */ + valueold[i] = val.rValue; + plotAddRealValue(&run->data[i], valueold[i]); + } + else if (interpolatenow) { + /* Interpolate time if actual time is greater than proposed next time step */ + double newval; + valuenew[i] = val.rValue; + newval = (timestep - run->circuit->CKTstep - timeold)/(timenew - timeold) * (valuenew[i] - valueold[i]) + valueold[i]; + plotAddRealValue(&run->data[i], newval); + valueold[i] = valuenew[i]; + } + else if (nodata) + /* Just keep the transient output value corresponding to timeold, + but do not store to file */ + valueold[i] = val.rValue; + } + +#ifdef TCL_MODULE + /*relinks and unlocks vector*/ + blt_relink(i, (run->data[i]).vec); +#endif + + } + + gr_iplot(run->runPlot); + + if (ft_bpcheck(run->runPlot, run->pointCount) == FALSE) + shouldstop = TRUE; + +#ifdef TCL_MODULE + Tcl_ExecutePerLoop(); +#elif defined SHARED_MODULE + sh_ExecutePerLoop(); +#endif + + return(OK); +} -- cgit From d8423a5909a5bbac9b17761a1ea844cb2ca401a0 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Tue, 14 Jul 2020 11:45:06 +0530 Subject: OS - independent with Windows compatability --- src/createKicadLibrary.py | 543 +++++----- src/model_generation.py | 2564 ++++++++++++++++++++------------------------- src/ngspice_ghdl.py | 32 +- 3 files changed, 1403 insertions(+), 1736 deletions(-) (limited to 'src') diff --git a/src/createKicadLibrary.py b/src/createKicadLibrary.py index 966c9d6..2b3e7d7 100644 --- a/src/createKicadLibrary.py +++ b/src/createKicadLibrary.py @@ -1,269 +1,274 @@ -from Appconfig import Appconfig -import re -import os -import xml.etree.cElementTree as ET -from PyQt4 import QtGui - - -class AutoSchematic(QtGui.QWidget): - - def __init__(self, modelname): - QtGui.QWidget.__init__(self) - self.modelname = modelname.split('.')[0] - self.template = Appconfig.kicad_lib_template.copy() - self.xml_loc = Appconfig.xml_loc - self.lib_loc = Appconfig.lib_loc - self.kicad_nghdl_lib = '/usr/share/kicad/library/eSim_Nghdl.lib' - self.parser = Appconfig.parser_nghdl - - def createKicadLibrary(self): - xmlFound = None - for root, dirs, files in os.walk(self.xml_loc): - if (str(self.modelname) + '.xml') in files: - xmlFound = root - print(xmlFound) - if xmlFound is None: - self.getPortInformation() - self.createXML() - self.createLib() - elif (xmlFound == self.xml_loc + '/Nghdl'): - print('Library already exists...') - ret = QtGui.QMessageBox.warning( - self, "Warning", '''Library files for this model ''' + - '''already exist. Do you want to overwrite it?
- If yes press ok, else cancel it and ''' + - '''change the name of your vhdl file.''', - QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel - ) - if ret == QtGui.QMessageBox.Ok: - print("Overwriting existing libraries") - self.getPortInformation() - self.createXML() - self.removeOldLibrary() # Removes the exisitng library - self.createLib() - else: - print("Exiting Nghdl") - quit() - else: - print('Pre existing library...') - ret = QtGui.QMessageBox.critical( - self, "Error", '''A standard library already exists ''' + - '''with this name.
Please change the name ''' + - '''of your vhdl file and upload it again''', - QtGui.QMessageBox.Ok - ) - - # quit() - - def getPortInformation(self): - portInformation = PortInfo(self) - portInformation.getPortInfo() - self.portInfo = portInformation.bit_list - self.input_length = portInformation.input_len - - def createXML(self): - cwd = os.getcwd() - xmlDestination = os.path.join(self.xml_loc, 'Nghdl') - self.splitText = "" - for bit in self.portInfo[:-1]: - self.splitText += bit + "-V:" - self.splitText += self.portInfo[-1] + "-V" - - print("changing directory to ", xmlDestination) - os.chdir(xmlDestination) - - root = ET.Element("model") - ET.SubElement(root, "name").text = self.modelname - ET.SubElement(root, "type").text = "Nghdl" - ET.SubElement(root, "node_number").text = str(len(self.portInfo)) - ET.SubElement(root, "title").text = ( - "Add parameters for " + str(self.modelname)) - ET.SubElement(root, "split").text = self.splitText - param = ET.SubElement(root, "param") - ET.SubElement(param, "rise_delay", default="1.0e-9").text = ( - "Enter Rise Delay (default=1.0e-9)") - ET.SubElement(param, "fall_delay", default="1.0e-9").text = ( - "Enter Fall Delay (default=1.0e-9)") - ET.SubElement(param, "input_load", default="1.0e-12").text = ( - "Enter Input Load (default=1.0e-12)") - ET.SubElement(param, "instance_id", default="1").text = ( - "Enter Instance ID (Between 0-99)") - tree = ET.ElementTree(root) - tree.write(str(self.modelname) + '.xml') - print("Leaving the directory ", xmlDestination) - os.chdir(cwd) - - # Calculates the maximum between input and output ports - def findBlockSize(self): - ind = self.input_length - return max( - self.char_sum(self.portInfo[:ind]), - self.char_sum(self.portInfo[ind:]) - ) - - def char_sum(self, ls): - return sum([int(x) for x in ls]) - - def removeOldLibrary(self): - cwd = os.getcwd() - os.chdir(self.lib_loc) - print("Changing directory to ", self.lib_loc) - f = open(self.kicad_nghdl_lib) - lines = f.readlines() - f.close() - - output = [] - line_reading_flag = False - - for line in lines: - if line.startswith("DEF"): - if line.split()[1] == self.modelname: - line_reading_flag = True - if not line_reading_flag: - output.append(line) - if line.startswith("ENDDEF"): - line_reading_flag = False - - f = open(self.kicad_nghdl_lib, 'w') - for line in output: - f.write(line) - - os.chdir(cwd) - print("Leaving directory, ", self.lib_loc) - - def createLib(self): - self.dist_port = 100 # Distance between two ports - self.inc_size = 100 # Increment size of a block - cwd = os.getcwd() - os.chdir(self.lib_loc) - print("Changing directory to ", self.lib_loc) - - lib_file = open(self.kicad_nghdl_lib, "a") - line1 = self.template["start_def"] - line1 = line1.split() - line1 = [w.replace('comp_name', self.modelname) for w in line1] - self.template["start_def"] = ' '.join(line1) - if os.stat(self.kicad_nghdl_lib).st_size == 0: - lib_file.write("EESchema-LIBRARY Version 2.3" + "\n\n") - # lib_file.write("#encoding utf-8"+ "\n"+ "#"+ "\n" + - # "#test_compo" + "\n"+ "#"+ "\n") - lib_file.write( - self.template["start_def"] + "\n" + self.template["U_field"]+"\n" - ) - - line3 = self.template["comp_name_field"] - line3 = line3.split() - line3 = [w.replace('comp_name', self.modelname) for w in line3] - self.template["comp_name_field"] = ' '.join(line3) - - lib_file.write(self.template["comp_name_field"] + "\n") - - line4 = self.template["blank_field"] - line4_1 = line4[0] - line4_2 = line4[1] - line4_1 = line4_1.split() - line4_1 = [w.replace('blank_quotes', '""') for w in line4_1] - line4_2 = line4_2.split() - line4_2 = [w.replace('blank_quotes', '""') for w in line4_2] - line4[0] = ' '.join(line4_1) - line4[1] = ' '.join(line4_2) - self.template["blank_qoutes"] = line4 - - lib_file.write( - line4[0] + "\n" + line4[1] + "\n" + - self.template["start_draw"] + "\n" - ) - - draw_pos = self.template["draw_pos"] - draw_pos = draw_pos.split() - draw_pos[4] = str( - int(draw_pos[4]) - self.findBlockSize() * self.inc_size) - self.template["draw_pos"] = ' '.join(draw_pos) - - lib_file.write(self.template["draw_pos"]+"\n") - - input_port = self.template["input_port"] - input_port = input_port.split() - output_port = self.template["output_port"] - output_port = output_port.split() - inputs = self.portInfo[0: self.input_length] - outputs = self.portInfo[self.input_length:] - - print("INPUTS AND OUTPUTS ") - print(inputs) - print(outputs) - - inputs = self.char_sum(inputs) - outputs = self.char_sum(outputs) - - total = inputs+outputs - - port_list = [] - - for i in range(total): - if (i < inputs): - input_port[1] = "in" + str(i + 1) - input_port[2] = str(i + 1) - input_port[4] = str(int(input_port[4]) - self.dist_port) - input_list = ' '.join(input_port) - port_list.append(input_list) - - else: - output_port[1] = "out" + str(i - inputs + 1) - output_port[2] = str(i + 1) - output_port[4] = str(int(output_port[4]) - self.dist_port) - output_list = ' '.join(output_port) - port_list.append(output_list) - - for ports in port_list: - lib_file.write(ports+"\n") - lib_file.write( - self.template["end_draw"] + "\n" + - self.template["end_def"] + "\n\n\n" - ) - - os.chdir(cwd) - print('Leaving directory, ', self.lib_loc) - QtGui.QMessageBox.information( - self, "Library added", - '''Library details for this model is added to the ''' + - '''eSim_Nghdl.lib in the KiCad shared directory''', - QtGui.QMessageBox.Ok - ) - - -class PortInfo: - def __init__(self, model): - self.modelname = model.modelname - self.model_loc = model.parser.get('NGSPICE', 'DIGITAL_MODEL') - self.bit_list = [] - self.input_len = 0 - - def getPortInfo(self): - info_loc = os.path.join(self.model_loc, self.modelname+'/DUTghdl/') - input_list = [] - output_list = [] - read_file = open(info_loc + 'connection_info.txt', 'r') - data = read_file.readlines() - read_file.close() - - for line in data: - if re.match(r'^\s*$', line): - pass - else: - in_items = re.findall( - "IN", line, re.MULTILINE | re.IGNORECASE - ) - out_items = re.findall( - "OUT", line, re.MULTILINE | re.IGNORECASE - ) - if in_items: - input_list.append(line.split()) - if out_items: - output_list.append(line.split()) - - for in_list in input_list: - self.bit_list.append(in_list[2]) - self.input_len = len(self.bit_list) - for out_list in output_list: - self.bit_list.append(out_list[2]) +from Appconfig import Appconfig +import re +import os +import xml.etree.cElementTree as ET +from PyQt4 import QtGui + + +class AutoSchematic(QtGui.QWidget): + + def __init__(self, modelname): + QtGui.QWidget.__init__(self) + self.modelname = modelname.split('.')[0] + self.template = Appconfig.kicad_lib_template.copy() + self.xml_loc = Appconfig.xml_loc + self.lib_loc = Appconfig.lib_loc + if os.name == 'nt': + eSim_src = Appconfig.src_home + inst_dir = eSim_src.replace('\eSim', '') + self.kicad_nghdl_lib = inst_dir + '/KiCad/share/kicad/library/eSim_Nghdl.lib' + else: + self.kicad_nghdl_lib = '/usr/share/kicad/library/eSim_Nghdl.lib' + self.parser = Appconfig.parser_nghdl + + def createKicadLibrary(self): + xmlFound = None + for root, dirs, files in os.walk(self.xml_loc): + if (str(self.modelname) + '.xml') in files: + xmlFound = root + print(xmlFound) + if xmlFound is None: + self.getPortInformation() + self.createXML() + self.createLib() + elif (xmlFound == os.path.join(self.xml_loc, 'Nghdl')): + print('Library already exists...') + ret = QtGui.QMessageBox.warning( + self, "Warning", '''Library files for this model ''' + + '''already exist. Do you want to overwrite it?
+ If yes press ok, else cancel it and ''' + + '''change the name of your vhdl file.''', + QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel + ) + if ret == QtGui.QMessageBox.Ok: + print("Overwriting existing libraries") + self.getPortInformation() + self.createXML() + self.removeOldLibrary() # Removes the exisitng library + self.createLib() + else: + print("Exiting Nghdl") + quit() + else: + print('Pre existing library...') + ret = QtGui.QMessageBox.critical( + self, "Error", '''A standard library already exists ''' + + '''with this name.
Please change the name ''' + + '''of your vhdl file and upload it again''', + QtGui.QMessageBox.Ok + ) + + # quit() + + def getPortInformation(self): + portInformation = PortInfo(self) + portInformation.getPortInfo() + self.portInfo = portInformation.bit_list + self.input_length = portInformation.input_len + + def createXML(self): + cwd = os.getcwd() + xmlDestination = os.path.join(self.xml_loc, 'Nghdl') + self.splitText = "" + for bit in self.portInfo[:-1]: + self.splitText += bit + "-V:" + self.splitText += self.portInfo[-1] + "-V" + + print("changing directory to ", xmlDestination) + os.chdir(xmlDestination) + + root = ET.Element("model") + ET.SubElement(root, "name").text = self.modelname + ET.SubElement(root, "type").text = "Nghdl" + ET.SubElement(root, "node_number").text = str(len(self.portInfo)) + ET.SubElement(root, "title").text = ( + "Add parameters for " + str(self.modelname)) + ET.SubElement(root, "split").text = self.splitText + param = ET.SubElement(root, "param") + ET.SubElement(param, "rise_delay", default="1.0e-9").text = ( + "Enter Rise Delay (default=1.0e-9)") + ET.SubElement(param, "fall_delay", default="1.0e-9").text = ( + "Enter Fall Delay (default=1.0e-9)") + ET.SubElement(param, "input_load", default="1.0e-12").text = ( + "Enter Input Load (default=1.0e-12)") + ET.SubElement(param, "instance_id", default="1").text = ( + "Enter Instance ID (Between 0-99)") + tree = ET.ElementTree(root) + tree.write(str(self.modelname) + '.xml') + print("Leaving the directory ", xmlDestination) + os.chdir(cwd) + + # Calculates the maximum between input and output ports + def findBlockSize(self): + ind = self.input_length + return max( + self.char_sum(self.portInfo[:ind]), + self.char_sum(self.portInfo[ind:]) + ) + + def char_sum(self, ls): + return sum([int(x) for x in ls]) + + def removeOldLibrary(self): + cwd = os.getcwd() + os.chdir(self.lib_loc) + print("Changing directory to ", self.lib_loc) + f = open(self.kicad_nghdl_lib) + lines = f.readlines() + f.close() + + output = [] + line_reading_flag = False + + for line in lines: + if line.startswith("DEF"): + if line.split()[1] == self.modelname: + line_reading_flag = True + if not line_reading_flag: + output.append(line) + if line.startswith("ENDDEF"): + line_reading_flag = False + + f = open(self.kicad_nghdl_lib, 'w') + for line in output: + f.write(line) + + os.chdir(cwd) + print("Leaving directory, ", self.lib_loc) + + def createLib(self): + self.dist_port = 100 # Distance between two ports + self.inc_size = 100 # Increment size of a block + cwd = os.getcwd() + os.chdir(self.lib_loc) + print("Changing directory to ", self.lib_loc) + + lib_file = open(self.kicad_nghdl_lib, "a") + line1 = self.template["start_def"] + line1 = line1.split() + line1 = [w.replace('comp_name', self.modelname) for w in line1] + self.template["start_def"] = ' '.join(line1) + if os.stat(self.kicad_nghdl_lib).st_size == 0: + lib_file.write("EESchema-LIBRARY Version 2.3" + "\n\n") + # lib_file.write("#encoding utf-8"+ "\n"+ "#"+ "\n" + + # "#test_compo" + "\n"+ "#"+ "\n") + lib_file.write( + self.template["start_def"] + "\n" + self.template["U_field"]+"\n" + ) + + line3 = self.template["comp_name_field"] + line3 = line3.split() + line3 = [w.replace('comp_name', self.modelname) for w in line3] + self.template["comp_name_field"] = ' '.join(line3) + + lib_file.write(self.template["comp_name_field"] + "\n") + + line4 = self.template["blank_field"] + line4_1 = line4[0] + line4_2 = line4[1] + line4_1 = line4_1.split() + line4_1 = [w.replace('blank_quotes', '""') for w in line4_1] + line4_2 = line4_2.split() + line4_2 = [w.replace('blank_quotes', '""') for w in line4_2] + line4[0] = ' '.join(line4_1) + line4[1] = ' '.join(line4_2) + self.template["blank_qoutes"] = line4 + + lib_file.write( + line4[0] + "\n" + line4[1] + "\n" + + self.template["start_draw"] + "\n" + ) + + draw_pos = self.template["draw_pos"] + draw_pos = draw_pos.split() + draw_pos[4] = str( + int(draw_pos[4]) - self.findBlockSize() * self.inc_size) + self.template["draw_pos"] = ' '.join(draw_pos) + + lib_file.write(self.template["draw_pos"]+"\n") + + input_port = self.template["input_port"] + input_port = input_port.split() + output_port = self.template["output_port"] + output_port = output_port.split() + inputs = self.portInfo[0: self.input_length] + outputs = self.portInfo[self.input_length:] + + print("INPUTS AND OUTPUTS ") + print(inputs) + print(outputs) + + inputs = self.char_sum(inputs) + outputs = self.char_sum(outputs) + + total = inputs+outputs + + port_list = [] + + for i in range(total): + if (i < inputs): + input_port[1] = "in" + str(i + 1) + input_port[2] = str(i + 1) + input_port[4] = str(int(input_port[4]) - self.dist_port) + input_list = ' '.join(input_port) + port_list.append(input_list) + + else: + output_port[1] = "out" + str(i - inputs + 1) + output_port[2] = str(i + 1) + output_port[4] = str(int(output_port[4]) - self.dist_port) + output_list = ' '.join(output_port) + port_list.append(output_list) + + for ports in port_list: + lib_file.write(ports+"\n") + lib_file.write( + self.template["end_draw"] + "\n" + + self.template["end_def"] + "\n\n\n" + ) + + os.chdir(cwd) + print('Leaving directory, ', self.lib_loc) + QtGui.QMessageBox.information( + self, "Library added", + '''Library details for this model is added to the ''' + + '''eSim_Nghdl.lib in the KiCad shared directory''', + QtGui.QMessageBox.Ok + ) + + +class PortInfo: + def __init__(self, model): + self.modelname = model.modelname + self.model_loc = model.parser.get('NGSPICE', 'DIGITAL_MODEL') + self.bit_list = [] + self.input_len = 0 + + def getPortInfo(self): + info_loc = os.path.join(self.model_loc, self.modelname+'/DUTghdl/') + input_list = [] + output_list = [] + read_file = open(info_loc + 'connection_info.txt', 'r') + data = read_file.readlines() + read_file.close() + + for line in data: + if re.match(r'^\s*$', line): + pass + else: + in_items = re.findall( + "IN", line, re.MULTILINE | re.IGNORECASE + ) + out_items = re.findall( + "OUT", line, re.MULTILINE | re.IGNORECASE + ) + if in_items: + input_list.append(line.split()) + if out_items: + output_list.append(line.split()) + + for in_list in input_list: + self.bit_list.append(in_list[2]) + self.input_len = len(self.bit_list) + for out_list in output_list: + self.bit_list.append(out_list[2]) diff --git a/src/model_generation.py b/src/model_generation.py index 305ced8..7baecc1 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -1,1450 +1,1114 @@ -#!/usr/bin/python3 - -import re -import os -from configparser import SafeConfigParser - - -class ModelGeneration: - - def __init__(self, file): - - # Script starts from here - print("Arguement is : ", file) - self.fname = os.path.basename(file) - print("VHDL filename is : ", self.fname) - self.home = os.path.expanduser("~") - self.parser = SafeConfigParser() - self.parser.read(os.path.join( - self.home, os.path.join('.nghdl', 'config.ini'))) - self.ngspice_home = self.parser.get('NGSPICE', 'NGSPICE_HOME') - self.release_dir = self.parser.get('NGSPICE', 'RELEASE') - self.src_home = self.parser.get('SRC', 'SRC_HOME') - self.licensefile = self.parser.get('SRC', 'LICENSE') - - # #### Creating connection_info.txt file from vhdl file #### # - read_vhdl = open(file, 'r') - vhdl_data = read_vhdl.readlines() - read_vhdl.close() - - start_flag = -1 # Used for scaning part of data - scan_data = [] - # p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() - - for item in vhdl_data: - if re.search('port', item, re.I): - start_flag = 1 - - elif re.search("end", item, re.I): - start_flag = 0 - - if start_flag == 1: - item = re.sub("port", " ", item, flags=re.I) - item = re.sub("\(", " ", item, flags=re.I) # noqa - item = re.sub("\)", " ", item, flags=re.I) # noqa - item = re.sub(";", " ", item, flags=re.I) - - scan_data.append(item.rstrip()) - scan_data = [_f for _f in scan_data if _f] - elif start_flag == 0: - break - - port_info = [] - self.port_vector_info = [] - - for item in scan_data: - print("Scan Data :", item) - if re.search("in", item, flags=re.I): - if re.search("std_logic_vector", item, flags=re.I): - temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) - elif re.search("std_logic", item, flags=re.I): - temp = re.compile(r"\s*std_logic\s*", flags=re.I) - else: - raise ValueError("Please check your vhdl " + - "code for datatype of input port") - elif re.search("out", item, flags=re.I): - if re.search("std_logic_vector", item, flags=re.I): - temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) - elif re.search("std_logic", item, flags=re.I): - temp = re.compile(r"\s*std_logic\s*", flags=re.I) - else: - raise ValueError("Please check your vhdl " + - "code for datatype of output port") - else: - raise ValueError( - "Please check the in/out direction of your port" - ) - - lhs = temp.split(item)[0] - rhs = temp.split(item)[1] - bit_info = re.compile(r"\s*downto\s*", flags=re.I).split(rhs)[0] - if bit_info: - port_info.append(lhs + ":" + str(int(bit_info) + int(1))) - self.port_vector_info.append(1) - else: - port_info.append(lhs + ":" + str(int(1))) - self.port_vector_info.append(0) - - print("Port Info :", port_info) - - # Open connection_info.txt file - con_ifo = open('connection_info.txt', 'w') - - for item in port_info: - word = item.split(':') - con_ifo.write( - word[0].strip() + ' ' + word[1].strip() + ' ' + word[2].strip() - ) - con_ifo.write("\n") - con_ifo.close() - - def readPortInfo(self): - - # ############## Reading connection/port information ############## # - - # Declaring input and output list - input_list = [] - output_list = [] - - # Reading connection_info.txt file for port infomation - read_file = open('connection_info.txt', 'r') - data = read_file.readlines() - read_file.close() - - # Extracting input and output port list from data - print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") - for line in data: - print(line) - if re.match(r'^\s*$', line): - pass - else: - in_items = re.findall( - "IN", line, re.MULTILINE | re.IGNORECASE - ) - out_items = re.findall( - "OUT", line, re.MULTILINE | re.IGNORECASE - ) - if in_items: - input_list.append(line.split()) - - if out_items: - output_list.append(line.split()) - - print("Inout List :", input_list) - print("Output list", output_list) - - self.input_port = [] - self.output_port = [] - - # creating list of input and output port with its weight - for input in input_list: - self.input_port.append(input[0]+":"+input[2]) - for output in output_list: - self.output_port.append(output[0]+":"+output[2]) - - print("Output Port List : ", self.output_port) - print("Input Port List : ", self.input_port) - -#08.June.2020 - BM - If OS is Windows, write Windows socket version of cfunc.mod, else write Linux(BSD) socket version - if os.name == 'nt': - def createCfuncModFile(self): - - # ## Creating content for cfunc.mod file ## # - - print("Starting With cfunc.mod file") - cfunc = open('cfunc.mod', 'w') - print("Building content for cfunc.mod file") - - comment = '''/* This is cfunc.mod file auto generated by gen_con_info.py - Developed by Fahim, Rahul at IIT Bombay */\n - ''' - - header = ''' - #include - #include - #include - #include - #include - #include - #include - #include - - #undef BOOLEAN - #include - ''' - - function_open = ( - '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') - - digital_state_output = [] - for item in self.output_port: - digital_state_output.append( - "Digital_State_t *_op_" + item.split(':')[0] + - ", *_op_" + item.split(':')[0] + "_old;" - ) - - var_section = ''' - // Declaring components of Client - FILE *log_client = NULL; - log_client=fopen("client.log","a"); - int bytes_recieved; - char send_data[1024]; - char recv_data[1024]; - char *key_iter; - struct hostent *host; - struct sockaddr_in server_addr; - int sock_port = 5000+PARAM(instance_id); - ''' - - temp_input_var = [] - for item in self.input_port: - temp_input_var.append( - "char temp_" + item.split(':')[0] + "[1024];" - ) - - # Start of INIT function - init_start_function = ''' - if(INIT) - { - /* Allocate storage for output ports ''' \ - '''and set the load for input ports */ - ''' - - cm_event_alloc = [] - cm_count_output = 0 - for item in self.output_port: - cm_event_alloc.append( - "cm_event_alloc(" + - str(cm_count_output) + "," + item.split(':')[1] + - "*sizeof(Digital_State_t));" - ) - cm_count_output = cm_count_output + 1 - - load_in_port = [] - for item in self.input_port: - load_in_port.append( - "for(Ii=0;Iih_addr); - bzero(&(server_addr.sin_zero),8); - - ''' - - connect_server = ''' - fprintf(log_client,"Client-Connecting to server \\n"); - - //Connecting to server - int try_limit=10; - while(try_limit>0) - { - if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ - '''sizeof(struct sockaddr)) == -1) - { - sleep(1); - try_limit--; - if(try_limit==0) - { - fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ - '''failed...giving up \\n"); - fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ - '''port, failed...giving up \\n"); - exit(1); - } - } - else - { - printf("Client-Connected to server \\n"); - fprintf(log_client,"Client-Connected to server \\n"); - break; - } - } - ''' - - # Assign bit value to every input - assign_data_to_input = [] - for item in self.input_port: - assign_data_to_input.append("\tfor(Ii=0;Ii - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - ''' - - function_open = ( - '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') - - digital_state_output = [] - for item in self.output_port: - digital_state_output.append( - "Digital_State_t *_op_" + item.split(':')[0] + - ", *_op_" + item.split(':')[0] + "_old;" - ) - - var_section = ''' - // Declaring components of Client - FILE *log_client = NULL; - log_client=fopen("client.log","a"); - int socket_fd, bytes_recieved; - char send_data[1024]; - char recv_data[1024]; - char *key_iter; - struct hostent *host; - struct sockaddr_in server_addr; - int sock_port = 5000+PARAM(instance_id); - ''' - - temp_input_var = [] - for item in self.input_port: - temp_input_var.append( - "char temp_" + item.split(':')[0] + "[1024];" - ) - - # Start of INIT function - init_start_function = ''' - if(INIT) - { - /* Allocate storage for output ports ''' \ - '''and set the load for input ports */ - ''' - - cm_event_alloc = [] - cm_count_output = 0 - for item in self.output_port: - cm_event_alloc.append( - "cm_event_alloc(" + - str(cm_count_output) + "," + item.split(':')[1] + - "*sizeof(Digital_State_t));" - ) - cm_count_output = cm_count_output + 1 - - load_in_port = [] - for item in self.input_port: - load_in_port.append( - "for(Ii=0;Iih_addr); - bzero(&(server_addr.sin_zero),8); - ''' - - connect_server = ''' - fprintf(log_client,"Client-Connecting to server \\n"); - //Connecting to server - int try_limit=10; - while(try_limit>0) - { - if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ - '''sizeof(struct sockaddr)) == -1) - { - sleep(1); - try_limit--; - if(try_limit==0) - { - fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ - '''failed...giving up \\n"); - fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ - '''port, failed...giving up \\n"); - exit(1); - } - } - else - { - printf("Client-Connected to server \\n"); - fprintf(log_client,"Client-Connected to server \\n"); - break; - } - } - ''' - - # Assign bit value to every input - assign_data_to_input = [] - for item in self.input_port: - assign_data_to_input.append("\tfor(Ii=0;Ii " + item.split(':')[0] + ",\n") - - for item in self.output_port: - if self.output_port.index(item) == len(self.output_port) - 1: - map.append("\t\t\t\t" + item.split(':')[0] + - " => " + item.split(':')[0] + "\n") - else: - map.append("\t\t\t\t" + item.split(':')[0] + - " => " + item.split(':')[0] + ",\n") - map.append("\t\t\t);") - - # Testbench Clock - tb_clk = "clk_s <= not clk_s after 5 us;\n\n" - - # Adding Process block for Vhpi - process_Vhpi = [] - process_Vhpi.append( - "process\n\t\tvariable sock_port : integer;" + - "\n\t\ttype string_ptr is access string;" + - "\n\t\tvariable sock_ip : string_ptr;" + - "\n\t\tbegin\n\t\tsock_port := sock_port_fun;" + - "\n\t\tsock_ip := new string'(sock_ip_fun);" + - "\n\t\tVhpi_Initialize(sock_port," + - "Pack_String_To_Vhpi_String(sock_ip.all));" + - "\n\t\twait until clk_s = '1';" + - "\n\t\twhile true loop\n\t\t\twait until clk_s = '0';" + - "\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\t" + - "Vhpi_Send;" + - "\n\t\tend loop;\n\t\twait;\n\tend process;\n\n" - ) - - # Adding process block - process = [] - process.append("\tprocess\n") - process.append("\t\tvariable count : integer:=0;\n") - - for item in self.input_port: - process.append( - "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" - ) - - for item in self.output_port: - process.append( - "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" - ) - - process.append("\t\tvariable obj_ref : VhpiString;\n") - process.append("\tbegin\n") - process.append("\t\twhile true loop\n") - process.append("\t\t\twait until clk_s = '0';\n\n") - - port_vector_count = 0 - - for item in self.input_port: - process.append( - '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + - item.split(':')[0] + '");\n' - ) - process.append( - '\t\t\tVhpi_Get_Port_Value(obj_ref,' + - item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' - ) - - if self.port_vector_info[port_vector_count]: - process.append( - '\t\t\t' + item.split(':')[0] + - ' <= Unpack_String(' + item.split(':')[0] + '_v,' + - item.split(':')[1] + ');\n' - ) - else: - process.append( - '\t\t\t' + item.split(':')[0] + - ' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n' - ) - - port_vector_count += 1 - process.append("\n") - - process.append('\t\t\twait for 1 us;\n') - - for item in self.output_port: - if self.port_vector_info[port_vector_count]: - process.append( - '\t\t\t' + item.split(':')[0] + - '_v := Pack_String_To_Vhpi_String' + - '(Convert_SLV_To_String(' + - item.split(':')[0]+'));\n' - ) - else: - process.append( - '\t\t\t' + item.split(':')[0] + - '_v := Pack_String_To_Vhpi_String(To_String(' + - item.split(':')[0]+'));\n' - ) - - port_vector_count += 1 - - process.append( - '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + - item.split(':')[0]+'");\n' - ) - process.append( - '\t\t\tVhpi_Set_Port_Value(obj_ref,' + - item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' - ) - process.append("\n") - - process.append( - '\t\t\treport "Iteration - "' + - "& integer'image(count) severity note;\n" - ) - process.append('\t\t\tcount := count + 1;\n') - process.append("\t\tend loop;\n") - process.append("\tend process;\n\n") - process.append("end architecture;") - - # Writing all the components to testbench file - testbench.write(comment_vhdl) - testbench.write(tb_header) - testbench.write(tb_entity) - testbench.write(arch) - - for item in components: - testbench.write(item) - - for item in signals: - testbench.write(item) - - testbench.write("\n\n") - - testbench.write("begin\n\n") - - for item in map: - testbench.write(item) - - testbench.write("\n\t"+tb_clk) - - for item in process_Vhpi: - testbench.write(item) - - for item in process: - testbench.write(item) - - testbench.close() - - def createServerScript(self): - - # ####### Creating and writing components in start_server.sh ####### # - self.digital_home = self.parser.get('NGSPICE', 'DIGITAL_MODEL') - - start_server = open('start_server.sh', 'w') - - start_server.write("#!/bin/bash\n\n") - start_server.write( - "###This server run ghdl testebench for infinite time till " + - "ngspice send END signal to stop it\n\n" - ) - #08.June.2020 - BM - Use correct path with respect to particular OS - if os.name == 'nt': - pathstr = self.digital_home + "/" + \ - self.fname.split('.')[0] + "/DUTghdl/" - pathstr = pathstr.replace("\\", "/") - start_server.write("cd "+pathstr+"\n") - else: - start_server.write("cd "+self.digital_home + - "/" + self.fname.split('.')[0] + "/DUTghdl/\n") - start_server.write("chmod 775 sock_pkg_create.sh &&\n") - start_server.write("./sock_pkg_create.sh $1 $2 &&\n") - start_server.write("ghdl -i *.vhdl &&\n") - start_server.write("ghdl -a *.vhdl &&\n") - start_server.write("ghdl -a "+self.fname+" &&\n") - start_server.write( - "ghdl -a "+self.fname.split('.')[0]+"_tb.vhdl &&\n" - ) - #08.June.2020 - BM - If OS i Windows, link server with libws2_32.a - if os.name == 'nt': - start_server.write("ghdl -e -Wl,ghdlserver.o " + - "-Wl,libws2_32.a " + self.fname.split('.')[0] + "_tb &&\n") - start_server.write("./"+self.fname.split('.')[0]+"_tb.exe") - else: - start_server.write("ghdl -e -Wl,ghdlserver.o " + - self.fname.split('.')[0] + "_tb &&\n") - start_server.write("./"+self.fname.split('.')[0]+"_tb") - - start_server.close() - - def createSockScript(self): - - # ########### Creating and writing in sock_pkg_create.sh ########### # - - sock_pkg_create = open('sock_pkg_create.sh', 'w') - - sock_pkg_create.write("#!/bin/bash\n\n") - sock_pkg_create.write( - "##This file creates sock_pkg.vhdl file and sets the port " + - "and ip from parameters passed to it\n\n" - ) - sock_pkg_create.write("echo \"library ieee;\n") - sock_pkg_create.write("package sock_pkg is\n") - sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") - sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") - sock_pkg_create.write("end;\n\n") - sock_pkg_create.write("package body sock_pkg is\n") - sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") - sock_pkg_create.write("\t\tvariable sock_port : integer;\n") - sock_pkg_create.write("\t\t\tbegin\n") - sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") - sock_pkg_create.write("\t\t\t\treturn sock_port;\n") - sock_pkg_create.write("\t\t\tend function;\n\n") - sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") - sock_pkg_create.write("\t\ttype string_ptr is access string;\n") - sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") - sock_pkg_create.write("\t\t\tbegin\n") - sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') - sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") - sock_pkg_create.write("\t\t\tend function;\n\n") - sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl") +#!/usr/bin/python3 + +import re +import os +from configparser import SafeConfigParser + + +class ModelGeneration: + + def __init__(self, file): + + # Script starts from here + print("Arguement is : ", file) + self.fname = os.path.basename(file) + print("VHDL filename is : ", self.fname) + self.home = os.path.expanduser("~") + self.parser = SafeConfigParser() + self.parser.read(os.path.join( + self.home, os.path.join('.nghdl', 'config.ini'))) + self.ngspice_home = self.parser.get('NGSPICE', 'NGSPICE_HOME') + self.release_dir = self.parser.get('NGSPICE', 'RELEASE') + self.src_home = self.parser.get('SRC', 'SRC_HOME') + self.licensefile = self.parser.get('SRC', 'LICENSE') + + # #### Creating connection_info.txt file from vhdl file #### # + read_vhdl = open(file, 'r') + vhdl_data = read_vhdl.readlines() + read_vhdl.close() + + start_flag = -1 # Used for scaning part of data + scan_data = [] + # p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() + + for item in vhdl_data: + if re.search('port', item, re.I): + start_flag = 1 + + elif re.search("end", item, re.I): + start_flag = 0 + + if start_flag == 1: + item = re.sub("port", " ", item, flags=re.I) + item = re.sub("\(", " ", item, flags=re.I) # noqa + item = re.sub("\)", " ", item, flags=re.I) # noqa + item = re.sub(";", " ", item, flags=re.I) + + scan_data.append(item.rstrip()) + scan_data = [_f for _f in scan_data if _f] + elif start_flag == 0: + break + + port_info = [] + self.port_vector_info = [] + + for item in scan_data: + print("Scan Data :", item) + if re.search("in", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of input port") + elif re.search("out", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of output port") + else: + raise ValueError( + "Please check the in/out direction of your port" + ) + + lhs = temp.split(item)[0] + rhs = temp.split(item)[1] + bit_info = re.compile(r"\s*downto\s*", flags=re.I).split(rhs)[0] + if bit_info: + port_info.append(lhs + ":" + str(int(bit_info) + int(1))) + self.port_vector_info.append(1) + else: + port_info.append(lhs + ":" + str(int(1))) + self.port_vector_info.append(0) + + print("Port Info :", port_info) + + # Open connection_info.txt file + con_ifo = open('connection_info.txt', 'w') + + for item in port_info: + word = item.split(':') + con_ifo.write( + word[0].strip() + ' ' + word[1].strip() + ' ' + word[2].strip() + ) + con_ifo.write("\n") + con_ifo.close() + + def readPortInfo(self): + + # ############## Reading connection/port information ############## # + + # Declaring input and output list + input_list = [] + output_list = [] + + # Reading connection_info.txt file for port infomation + read_file = open('connection_info.txt', 'r') + data = read_file.readlines() + read_file.close() + + # Extracting input and output port list from data + print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") + for line in data: + print(line) + if re.match(r'^\s*$', line): + pass + else: + in_items = re.findall( + "IN", line, re.MULTILINE | re.IGNORECASE + ) + out_items = re.findall( + "OUT", line, re.MULTILINE | re.IGNORECASE + ) + if in_items: + input_list.append(line.split()) + + if out_items: + output_list.append(line.split()) + + print("Inout List :", input_list) + print("Output list", output_list) + + self.input_port = [] + self.output_port = [] + + # creating list of input and output port with its weight + for input in input_list: + self.input_port.append(input[0]+":"+input[2]) + for output in output_list: + self.output_port.append(output[0]+":"+output[2]) + + print("Output Port List : ", self.output_port) + print("Input Port List : ", self.input_port) + + def createCfuncModFile(self): + + # ############## Creating content for cfunc.mod file ############## # + + print("Starting With cfunc.mod file") + cfunc = open('cfunc.mod', 'w') + print("Building content for cfunc.mod file") + + comment = '''/* This is cfunc.mod file auto generated by gen_con_info.py + Developed by Fahim, Rahul at IIT Bombay */\n + ''' + + header = ''' + #include + #include + #include + #include + #include + #include + #include + #include + + ''' + + if os.name == 'nt': + header += ''' + #undef BOOLEAN + #include + ''' + else: + header += ''' + #include + #include + #include + ''' + + function_open = ( + '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') + + digital_state_output = [] + for item in self.output_port: + digital_state_output.append( + "Digital_State_t *_op_" + item.split(':')[0] + + ", *_op_" + item.split(':')[0] + "_old;" + ) + + var_section = ''' + // Declaring components of Client + FILE *log_client = NULL; + log_client=fopen("client.log","a"); + int bytes_recieved; + char send_data[1024]; + char recv_data[1024]; + char *key_iter; + struct hostent *host; + struct sockaddr_in server_addr; + int sock_port = 5000+PARAM(instance_id); + ''' + + if os.name != 'nt': + var_section += ''' + int socket_fd; + ''' + + temp_input_var = [] + for item in self.input_port: + temp_input_var.append( + "char temp_" + item.split(':')[0] + "[1024];" + ) + + # Start of INIT function + init_start_function = ''' + if(INIT) + { + /* Allocate storage for output ports ''' \ + '''and set the load for input ports */ + ''' + + cm_event_alloc = [] + cm_count_output = 0 + for item in self.output_port: + cm_event_alloc.append( + "cm_event_alloc(" + + str(cm_count_output) + "," + item.split(':')[1] + + "*sizeof(Digital_State_t));" + ) + cm_count_output = cm_count_output + 1 + + load_in_port = [] + for item in self.input_port: + load_in_port.append( + "for(Ii=0;Iih_addr); + bzero(&(server_addr.sin_zero),8); + + ''' + + connect_server = ''' + fprintf(log_client,"Client-Connecting to server \\n"); + + //Connecting to server + int try_limit=10; + while(try_limit>0) + { + if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ + '''sizeof(struct sockaddr)) == -1) + { + sleep(1); + try_limit--; + if(try_limit==0) + { + fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ + '''failed...giving up \\n"); + fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ + '''port, failed...giving up \\n"); + exit(1); + } + } + else + { + printf("Client-Connected to server \\n"); + fprintf(log_client,"Client-Connected to server \\n"); + break; + } + } + ''' + + # Assign bit value to every input + assign_data_to_input = [] + for item in self.input_port: + assign_data_to_input.append("\tfor(Ii=0;Ii " + item.split(':')[0] + ",\n") + + for item in self.output_port: + if self.output_port.index(item) == len(self.output_port) - 1: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + "\n") + else: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + ",\n") + map.append("\t\t\t);") + + # Testbench Clock + tb_clk = "clk_s <= not clk_s after 5 us;\n\n" + + # Adding Process block for Vhpi + process_Vhpi = [] + process_Vhpi.append( + "process\n\t\tvariable sock_port : integer;" + + "\n\t\ttype string_ptr is access string;" + + "\n\t\tvariable sock_ip : string_ptr;" + + "\n\t\tbegin\n\t\tsock_port := sock_port_fun;" + + "\n\t\tsock_ip := new string'(sock_ip_fun);" + + "\n\t\tVhpi_Initialize(sock_port," + + "Pack_String_To_Vhpi_String(sock_ip.all));" + + "\n\t\twait until clk_s = '1';" + + "\n\t\twhile true loop\n\t\t\twait until clk_s = '0';" + + "\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\t" + + "Vhpi_Send;" + + "\n\t\tend loop;\n\t\twait;\n\tend process;\n\n" + ) + + # Adding process block + process = [] + process.append("\tprocess\n") + process.append("\t\tvariable count : integer:=0;\n") + + for item in self.input_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + for item in self.output_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + process.append("\t\tvariable obj_ref : VhpiString;\n") + process.append("\tbegin\n") + process.append("\t\twhile true loop\n") + process.append("\t\t\twait until clk_s = '0';\n\n") + + port_vector_count = 0 + + for item in self.input_port: + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0] + '");\n' + ) + process.append( + '\t\t\tVhpi_Get_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= Unpack_String(' + item.split(':')[0] + '_v,' + + item.split(':')[1] + ');\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n' + ) + + port_vector_count += 1 + process.append("\n") + + process.append('\t\t\twait for 1 us;\n') + + for item in self.output_port: + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String' + + '(Convert_SLV_To_String(' + + item.split(':')[0]+'));\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String(To_String(' + + item.split(':')[0]+'));\n' + ) + + port_vector_count += 1 + + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0]+'");\n' + ) + process.append( + '\t\t\tVhpi_Set_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + process.append("\n") + + process.append( + '\t\t\treport "Iteration - "' + + "& integer'image(count) severity note;\n" + ) + process.append('\t\t\tcount := count + 1;\n') + process.append("\t\tend loop;\n") + process.append("\tend process;\n\n") + process.append("end architecture;") + + # Writing all the components to testbench file + testbench.write(comment_vhdl) + testbench.write(tb_header) + testbench.write(tb_entity) + testbench.write(arch) + + for item in components: + testbench.write(item) + + for item in signals: + testbench.write(item) + + testbench.write("\n\n") + + testbench.write("begin\n\n") + + for item in map: + testbench.write(item) + + testbench.write("\n\t"+tb_clk) + + for item in process_Vhpi: + testbench.write(item) + + for item in process: + testbench.write(item) + + testbench.close() + + def createServerScript(self): + + # ####### Creating and writing components in start_server.sh ####### # + self.digital_home = self.parser.get('NGSPICE', 'DIGITAL_MODEL') + + start_server = open('start_server.sh', 'w') + + start_server.write("#!/bin/bash\n\n") + start_server.write( + "###This server run ghdl testebench for infinite time till " + + "ngspice send END signal to stop it\n\n" + ) + + if os.name == 'nt': + pathstr = self.digital_home + "/" + \ + self.fname.split('.')[0] + "/DUTghdl/" + pathstr = pathstr.replace("\\", "/") + start_server.write("cd "+pathstr+"\n") + else: + start_server.write("cd "+self.digital_home + + "/" + self.fname.split('.')[0] + "/DUTghdl/\n") + + start_server.write("chmod 775 sock_pkg_create.sh &&\n") + start_server.write("./sock_pkg_create.sh $1 $2 &&\n") + start_server.write("ghdl -i *.vhdl &&\n") + start_server.write("ghdl -a *.vhdl &&\n") + start_server.write("ghdl -a "+self.fname+" &&\n") + start_server.write( + "ghdl -a "+self.fname.split('.')[0]+"_tb.vhdl &&\n" + ) + + if os.name == 'nt': + start_server.write("ghdl -e -Wl,ghdlserver.o " + + "-Wl,libws2_32.a " + self.fname.split('.')[0] + "_tb &&\n") + start_server.write("./"+self.fname.split('.')[0]+"_tb.exe") + else: + start_server.write("ghdl -e -Wl,ghdlserver.o " + + self.fname.split('.')[0] + "_tb &&\n") + start_server.write("./"+self.fname.split('.')[0]+"_tb") + + start_server.close() + + def createSockScript(self): + + # ########### Creating and writing in sock_pkg_create.sh ########### # + + sock_pkg_create = open('sock_pkg_create.sh', 'w') + + sock_pkg_create.write("#!/bin/bash\n\n") + sock_pkg_create.write( + "##This file creates sock_pkg.vhdl file and sets the port " + + "and ip from parameters passed to it\n\n" + ) + sock_pkg_create.write("echo \"library ieee;\n") + sock_pkg_create.write("package sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") + sock_pkg_create.write("end;\n\n") + sock_pkg_create.write("package body sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") + sock_pkg_create.write("\t\tvariable sock_port : integer;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") + sock_pkg_create.write("\t\t\t\treturn sock_port;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") + sock_pkg_create.write("\t\ttype string_ptr is access string;\n") + sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') + sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl") diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 06921ad..e873555 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -2,15 +2,14 @@ # This file create the gui to install code model in the ngspice. -#08.June.2020 - Bladen Martin - Added if-else constructs to make code OS independent# import os +import sys import shutil import subprocess -import sys -from configparser import SafeConfigParser -from PyQt4 import QtCore from PyQt4 import QtGui +from PyQt4 import QtCore +from configparser import SafeConfigParser from Appconfig import Appconfig from createKicadLibrary import AutoSchematic from model_generation import ModelGeneration @@ -141,7 +140,6 @@ class Mainwindow(QtGui.QWidget): ) if ret == QtGui.QMessageBox.Ok: print("Overwriting existing model " + self.modelname) - #08.June.2020 - BM - Delete existing model directory if os.name == 'nt': cmd = "rmdir " + self.modelname + "/s /q" else: @@ -219,16 +217,18 @@ class Mainwindow(QtGui.QWidget): "/src/ghdlserver/Utility_Package.vhdl", path + "/DUTghdl/") shutil.copy(os.path.join(self.home, self.src_home) + "/src/ghdlserver/Vhpi_Package.vhdl", path + "/DUTghdl/") - #08.June.2020 - BM - If OS is Windows, copy C library libws2_32.a to DUTghl be linked with server by GHDL + if os.name == 'nt': shutil.copy(os.path.join(self.home, self.src_home) + "/src/ghdlserver/libws2_32.a", path + "/DUTghdl/") + for file in self.file_list: shutil.copy(str(file), path + "/DUTghdl/") + os.chdir(path + "/DUTghdl") - #08.June.2020 - BM - Run following commands as per OS. Use bash.exe provided by MSYS for Windows if os.name == 'nt': - self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') #path to msys bin directory where bash is located + # path to msys bin directory where bash is located + self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') subprocess.call(self.msys_bin+"/bash.exe " + path + "/DUTghdl/compile.sh", shell=True) subprocess.call(self.msys_bin+"/bash.exe -c " + @@ -239,11 +239,9 @@ class Mainwindow(QtGui.QWidget): subprocess.call("bash " + path + "/DUTghdl/compile.sh", shell=True) subprocess.call("chmod a+x start_server.sh", shell=True) subprocess.call("chmod a+x sock_pkg_create.sh", shell=True) + os.remove("compile.sh") os.remove("ghdlserver.c") - # os.remove("ghdlserver.h") - # os.remove("Utility_Package.vhdl") - # os.remove("Vhpi_Package.vhdl") # Slot to redirect stdout and stderr to window console @QtCore.pyqtSlot() @@ -259,17 +257,17 @@ class Mainwindow(QtGui.QWidget): def runMake(self): print("run Make Called") self.release_home = self.parser.get('NGSPICE', 'RELEASE') - #08.June.2020 - BM - Changed make location to .../ngspice-nghdl/release/src/xspice/icm path_icm = os.path.join(self.release_home, "src/xspice/icm") - print(path_icm) os.chdir(path_icm) + try: - #08.June.2020 - BM - Use make.exe provided by MSYS for Windows if os.name == 'nt': - self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') #path to msys bin directory where make is located - cmd = self.msys_bin+"\make.exe" + # path to msys bin directory where make is located + self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') + cmd = self.msys_bin+"\\make.exe" else: cmd = " make" + print("Running Make command in " + path_icm) path = os.getcwd() # noqa self.process = QtCore.QProcess(self) @@ -284,7 +282,7 @@ class Mainwindow(QtGui.QWidget): try: if os.name == 'nt': self.msys_bin = self.parser.get('COMPILER', 'MSYS_HOME') - cmd = self.msys_bin+"\make.exe install" + cmd = self.msys_bin+"\\make.exe install" else: cmd = " make install" print("Running Make Install") -- cgit From 0d7dc23ae2b9e8a9d21dbb318195f64cbd7bb3dc Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Tue, 14 Jul 2020 11:56:28 +0530 Subject: cleaned up code --- src/ghdlserver/ghdlserver.c | 1022 ++++++++++++++++++++++--------------------- src/ghdlserver/ghdlserver.h | 22 +- 2 files changed, 528 insertions(+), 516 deletions(-) (limited to 'src') diff --git a/src/ghdlserver/ghdlserver.c b/src/ghdlserver/ghdlserver.c index ec817fd..f2b632d 100644 --- a/src/ghdlserver/ghdlserver.c +++ b/src/ghdlserver/ghdlserver.c @@ -1,503 +1,521 @@ -/********************************************************************************** - * FOSSEE, IIT-Bombay - ********************************************************************************** - * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking - * - Close previous used socket to prevent from - * generating too many socket descriptors - * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options - * 26.Sept.2019 - Rahul Paknikar - Added reading of IP from a file to - * support multiple digital models - * - On exit, the test bench removes the - * NGHDL_COMMON_IP_ file, shared by all - * nghdl digital models and is stored in /tmp - * directory. It tracks the used IPs for existing - * digital models in current simulation. - * - Writes PID file in append mode. - * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for - * a given event. - * - Removed bug to terminate multiple testbench - * instances in ngpsice windows. - ********************************************************************************** - ********************************************************************************** - * 24.Mar.2017 - Raj Mohan - Added signal handler for SIGUSR1, to handle an - * orphan test bench process. - * The test bench will now create a PID file in - * /tmp directory with the name - * NGHDL___ - * This file contains the PID of the test bench . - * On exit, the test bench removes this file. - * The SIGUSR1 signal serves the same purpose as the - * "End" signal. - * - Added //syslog interface for logging. - * - Enabled SO_REUSEADDR socket option. - * - Added the following functions: - * o create_pid_file() - * o get_ngspice_pid() - * 22.Feb.2017 - Raj Mohan - Implemented a kludge to fix a problem in the - * test bench VHDL code. - * - Changed sleep() to nanosleep(). - * 10.Feb.2017 - Raj Mohan - Log messages with timestamp/code clean up. - * Added the following functions: - * o curtim() - * o print_hash_table() - *********************************************************************************/ - -#include -#include "ghdlserver.h" -#include "uthash.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#include -#include -#endif - -#ifdef __linux__ -#include -#include -#include -#include -#include -#endif - -#define _XOPEN_SOURCE 500 -#define MAX_NUMBER_PORT 100 -#define NGSPICE "ngspice" // 17.Mar.2017 - RM - -static FILE *pid_file; -static char pid_filename[80]; -static char *Out_Port_Array[MAX_NUMBER_PORT]; -static int out_port_num = 0; - -static int server_socket_id = -1; - -static int sendto_sock; // 22.Feb.2017 - RM - Kludge -static int prev_sendto_sock; // 22.Feb.2017 - RM - Kludge -static int pid_file_created; // 10.Mar.2017 - RM - -#ifdef __linux__ -extern char *__progname; // 26.Feb.2017 May not be portable to non-GNU systems. -#endif - -void Vhpi_Exit(int sig); - -struct my_struct -{ - char val[1024]; - char key[1024]; - UT_hash_handle hh; //Makes this structure hashable. -}; - -static struct my_struct *s, *users, *tmp = NULL; - -#ifdef DEBUG -static char *curtim(void) -{ - static char ct[50]; - struct timeval tv; - struct tm *ptm; - long milliseconds; - char time_string[40]; - - gettimeofday(&tv, NULL); - ptm = localtime(&tv.tv_sec); - strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); - milliseconds = tv.tv_usec / 1000; - sprintf(ct, "%s.%03ld", time_string, milliseconds); - return (ct); -} -#endif - -#ifdef DEBUG -static void print_hash_table(void) -{ - struct my_struct *sptr; - - for (sptr = users; sptr != NULL; sptr = sptr->hh.next) - //syslog(LOG_INFO, "Hash table:val:%s: key: %s", sptr->val, sptr->key); -} -#endif - -static void parse_buffer(int sock_id, char *receive_buffer) -{ - static int rcvnum; - -#ifdef __linux__ - //syslog(LOG_INFO, "RCVD RCVN:%d from CLT:%d buffer : %s", rcvnum++, sock_id, receive_buffer); -#endif - - /*Parsing buffer to store in hash table */ - char *rest; - char *token; - char *ptr1 = receive_buffer; - char *var; - char *value; - - // Processing tokens. - while (token = strtok_r(ptr1, ",", &rest)) - { - ptr1 = rest; - while (var = strtok_r(token, ":", &value)) - { - s = (struct my_struct *)malloc(sizeof(struct my_struct)); - strncpy(s->key, var, 64); - strncpy(s->val, value, 64); - HASH_ADD_STR(users, key, s); - break; - } - } - - s = (struct my_struct *)malloc(sizeof(struct my_struct)); - strncpy(s->key, "sock_id", 64); - snprintf(s->val, 64, "%d", sock_id); - HASH_ADD_STR(users, key, s); -} - -//Create Server and listen for client connections. -// 26.Sept.2019 - RP - added parameter of socket ip - -static int create_server(int port_number, char my_ip[], int max_connections) -{ - int sockfd, reuse = 1; - struct sockaddr_in serv_addr; - - sockfd = socket(AF_INET, SOCK_STREAM, 0); - - if (sockfd < 0) - { -#ifdef __linux__ - fprintf(stderr, "%s- Error: in opening socket at server \n", __progname); -#endif -#ifdef _WIN32 - fprintf(stderr, "Error: in opening socket at server \n"); -#endif - //exit(1); - return -1; - } - - //18.May.2020 - BM - typecast optval field to char * - /* 20.Mar.2017 - RM - SO_REUSEADDR option. To take care of TIME_WAIT state.*/ - int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)); - -/* 08.Nov.2019 - RP - SO_REUSEPORT and SO_DONTROUTE option.*/ -/* 08.June.2020 - B< - SO_REUSEPORT only available in Linux*/ -#ifdef __linux__ - ret += setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)); -#endif - - ret += setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, (char *)&reuse, sizeof(int)); - - if (ret < 0) - { -#ifdef __linux__ - //syslog(LOG_ERR, "create_server:setsockopt() failed...."); -#endif - // close(sockfd); - // return -1; - } - - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(my_ip); // 26.Sept.2019 - RP - Bind to specific IP only - serv_addr.sin_port = htons(port_number); - - if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { -#ifdef __linux__ - fprintf(stderr, "%s- Error: could not bind socket to port %d\n", __progname, port_number); - //syslog(LOG_ERR, "Error: could not bind socket to port %d", port_number); - close(sockfd); -#endif -#ifdef _WIN32 - fprintf(stderr, "Error: could not bind socket to port %d\n", port_number); - closesocket(sockfd); -#endif - exit(1); - } - - // Start listening on the server. - listen(sockfd, max_connections); - - return sockfd; -} - -// The server to wait (blocking) for a client connection. -static int connect_to_client(int server_fd) -{ - int ret_val = 0; - int newsockfd = -1; - socklen_t clilen; - struct sockaddr_in cli_addr; - - clilen = sizeof(cli_addr); - - /* 08.Nov.2019 - RP - Blocking Socket (Accept) */ - newsockfd = accept(server_fd, (struct sockaddr *)&cli_addr, &clilen); - if (newsockfd >= 0) - { -#ifdef _linux_ - //syslog(LOG_INFO, "SRV:%d New Client Connection CLT:%d", server_fd, newsockfd); -#endif - } - else - { -#ifdef __linux__ - //syslog(LOG_ERR, "Error: failed in accept(), socket=%d", server_fd); -#endif - - exit(1); - } - - return newsockfd; -} - -//Receive string from socket and put it inside buffer. -static void receive_string(int sock_id, char *buffer) -{ - int nbytes = 0; - - /* 08.Nov.2019 - RP - Blocking Socket - Receive */ - nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); - if (nbytes <= 0) - { - perror("receive_string() - READ FAILURE "); - exit(1); - } - /* 08.June.2020 - BM - Added condition to close on recieving close message - from outitf.c patch after simulation is over*/ - char *compstr = "CLOSE_FROM_NGSPICE"; - if (strcmp(buffer, compstr) == 0) - { - Vhpi_Exit(1); - } -} - -static void Data_Send(int sockid) -{ - static int trnum; - char *out; - - int i; - char colon = ':'; - char semicolon = ';'; - int wrt_retries = 0; - int ret; - - s = NULL; - - out = calloc(1, 2048); - - // 5.July.2019 - RP - loop to send all ports at once for an event - for (i = 0; i < out_port_num; i++) - { - HASH_FIND_STR(users, Out_Port_Array[i], s); - if (strcmp(Out_Port_Array[i], s->key) == 0) - { - strncat(out, s->key, strlen(s->key)); - strncat(out, &colon, 1); - strncat(out, s->val, strlen(s->val)); - strncat(out, &semicolon, 1); - } - else - { -#ifdef __linux__ - //syslog(LOG_ERR, "The %s's value not found in the table.", Out_Port_Array[i]); -#endif - free(out); - return; - } - } - - /* 08.Nov.2019 - RP - Blocking Socket (Send) */ - if ((send(sockid, out, strlen(out), 0)) == -1) - { -#ifdef __linux__ - //syslog(LOG_ERR, "Failure sending to CLT:%d buffer:%s", sockid, out); -#endif - exit(1); - } -#ifdef __linux__ - //syslog(LOG_INFO, "SNT:TRNUM:%d to CLT:%d buffer: %s", trnum++, sockid, out); -#endif - free(out); -} - -// 26.Sept.2019 - RP - added parameter of socket ip -void Vhpi_Initialize(int sock_port, char sock_ip[]) -{ - DEFAULT_SERVER_PORT = sock_port; - - signal(SIGINT, Vhpi_Exit); - signal(SIGTERM, Vhpi_Exit); - //signal(SIGUSR1, Vhpi_Exit); //10.Mar.2017 - RM - -#ifdef _WIN32 - WSADATA WSAData; - WSAStartup(MAKEWORD(2, 2), &WSAData); -#endif - - int try_limit = 100; - - while (try_limit > 0) - { - // 26.Sept.2019 - RP - server_socket_id = create_server(DEFAULT_SERVER_PORT, sock_ip, DEFAULT_MAX_CONNECTIONS); - - if (server_socket_id >= 0) - { -#ifdef __linux__ - //syslog(LOG_INFO, "Started the server on port %d SRV:%d", DEFAULT_SERVER_PORT, server_socket_id); -#endif - goto whileout; - } -#ifdef __linux__ - //syslog(LOG_ERR, "Could not start server on port %d,will try again", DEFAULT_SERVER_PORT); -#endif - usleep(1000); - try_limit--; - - if (try_limit == 0) - { -#ifdef __linux__ - //syslog(LOG_ERR, "Error:Tried to start server on port %d, failed..giving up.", DEFAULT_SERVER_PORT); -#endif - exit(1); - } - } - -whileout: - printf(""); - //Reading Output Port name and storing in Out_Port_Array; - char *line = NULL; - size_t len = 0; - ssize_t read; - char *token; - FILE *fp; - struct timespec ts; - - fp = fopen("connection_info.txt", "r"); - if (!fp) - { -#ifdef __linux__ - //syslog(LOG_ERR, "Vhpi_Initialize: Failed to open connection_info.txt. Exiting..."); -#endif - exit(1); - } - - line = (char *)malloc(80); -#ifdef __linux__ - while ((read = getline(&line, &len, fp)) != -1) - { - if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) - { - strtok_r(line, " ", &token); - Out_Port_Array[out_port_num] = line; - out_port_num++; - } - line = (char *)malloc(80); - } -#endif -#ifdef _WIN32 - while (fgets(line, sizeof(line), fp) != NULL) - { - if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) - { - strtok_r(line, " ", &token); - Out_Port_Array[out_port_num] = line; - printf("%s \n", line); - out_port_num++; - } - line = (char *)malloc(80); - } -#endif - fclose(fp); - free(line); - - ts.tv_sec = 2; - ts.tv_nsec = 0; - nanosleep(&ts, NULL); -} - -void Vhpi_Set_Port_Value(char *port_name, char *port_value, int port_width) -{ - s = (struct my_struct *)malloc(sizeof(struct my_struct)); - strncpy(s->key, port_name, 64); - strncpy(s->val, port_value, 64); - HASH_ADD_STR(users, key, s); -} - -void Vhpi_Get_Port_Value(char *port_name, char *port_value, int port_width) -{ - HASH_FIND_STR(users, port_name, s); - if (s) - { - snprintf(port_value, sizeof(port_value), "%s", s->val); - HASH_DEL(users, s); - free(s); - s = NULL; - } -} - -void Vhpi_Listen() -{ - sendto_sock = connect_to_client(server_socket_id); // 22.Feb.2017 - RM - Kludge - char receive_buffer[MAX_BUF_SIZE]; - receive_string(sendto_sock, receive_buffer); - -#ifdef __linux__ - //syslog(LOG_INFO, "Vhpi_Listen:New socket connection CLT:%d", sendto_sock); -#endif - - if (strcmp(receive_buffer, "END") == 0) - { -#ifdef __linux__ - //syslog(LOG_INFO, "RCVD:CLOSE REQUEST from CLT:%d", sendto_sock); -#endif - Vhpi_Exit(0); - } - - parse_buffer(sendto_sock, receive_buffer); -} - -void Vhpi_Send() -{ - // 22.Feb.2017 - RM - Kludge - if (prev_sendto_sock != sendto_sock) - { - Data_Send(sendto_sock); -#ifdef __linux__ - close(prev_sendto_sock); // 08.Nov.2019 - RP - Close previous socket -#endif -#ifdef _WIN32 - closesocket(prev_sendto_sock); -#endif - - prev_sendto_sock = sendto_sock; - } - // 22.Feb.2017 End kludge -} - -void Vhpi_Exit(int sig) -{ -#ifdef __linux__ - close(server_socket_id); // 08.Nov.2019 - RP - Close previous socket - //syslog(LOG_INFO, "*** Closed VHPI link. Exiting... ***"); -#endif -#ifdef _WIN32 - closesocket(server_socket_id); -#endif - exit(0); +/************************************************************************************ + * eSim Team, FOSSEE, IIT-Bombay + ************************************************************************************ + * 8.June.2020 - Bladen Martin - Added OS (Windows and Linux) dependent + * - Rahul Paknikar preprocessors for ease of maintenance + * + * 28.May.2020 - Bladen Martin - Termination of testbench: Replaced Process ID + * - Rahul Paknikar mechanism with socket connection from client + * receiving the special close message + ************************************************************************************ + ************************************************************************************ + * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking + * - Close previous used socket to prevent from + * generating too many socket descriptors + * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options + * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for + * a given event. + ************************************************************************************ + ************************************************************************************ + * 24.Mar.2017 - Raj Mohan - Added syslog interface for logging. + * - Enabled SO_REUSEADDR socket option. + * 22.Feb.2017 - Raj Mohan - Implemented a kludge to fix a problem in the + * test bench VHDL code. + * - Changed sleep() to nanosleep(). + * 10.Feb.2017 - Raj Mohan - Log messages with timestamp/code clean up. + * Added the following functions: + * o curtim() + * o print_hash_table() + ***********************************************************************************/ + +#include +#include "ghdlserver.h" +#include "uthash.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ + #include + #include + #include + #include + #include +#elif _WIN32 + #include + #include + #include + #include +#endif + +#define _XOPEN_SOURCE 500 +#define MAX_NUMBER_PORT 100 +#define NGSPICE "ngspice" // 17.Mar.2017 - RM + +static FILE *pid_file; +static char pid_filename[80]; +static char *Out_Port_Array[MAX_NUMBER_PORT]; +static int out_port_num = 0; +static int server_socket_id = -1; +static int sendto_sock; // 22.Feb.2017 - RM - Kludge +static int prev_sendto_sock; // 22.Feb.2017 - RM - Kludge +static int pid_file_created; // 10.Mar.2017 - RM + +#ifdef __linux__ + extern char* __progname; // 26.Feb.2017 May not be portable to non-GNU systems. +#endif + +void Vhpi_Exit(int sig); + +struct my_struct { + char val[1024]; + char key[1024]; + UT_hash_handle hh; //Makes this structure hashable. +}; + +static struct my_struct *s, *users, *tmp = NULL; + + +#ifdef DEBUG +static char* curtim(void) +{ + static char ct[50]; + struct timeval tv; + struct tm *ptm; + long milliseconds; + char time_string[40]; + + gettimeofday (&tv, NULL); + ptm = localtime (&tv.tv_sec); + strftime (time_string, sizeof (time_string), "%Y-%m-%d %H:%M:%S", ptm); + milliseconds = tv.tv_usec / 1000; + sprintf (ct, "%s.%03ld", time_string, milliseconds); + return(ct); +} +#endif + + +#ifdef DEBUG +static void print_hash_table(void) +{ + struct my_struct *sptr; + + #ifdef __linux__ + for(sptr = users; sptr != NULL; sptr = sptr->hh.next) + syslog(LOG_INFO, "Hash table:val:%s: key: %s", sptr->val, sptr->key); + #endif +} +#endif + + +static void parse_buffer(int sock_id, char *receive_buffer) +{ + static int rcvnum; + + #ifdef __linux__ + syslog(LOG_INFO, "RCVD RCVN:%d from CLT:%d buffer : %s", + rcvnum++, sock_id, receive_buffer); + #endif + + /*Parsing buffer to store in hash table */ + char *rest; + char *token; + char *ptr1 = receive_buffer; + char *var; + char *value; + + // Processing tokens. + while (token = strtok_r(ptr1, ",", &rest)) + { + ptr1 = rest; + while (var = strtok_r(token, ":", &value)) + { + s = (struct my_struct *) malloc(sizeof(struct my_struct)); + strncpy(s->key, var, 64); + strncpy(s->val, value, 64); + HASH_ADD_STR(users, key, s); + break; + } + } + + s = (struct my_struct *) malloc(sizeof(struct my_struct)); + strncpy(s->key, "sock_id", 64); + snprintf(s->val, 64, "%d", sock_id); + HASH_ADD_STR(users, key, s); +} + + +//Create Server and listen for client connections. +// 26.Sept.2019 - RP - added parameter of socket ip +static int create_server(int port_number, char my_ip[], int max_connections) +{ + int sockfd, reuse = 1; + struct sockaddr_in serv_addr; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + if (sockfd < 0) + { + #ifdef __linux__ + fprintf(stderr, "%s- Error: in opening socket at server \n", __progname); + + #elif _WIN32 + fprintf(stderr, "Error: in opening socket at server \n"); + + #endif + + //exit(1); + return -1; + } + + /* 18.May.2020 - BM - typecast optval field to char* */ + /* 20.Mar.2017 - RM - SO_REUSEADDR option. To take care of TIME_WAIT state.*/ + int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *) &reuse, sizeof(int)); + + /* 08.Nov.2019 - RP - SO_REUSEPORT and SO_DONTROUTE option.*/ + /* 08.June.2020 - BM - SO_REUSEPORT only available in Linux */ + #ifdef __linux__ + ret += setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)); + #endif + + ret += setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, (char *) &reuse, sizeof(int)); + if (ret < 0) + { + #ifdef __linux__ + syslog(LOG_ERR, "create_server:setsockopt() failed...."); + #endif + // close(sockfd); + // return -1; + } + + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = inet_addr(my_ip); // 26.Sept.2019 - RP - Bind to specific IP only + serv_addr.sin_port = htons(port_number); + + if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) + { + #ifdef __linux__ + fprintf(stderr, "%s- Error: could not bind socket to port %d\n", __progname, port_number); + syslog(LOG_ERR, "Error: could not bind socket to port %d", port_number); + close(sockfd); + + #elif _WIN32 + fprintf(stderr, "Error: could not bind socket to port %d\n", port_number); + closesocket(sockfd); + + #endif + + exit(1); + } + + // Start listening on the server. + listen(sockfd, max_connections); + + return sockfd; +} + + +// The server to wait (blocking) for a client connection. +static int connect_to_client(int server_fd) +{ + int ret_val = 0; + int newsockfd = -1; + socklen_t clilen; + struct sockaddr_in cli_addr; + + clilen = sizeof(cli_addr); + + /* 08.Nov.2019 - RP - Blocking Socket (Accept) */ + newsockfd = accept(server_fd, (struct sockaddr *) &cli_addr, &clilen); + if (newsockfd >= 0) + { + #ifdef _linux_ + syslog(LOG_INFO, "SRV:%d New Client Connection CLT:%d", server_fd, newsockfd); + #endif + } + else + { + #ifdef __linux__ + syslog(LOG_ERR, "Error: failed in accept(), socket=%d", server_fd); + #endif + + exit(1); + } + + return newsockfd; +} + + +//Receive string from socket and put it inside buffer. +static void receive_string(int sock_id, char *buffer) +{ + int nbytes = 0; + + /* 08.Nov.2019 - RP - Blocking Socket - Receive */ + nbytes = recv(sock_id, buffer, MAX_BUF_SIZE, 0); + if (nbytes <= 0) + { + perror("receive_string() - READ FAILURE "); + exit(1); + } + + // 28.May.2020 - BM - Added method to close server by Ngspice after simulation + char *exitstr = "CLOSE_FROM_NGSPICE"; + if (strcmp(buffer, exitstr) == 0) + { + Vhpi_Exit(0); + } +} + + +static void Data_Send(int sockid) +{ + static int trnum; + char *out; + + int i; + char colon = ':'; + char semicolon = ';'; + int wrt_retries = 0; + int ret; + + s = NULL; + + out = calloc(1, 2048); + + // 5.July.2019 - RP - loop to send all ports at once for an event + for (i = 0; i < out_port_num; i++) + { + HASH_FIND_STR(users, Out_Port_Array[i], s); + if (strcmp(Out_Port_Array[i], s->key) == 0) + { + strncat(out, s->key, strlen(s->key)); + strncat(out, &colon, 1); + strncat(out, s->val, strlen(s->val)); + strncat(out, &semicolon, 1); + } + else + { + #ifdef __linux__ + syslog(LOG_ERR,"The %s's value not found in the table.", + Out_Port_Array[i]); + #endif + + free(out); + printf("Error! The %s's value not found in the table. Exiting simulation...", + Out_Port_Array[i]); + return; + } + } + + /* 08.Nov.2019 - RP - Blocking Socket (Send) */ + if ((send(sockid, out, strlen(out), 0)) == -1) + { + #ifdef __linux__ + syslog(LOG_ERR, "Failure sending to CLT:%d buffer:%s", sockid, out); + #endif + + exit(1); + } + + #ifdef __linux__ + syslog(LOG_INFO, "SNT:TRNUM:%d to CLT:%d buffer: %s", trnum++, sockid, out); + #endif + + free(out); +} + + +// 26.Sept.2019 - RP - added parameter of socket ip +void Vhpi_Initialize(int sock_port, char sock_ip[]) +{ + DEFAULT_SERVER_PORT = sock_port; + + signal(SIGINT, Vhpi_Exit); + signal(SIGTERM, Vhpi_Exit); + + #ifdef _WIN32 + WSADATA WSAData; + WSAStartup(MAKEWORD(2, 2), &WSAData); + #endif + + int try_limit = 100; + + while (try_limit > 0) + { + // 26.Sept.2019 - RP + server_socket_id = create_server(DEFAULT_SERVER_PORT, sock_ip, DEFAULT_MAX_CONNECTIONS); + + if (server_socket_id >= 0) + { + #ifdef __linux__ + syslog(LOG_INFO, "Started the server on port %d SRV:%d", + DEFAULT_SERVER_PORT, server_socket_id); + #endif + + break; + } + + #ifdef __linux__ + syslog(LOG_ERR, "Could not start server on port %d,will try again", + DEFAULT_SERVER_PORT); + #endif + + usleep(1000); + try_limit--; + + if (try_limit == 0) + { + #ifdef __linux__ + syslog(LOG_ERR, + "Error:Tried to start server on port %d, failed..giving up.", + DEFAULT_SERVER_PORT); + #endif + + exit(1); + } + } + + //Reading Output Port name and storing in Out_Port_Array; + char *line = NULL; + size_t len = 0; + ssize_t read; + char *token; + FILE *fp; + struct timespec ts; + + fp = fopen("connection_info.txt", "r"); + if (!fp) + { + #ifdef __linux__ + syslog(LOG_ERR,"Vhpi_Initialize: Failed to open connection_info.txt. Exiting..."); + #endif + + exit(1); + } + + line = (char *) malloc(80); + + #ifdef __linux__ + while ((read = getline(&line, &len, fp)) != -1) + { + if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) + { + strtok_r(line, " ", &token); + Out_Port_Array[out_port_num] = line; + out_port_num++; + } + line = (char *) malloc(80); + } + + #elif _WIN32 + while (fgets(line, sizeof(line), fp) != NULL) + { + if (strstr(line, "OUT") != NULL || strstr(line, "out") != NULL) + { + strtok_r(line, " ", &token); + Out_Port_Array[out_port_num] = line; + out_port_num++; + } + line = (char *) malloc(80); + } + + #endif + + fclose(fp); + free(line); + + ts.tv_sec = 2; + ts.tv_nsec = 0; + nanosleep(&ts, NULL); +} + + +void Vhpi_Set_Port_Value(char *port_name, char *port_value, int port_width) +{ + s = (struct my_struct *) malloc(sizeof(struct my_struct)); + strncpy(s->key, port_name, 64); + strncpy(s->val, port_value, 64); + HASH_ADD_STR(users, key, s); +} + + +void Vhpi_Get_Port_Value(char *port_name, char *port_value, int port_width) +{ + HASH_FIND_STR(users, port_name, s); + if (s) + { + snprintf(port_value, sizeof(port_value), "%s", s->val); + HASH_DEL(users, s); + free(s); + s = NULL; + } +} + + +void Vhpi_Listen() +{ + sendto_sock = connect_to_client(server_socket_id); // 22.Feb.2017 - RM - Kludge + char receive_buffer[MAX_BUF_SIZE]; + receive_string(sendto_sock, receive_buffer); + + #ifdef __linux__ + syslog(LOG_INFO, "Vhpi_Listen:New socket connection CLT:%d", sendto_sock); + #endif + + if (strcmp(receive_buffer, "END") == 0) + { + #ifdef __linux__ + syslog(LOG_INFO, "RCVD:CLOSE REQUEST from CLT:%d", sendto_sock); + #endif + + Vhpi_Exit(0); + } + + parse_buffer(sendto_sock, receive_buffer); +} + + +void Vhpi_Send() +{ + // 22.Feb.2017 - RM - Kludge + if (prev_sendto_sock != sendto_sock) + { + Data_Send(sendto_sock); + + #ifdef __linux__ + close(prev_sendto_sock); // 08.Nov.2019 - RP - Close previous socket + + #elif _WIN32 + closesocket(prev_sendto_sock); + + #endif + + prev_sendto_sock = sendto_sock; + } + // 22.Feb.2017 End kludge +} + + +void Vhpi_Exit(int sig) +{ + #ifdef __linux__ + close(server_socket_id); + syslog(LOG_INFO, "*** Closed VHPI link. Exiting... ***"); + + #elif _WIN32 + closesocket(server_socket_id); + + #endif + + exit(0); } \ No newline at end of file diff --git a/src/ghdlserver/ghdlserver.h b/src/ghdlserver/ghdlserver.h index 0011d00..e04209b 100644 --- a/src/ghdlserver/ghdlserver.h +++ b/src/ghdlserver/ghdlserver.h @@ -5,28 +5,22 @@ #include #include - #include #include #include #ifdef __linux__ -#include -#include -#include -#endif - -#ifdef _WIN32 -#include -#include -#include -#include + #include + #include + #include +#elif _WIN32 + #include + #include + #include + #include #endif - - - // Should be enough.. #define MAX_BUF_SIZE 4096 -- cgit From 30678928c1746176de9923025b012c370fd28e0a Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Fri, 17 Jul 2020 21:03:14 +0530 Subject: flake8 compliant and visual indent --- src/createKicadLibrary.py | 13 +++++++------ src/ghdlserver/ghdlserver.c | 6 +++--- src/model_generation.py | 22 +++++++++++++--------- src/outitf.c | 5 +++-- 4 files changed, 26 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/createKicadLibrary.py b/src/createKicadLibrary.py index 2b3e7d7..d7a39d1 100644 --- a/src/createKicadLibrary.py +++ b/src/createKicadLibrary.py @@ -16,7 +16,8 @@ class AutoSchematic(QtGui.QWidget): if os.name == 'nt': eSim_src = Appconfig.src_home inst_dir = eSim_src.replace('\eSim', '') - self.kicad_nghdl_lib = inst_dir + '/KiCad/share/kicad/library/eSim_Nghdl.lib' + self.kicad_nghdl_lib = \ + inst_dir + '/KiCad/share/kicad/library/eSim_Nghdl.lib' else: self.kicad_nghdl_lib = '/usr/share/kicad/library/eSim_Nghdl.lib' self.parser = Appconfig.parser_nghdl @@ -82,17 +83,17 @@ class AutoSchematic(QtGui.QWidget): ET.SubElement(root, "type").text = "Nghdl" ET.SubElement(root, "node_number").text = str(len(self.portInfo)) ET.SubElement(root, "title").text = ( - "Add parameters for " + str(self.modelname)) + "Add parameters for " + str(self.modelname)) ET.SubElement(root, "split").text = self.splitText param = ET.SubElement(root, "param") ET.SubElement(param, "rise_delay", default="1.0e-9").text = ( - "Enter Rise Delay (default=1.0e-9)") + "Enter Rise Delay (default=1.0e-9)") ET.SubElement(param, "fall_delay", default="1.0e-9").text = ( - "Enter Fall Delay (default=1.0e-9)") + "Enter Fall Delay (default=1.0e-9)") ET.SubElement(param, "input_load", default="1.0e-12").text = ( - "Enter Input Load (default=1.0e-12)") + "Enter Input Load (default=1.0e-12)") ET.SubElement(param, "instance_id", default="1").text = ( - "Enter Instance ID (Between 0-99)") + "Enter Instance ID (Between 0-99)") tree = ET.ElementTree(root) tree.write(str(self.modelname) + '.xml') print("Leaving the directory ", xmlDestination) diff --git a/src/ghdlserver/ghdlserver.c b/src/ghdlserver/ghdlserver.c index 410a2ff..f2b632d 100644 --- a/src/ghdlserver/ghdlserver.c +++ b/src/ghdlserver/ghdlserver.c @@ -10,9 +10,9 @@ ************************************************************************************ ************************************************************************************ * 08.Nov.2019 - Rahul Paknikar - Switched to blocking sockets from non-blocking - * - Close previous used socket to prevent from - * generating too many socket descriptors - * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options + * - Close previous used socket to prevent from + * generating too many socket descriptors + * - Enabled SO_REUSEPORT, SO_DONTROUTE socket options * 5.July.2019 - Rahul Paknikar - Added loop to send all port values for * a given event. ************************************************************************************ diff --git a/src/model_generation.py b/src/model_generation.py index 7baecc1..f19a5c9 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -1,5 +1,3 @@ -#!/usr/bin/python3 - import re import os from configparser import SafeConfigParser @@ -289,11 +287,13 @@ class ModelGeneration: if os.name == 'nt': client_setup_ip += ''' - sprintf(ip_filename, "C:/Windows/Temp/NGHDL_COMMON_IP_%d.txt", getpid()); + sprintf(ip_filename, ''' \ + '''"C:/Windows/Temp/NGHDL_COMMON_IP_%d.txt", getpid()); ''' else: client_setup_ip += ''' - sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); + sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt",''' \ + ''' getpid()); ''' client_setup_ip += ''' @@ -495,8 +495,8 @@ class ModelGeneration: \t\t\telse if(*key_iter=='1')\n\t\t\t{\n\ \t\t\t\t_op_" + item.split(':')[0] + "[Ii]=ONE;\n\ \t\t\t}\n\t\t\telse\n\t\t\t{\n\ - \t\t\t\tfprintf(log_client,\"Unknown value return from server \\n\");\n\ - \t\t\t\tprintf(\"Client-Unknown value return \\n\");\n\t\t\t}\n\n\ + \t\t\t\tfprintf(log_client,\"Unknown value return from server \\n\");\ + \n\t\t\t\tprintf(\"Client-Unknown value return \\n\");\n\t\t\t}\n\n\ \t\t\tif(ANALYSIS == DC)\n\t\t\t{\n\ \t\t\t\tOUTPUT_STATE(" + item.split(':')[0] + "[Ii]) = _op_" + item.split(':')[0] + "[Ii];\n\ \t\t\t}\n\t\t\telse if(_op_" + item.split(':')[0] + "[Ii] != _op_" + item.split(':')[0] + "_old[Ii])\n\ @@ -555,8 +555,11 @@ class ModelGeneration: self.digital_home = self.parser.get('NGSPICE', 'DIGITAL_MODEL') self.msys_home = self.parser.get('COMPILER', 'MSYS_HOME') cmd_str2 = "\\'start_server.sh %d %s\\'" + "\\" + "\"" - cmd_str1 = os.path.normpath("\"cd " + self.digital_home + "/" + self.fname.split( - '.')[0] + "/DUTghdl/ && " + self.msys_home + "/bash.exe -c ") + cmd_str1 = os.path.normpath( + "\"cd " + self.digital_home + "/" + + self.fname.split('.')[0] + "/DUTghdl/ && " + + self.msys_home + "/bash.exe -c " + ) cmd_str1 = cmd_str1.replace("\\", "/") cfunc.write('\t\tsnprintf(command,1024, "start /min cmd /c ' + '\\' + cmd_str1 + cmd_str2 + ' &", sock_port, my_ip);') @@ -1072,7 +1075,8 @@ class ModelGeneration: if os.name == 'nt': start_server.write("ghdl -e -Wl,ghdlserver.o " + - "-Wl,libws2_32.a " + self.fname.split('.')[0] + "_tb &&\n") + "-Wl,libws2_32.a " + + self.fname.split('.')[0] + "_tb &&\n") start_server.write("./"+self.fname.split('.')[0]+"_tb.exe") else: start_server.write("ghdl -e -Wl,ghdlserver.o " + diff --git a/src/outitf.c b/src/outitf.c index fe60f7a..9b913ae 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -21,9 +21,9 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include "ngspice/ngspice.h" -/*05.June.2020 - BM - Added follwing includes for Windows OS */ +/*05.June.2020 - BM - Added follwing includes for Win OS */ #ifdef _WIN32 - #undef BOOLEAN /* Undefine it due to conflicting definitions in Windows OS */ + #undef BOOLEAN /* Undefine it due to conflicting definitions in Win OS */ #include #include @@ -211,6 +211,7 @@ static void close_server() #ifdef _WIN32 WSACleanup(); #endif + fclose(fptr); remove(ip_filename); } -- cgit From bef53fae3cf3f55024ffbdfe5886a531d4178300 Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Wed, 5 Aug 2020 23:56:39 +0530 Subject: resolved bug for undefined behavior of fclose --- src/outitf.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index 9b913ae..a4f76d3 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -58,7 +58,6 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski /* 27.May.2020 - BM - Added the following #include */ #ifdef __linux__ - #include #include #include #include @@ -206,13 +205,14 @@ static void close_server() closesocket(sock); #endif } + + fclose(fptr); } #ifdef _WIN32 WSACleanup(); #endif - fclose(fptr); remove(ip_filename); } -- cgit From 0906214c276402584eb2e1910173d271350f8399 Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Thu, 6 Aug 2020 00:34:48 +0530 Subject: ported GUI to PyQt5 --- src/createKicadLibrary.py | 20 ++++++------- src/ngspice_ghdl.py | 71 ++++++++++++++++++++++------------------------- 2 files changed, 43 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/createKicadLibrary.py b/src/createKicadLibrary.py index d7a39d1..65d9a9f 100644 --- a/src/createKicadLibrary.py +++ b/src/createKicadLibrary.py @@ -2,13 +2,13 @@ from Appconfig import Appconfig import re import os import xml.etree.cElementTree as ET -from PyQt4 import QtGui +from PyQt5 import QtWidgets -class AutoSchematic(QtGui.QWidget): +class AutoSchematic(QtWidgets.QWidget): def __init__(self, modelname): - QtGui.QWidget.__init__(self) + QtWidgets.QWidget.__init__(self) self.modelname = modelname.split('.')[0] self.template = Appconfig.kicad_lib_template.copy() self.xml_loc = Appconfig.xml_loc @@ -34,14 +34,14 @@ class AutoSchematic(QtGui.QWidget): self.createLib() elif (xmlFound == os.path.join(self.xml_loc, 'Nghdl')): print('Library already exists...') - ret = QtGui.QMessageBox.warning( + ret = QtWidgets.QMessageBox.warning( self, "Warning", '''Library files for this model ''' + '''already exist. Do you want to overwrite it?
If yes press ok, else cancel it and ''' + '''change the name of your vhdl file.''', - QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel + QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel ) - if ret == QtGui.QMessageBox.Ok: + if ret == QtWidgets.QMessageBox.Ok: print("Overwriting existing libraries") self.getPortInformation() self.createXML() @@ -52,11 +52,11 @@ class AutoSchematic(QtGui.QWidget): quit() else: print('Pre existing library...') - ret = QtGui.QMessageBox.critical( + ret = QtWidgets.QMessageBox.critical( self, "Error", '''A standard library already exists ''' + '''with this name.
Please change the name ''' + '''of your vhdl file and upload it again''', - QtGui.QMessageBox.Ok + QtWidgets.QMessageBox.Ok ) # quit() @@ -230,11 +230,11 @@ class AutoSchematic(QtGui.QWidget): os.chdir(cwd) print('Leaving directory, ', self.lib_loc) - QtGui.QMessageBox.information( + QtWidgets.QMessageBox.information( self, "Library added", '''Library details for this model is added to the ''' + '''eSim_Nghdl.lib in the KiCad shared directory''', - QtGui.QMessageBox.Ok + QtWidgets.QMessageBox.Ok ) diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index e873555..3a89ea1 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -1,25 +1,23 @@ #!/usr/bin/python3 - -# This file create the gui to install code model in the ngspice. +# This file create the GUI to install code model in the Ngspice. import os import sys import shutil import subprocess -from PyQt4 import QtGui -from PyQt4 import QtCore +from PyQt5 import QtGui, QtCore, QtWidgets from configparser import SafeConfigParser from Appconfig import Appconfig from createKicadLibrary import AutoSchematic from model_generation import ModelGeneration -class Mainwindow(QtGui.QWidget): +class Mainwindow(QtWidgets.QWidget): def __init__(self): # super(Mainwindow, self).__init__() - QtGui.QMainWindow.__init__(self) + QtWidgets.QMainWindow.__init__(self) print("Initializing..........") self.home = os.path.expanduser("~") @@ -41,20 +39,20 @@ class Mainwindow(QtGui.QWidget): self.initUI() def initUI(self): - self.uploadbtn = QtGui.QPushButton('Upload') + self.uploadbtn = QtWidgets.QPushButton('Upload') self.uploadbtn.clicked.connect(self.uploadModel) - self.exitbtn = QtGui.QPushButton('Exit') + self.exitbtn = QtWidgets.QPushButton('Exit') self.exitbtn.clicked.connect(self.closeWindow) - self.browsebtn = QtGui.QPushButton('Browse') + self.browsebtn = QtWidgets.QPushButton('Browse') self.browsebtn.clicked.connect(self.browseFile) - self.addbtn = QtGui.QPushButton('Add Files') + self.addbtn = QtWidgets.QPushButton('Add Files') self.addbtn.clicked.connect(self.addFiles) - self.removebtn = QtGui.QPushButton('Remove Files') + self.removebtn = QtWidgets.QPushButton('Remove Files') self.removebtn.clicked.connect(self.removeFiles) - self.ledit = QtGui.QLineEdit(self) - self.sedit = QtGui.QTextEdit(self) + self.ledit = QtWidgets.QLineEdit(self) + self.sedit = QtWidgets.QTextEdit(self) self.process = QtCore.QProcess(self) - self.termedit = QtGui.QTextEdit(self) + self.termedit = QtWidgets.QTextEdit(self) self.termedit.setReadOnly(1) pal = QtGui.QPalette() bgc = QtGui.QColor(0, 0, 0) @@ -63,7 +61,7 @@ class Mainwindow(QtGui.QWidget): self.termedit.setStyleSheet("QTextEdit {color:white}") # Creating gridlayout - grid = QtGui.QGridLayout() + grid = QtWidgets.QGridLayout() grid.setSpacing(5) grid.addWidget(self.ledit, 1, 0) grid.addWidget(self.browsebtn, 1, 1) @@ -90,15 +88,15 @@ class Mainwindow(QtGui.QWidget): def browseFile(self): print("Browse button clicked") - self.filename = QtGui.QFileDialog.getOpenFileName( - self, 'Open File', '.') + self.filename = QtWidgets.QFileDialog.getOpenFileName( + self, 'Open File', '.')[0] self.ledit.setText(self.filename) print("Vhdl file uploaded to process :", self.filename) def addFiles(self): print("Starts adding supporting files") title = self.addbtn.text() - for file in QtGui.QFileDialog.getOpenFileNames(self, title): + for file in QtWidgets.QFileDialog.getOpenFileNames(self, title)[0]: self.sedit.append(str(file)) self.file_list.append(file) print("Supporting Files are :", self.file_list) @@ -116,7 +114,7 @@ class Mainwindow(QtGui.QWidget): self.file_list.remove(file) if nonvhdl_count > 0: - QtGui.QMessageBox.critical( + QtWidgets.QMessageBox.critical( self, 'Critical', '''Important Message.

Supporting files should be .vhdl file ''' ) @@ -131,14 +129,14 @@ class Mainwindow(QtGui.QWidget): # Looking if model directory is present or not if os.path.isdir(self.modelname): print("Model Already present") - ret = QtGui.QMessageBox.warning( + ret = QtWidgets.QMessageBox.warning( self, "Warning", "This model already exist. Do you want to " + "overwrite it?
If yes press ok, else cancel it and " + "change the name of your vhdl file.", - QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel + QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel ) - if ret == QtGui.QMessageBox.Ok: + if ret == QtWidgets.QMessageBox.Ok: print("Overwriting existing model " + self.modelname) if os.name == 'nt': cmd = "rmdir " + self.modelname + "/s /q" @@ -295,10 +293,7 @@ class Mainwindow(QtGui.QWidget): self.process = QtCore.QProcess(self) self.process.start(cmd) self.process.finished.connect(self.createSchematicLib) - QtCore.QObject.connect( - self.process, QtCore.SIGNAL("readyReadStandardOutput()"), - self, QtCore.SLOT("readAllStandard()") - ) + self.process.readyReadStandardOutput.connect(self.readAllStandard) os.chdir(self.cur_dir) except BaseException: @@ -312,13 +307,13 @@ class Mainwindow(QtGui.QWidget): schematicLib = AutoSchematic(self.modelname) schematicLib.createKicadLibrary() else: - QtGui.QMessageBox.critical( + QtWidgets.QMessageBox.critical( self, 'Error', '''Cannot create Schematic Library of ''' + '''your model. Resolve the errors shown on ''' + '''console of NGHDL window. ''' ) else: - QtGui.QMessageBox.information( + QtWidgets.QMessageBox.information( self, 'Message', '''Important Message

''' + '''To create Schematic Library of your model, ''' + '''use NGHDL through eSim ''' @@ -344,15 +339,15 @@ class Mainwindow(QtGui.QWidget): self.runMake() self.runMakeInstall() else: - QtGui.QMessageBox.information( + QtWidgets.QMessageBox.information( self, 'Message', '''Important Message.
''' + '''
This accepts only .vhdl file ''' ) except Exception as e: - QtGui.QMessageBox.critical(self, 'Error', str(e)) + QtWidgets.QMessageBox.critical(self, 'Error', str(e)) -class FileRemover(QtGui.QWidget): +class FileRemover(QtWidgets.QWidget): def __init__(self, main_obj): super(FileRemover, self).__init__() @@ -365,8 +360,8 @@ class FileRemover(QtGui.QWidget): print(self.files) - self.grid = QtGui.QGridLayout() - removebtn = QtGui.QPushButton('Remove', self) + self.grid = QtWidgets.QGridLayout() + removebtn = QtWidgets.QPushButton('Remove', self) removebtn.clicked.connect(self.removeFiles) self.grid.addWidget(self.createCheckBox(), 0, 0) @@ -376,15 +371,15 @@ class FileRemover(QtGui.QWidget): self.show() def createCheckBox(self): - self.checkbox = QtGui.QGroupBox() + self.checkbox = QtWidgets.QGroupBox() self.checkbox.setTitle('Remove Files') - self.checkgrid = QtGui.QGridLayout() + self.checkgrid = QtWidgets.QGridLayout() - self.checkgroupbtn = QtGui.QButtonGroup() + self.checkgroupbtn = QtWidgets.QButtonGroup() for path in self.files: print(path) - self.cb_dict[path] = QtGui.QCheckBox(path) + self.cb_dict[path] = QtWidgets.QCheckBox(path) self.checkgroupbtn.addButton(self.cb_dict[path]) self.checkgrid.addWidget(self.cb_dict[path], self.row, self.col) self.row += 1 @@ -420,7 +415,7 @@ class FileRemover(QtGui.QWidget): def main(): - app = QtGui.QApplication(sys.argv) + app = QtWidgets.QApplication(sys.argv) if len(sys.argv) > 1: if sys.argv[1] == '-e': Appconfig.esimFlag = 1 -- cgit From 570bc95f225ac80c81405a40a29ef90ca5442fc5 Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Thu, 6 Aug 2020 00:36:46 +0530 Subject: replaced deprecated SafeConfigParser with ConfigParser --- src/ngspice_ghdl.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 3a89ea1..9ae499d 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -7,7 +7,7 @@ import sys import shutil import subprocess from PyQt5 import QtGui, QtCore, QtWidgets -from configparser import SafeConfigParser +from configparser import ConfigParser from Appconfig import Appconfig from createKicadLibrary import AutoSchematic from model_generation import ModelGeneration @@ -22,7 +22,7 @@ class Mainwindow(QtWidgets.QWidget): self.home = os.path.expanduser("~") # Reading all variables from config.ini - self.parser = SafeConfigParser() + self.parser = ConfigParser() self.parser.read( os.path.join(self.home, os.path.join('.nghdl', 'config.ini')) ) -- cgit From 906e279f2245613a699fb9cb174c28f42adf6f4b Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Thu, 6 Aug 2020 00:38:29 +0530 Subject: resolved issue with byte array object --- src/ngspice_ghdl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 9ae499d..56dd79a 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -248,7 +248,7 @@ class Mainwindow(QtWidgets.QWidget): str(self.process.readAllStandardOutput().data(), encoding='utf-8') ) stderror = self.process.readAllStandardError() - if stderror.toUpper().contains("ERROR"): + if stderror.toUpper().contains(b"ERROR"): self.errorFlag = True self.termedit.append(str(stderror.data(), encoding='utf-8')) -- cgit From d979750ea831bae780da20fefd92a93b026702c2 Mon Sep 17 00:00:00 2001 From: rahulp13 Date: Thu, 6 Aug 2020 00:41:48 +0530 Subject: added NGHDL main window as parent to the message windows --- src/createKicadLibrary.py | 9 +++++---- src/ngspice_ghdl.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/createKicadLibrary.py b/src/createKicadLibrary.py index 65d9a9f..e98d0d0 100644 --- a/src/createKicadLibrary.py +++ b/src/createKicadLibrary.py @@ -7,8 +7,9 @@ from PyQt5 import QtWidgets class AutoSchematic(QtWidgets.QWidget): - def __init__(self, modelname): + def __init__(self, parent, modelname): QtWidgets.QWidget.__init__(self) + self.parent = parent self.modelname = modelname.split('.')[0] self.template = Appconfig.kicad_lib_template.copy() self.xml_loc = Appconfig.xml_loc @@ -35,7 +36,7 @@ class AutoSchematic(QtWidgets.QWidget): elif (xmlFound == os.path.join(self.xml_loc, 'Nghdl')): print('Library already exists...') ret = QtWidgets.QMessageBox.warning( - self, "Warning", '''Library files for this model ''' + + self.parent, "Warning", '''Library files for this model ''' + '''already exist. Do you want to overwrite it?
If yes press ok, else cancel it and ''' + '''change the name of your vhdl file.''', @@ -53,7 +54,7 @@ class AutoSchematic(QtWidgets.QWidget): else: print('Pre existing library...') ret = QtWidgets.QMessageBox.critical( - self, "Error", '''A standard library already exists ''' + + self.parent, "Error", '''A standard library already exists ''' + '''with this name.
Please change the name ''' + '''of your vhdl file and upload it again''', QtWidgets.QMessageBox.Ok @@ -231,7 +232,7 @@ class AutoSchematic(QtWidgets.QWidget): os.chdir(cwd) print('Leaving directory, ', self.lib_loc) QtWidgets.QMessageBox.information( - self, "Library added", + self.parent, "Library added", '''Library details for this model is added to the ''' + '''eSim_Nghdl.lib in the KiCad shared directory''', QtWidgets.QMessageBox.Ok diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 56dd79a..fd17d7f 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -304,7 +304,7 @@ class Mainwindow(QtWidgets.QWidget): if Appconfig.esimFlag == 1: if not self.errorFlag: print('Creating library files................................') - schematicLib = AutoSchematic(self.modelname) + schematicLib = AutoSchematic(self, self.modelname) schematicLib.createKicadLibrary() else: QtWidgets.QMessageBox.critical( -- cgit From 71b98af4fc5b80dc5fd4cb0d23a213d302beac14 Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 6 Aug 2020 14:52:36 +0530 Subject: Update outitf.c --- src/outitf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/outitf.c b/src/outitf.c index fe60f7a..7cd0ddb 100644 --- a/src/outitf.c +++ b/src/outitf.c @@ -48,7 +48,7 @@ Modified: 2000 AlansFixes, 2013/2015 patch by Krzysztof Blaszkowski #include "plotting/graf.h" #include "../misc/misc_time.h" -/* 10.Mar.2917 - RM - Added the following #include */ +/* 10.Mar.2017 - RM - Added the following #include */ #include #include #include -- cgit From 2f27118577905998abe6e2d7d855464140538e0d Mon Sep 17 00:00:00 2001 From: Bladen Martin Date: Thu, 6 Aug 2020 19:24:05 +0530 Subject: Delete start_server.sh --- src/ghdlserver/start_server.sh | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100755 src/ghdlserver/start_server.sh (limited to 'src') diff --git a/src/ghdlserver/start_server.sh b/src/ghdlserver/start_server.sh deleted file mode 100755 index 548d7d7..0000000 --- a/src/ghdlserver/start_server.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -gcc -c ghdlserver.c -ghdl -a Utility_Package.vhdl && -ghdl -a Vhpi_Package.vhdl && -ghdl -a inverter.vhdl && -ghdl -a inverter_tb.vhdl && - -ghdl -e -Wl,ghdlserver.o inverter_tb && -./inverter_tb - -- cgit