float* ENR_newOutValueArray(ENResultsAPI* enrapi, ENR_ApiFunction func, ENR_ElementType type, int* length, int* errcode) // // Purpose: Allocates memory for outValue Array. // // Warning: Caller must free memory allocated by this function using ENR_free(). // { int size; float* array; if (enrapi->isOpened) { switch (func) { case ENR_getAttribute: if (type == ENR_node) size = enrapi->nodeCount; else size = enrapi->linkCount; break; case ENR_getResult: if (type == ENR_node) size = NNODERESULTS; else size = NLINKRESULTS; break; default: *errcode = 421; return NULL; } // Allocate memory for outValues array = (float*) calloc(size, sizeof(float)); *errcode = (MEMCHECK(array)); *length = size; return array; } *errcode = 412; return NULL; }
int unlinked() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code if any unlinked junctions found ** Purpose: checks for unlinked junctions in network ** ** NOTE: unlinked tanks have no effect on computations. **-------------------------------------------------------------- */ { char *marked; int i,err, errcode; errcode = 0; err = 0; marked = (char *) calloc(Nnodes+1,sizeof(char)); ERRCODE(MEMCHECK(marked)); if (!errcode) { memset(marked,0,(Nnodes+1)*sizeof(char)); for (i=1; i<=Nlinks; i++) /* Mark end nodes of each link */ { marked[Link[i].N1]++; marked[Link[i].N2]++; } for (i=1; i<=Njuncs; i++) /* Check each junction */ { if (marked[i] == 0) /* If not marked then error */ { err++; sprintf(Msg,ERR233,Node[i].ID); writeline(Msg); } if (err >= MAXERRS) break; } if (err > 0) errcode = 200; } free(marked); return(errcode); } /* End of unlinked */
static int readpacket(OCstate* state, OCURI* url,OCbytes* packet,OCdxd dxd,long* lastmodified) { int stat = OC_NOERR; int fileprotocol = 0; const char* suffix = ocdxdextension(dxd); char* fetchurl = NULL; CURL* curl = state->curl; fileprotocol = (strcmp(url->protocol,"file")==0); if(fileprotocol && !state->curlflags.proto_file) { /* Short circuit file://... urls*/ /* We do this because the test code always needs to read files*/ fetchurl = ocuribuild(url,NULL,NULL,0); stat = readfile(fetchurl,suffix,packet); } else { int flags = 0; if(!fileprotocol) { flags |= OCURICONSTRAINTS; flags |= OCURIUSERPWD; } flags |= OCURIENCODE; fetchurl = ocuribuild(url,NULL,suffix,flags); MEMCHECK(fetchurl,OC_ENOMEM); if(ocdebug > 0) {fprintf(stderr,"fetch url=%s\n",fetchurl); fflush(stderr);} stat = ocfetchurl(curl,fetchurl,packet,lastmodified); if(stat) oc_curl_printerror(state); if(ocdebug > 0) {fprintf(stderr,"fetch complete\n"); fflush(stderr);} } free(fetchurl); #ifdef OCDEBUG fprintf(stderr,"readpacket: packet.size=%lu\n", (unsigned long)ocbyteslength(packet)); #endif return OCTHROW(stat); }
double* SMO_newOutTimeList(SMOutputAPI* smoapi, int* errcode) // // Purpose: Allocates memory for TimeList. // // Warning: Caller must free memory allocated by this function using SMO_free_double(). // { int size; double* array; if (smoapi->isOpened) { size = smoapi->Nperiods; array = (double*)calloc(size, sizeof(double)); *errcode = (MEMCHECK(array)); return array; } *errcode = 412; return NULL; }
/* Build an NCattribute */ static NCerror buildattribute(char* name, nc_type ptype, size_t nvalues, char** values, NCattribute** attp) { int i; NCerror ncstat = NC_NOERR; NCattribute* att = NULL; att = (NCattribute*)calloc(1,sizeof(NCattribute)); MEMCHECK(att,NC_ENOMEM); att->name = nulldup(name); att->etype = ptype; att->values = nclistnew(); for(i=0;i<nvalues;i++) nclistpush(att->values,(void*)nulldup(values[i])); if(attp) *attp = att; else free(att); return THROW(ncstat); }
int readDATADDS(OCstate* state, OCtree* tree) { int stat; long lastmod = -1; #ifndef OC_DISK_STORAGE dapurlsetconstraints(&state->url,tree->constraint); stat = readpacket(state->curl,&state->url,state->packet,OCDATADDS,&lastmod); if(stat == OC_NOERR) state->datalastmodified = lastmod; tree->data.datasize = ocbyteslength(state->packet); #else /*OC_DISK_STORAGE*/ DAPURL* url = &state->url; int fileprotocol = 0; fileprotocol = (strncmp(url->base,"file:",5)==0); if(fileprotocol && !oc_curl_file_supported) { stat = readfiletofile(url->base, ".dods", tree->data.file, &tree->data.datasize); } else { char* fetchurl; dapurlsetconstraints(url,tree->constraint); fetchurl = dapurlgeturl(url,NULL,".dods",!fileprotocol); MEMCHECK(fetchurl,OC_ENOMEM); if (ocdebug > 0) {fprintf(stderr, "fetch url=%s\n", fetchurl);fflush(stderr);} stat = ocfetchurl_file(state->curl, fetchurl, tree->data.file, &tree->data.datasize, &lastmod); if(stat == OC_NOERR) state->datalastmodified = lastmod; if (ocdebug > 0) {fprintf(stderr,"fetch complete\n"); fflush(stderr);} free(fetchurl); } #endif /*OC_DISK_STORAGE*/ return THROW(stat); }
/* Convert path to a string; leave off the dataset name*/ static char* pathtostring(OClist* path, char* separator, int usecdfname) { int slen,i,len; char* pathname; if(path == NULL || (len = oclistlength(path))==0) return NULL; for(slen=0,i=0;i<len;i++) { OCnode* node = (OCnode*)oclistget(path,i); if(node->container == NULL || node->name == NULL) continue; slen += strlen(node->name); } slen += ((len-1)*strlen(separator)); slen += 1; /* for null terminator*/ pathname = (char*)ocmalloc(slen); MEMCHECK(pathname,NULL); pathname[0] = '\0'; for(i=0;i<len;i++) { OCnode* node = (OCnode*)oclistget(path,i); if(node->container == NULL || node->name == NULL) continue; if(strlen(pathname) > 0) strcat(pathname,separator); strcat(pathname,node->name); } return pathname; }
int openqual() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: opens WQ solver system **-------------------------------------------------------------- */ { int errcode = 0; int n; /* Allocate memory pool for WQ segments */ OutOfMemory = FALSE; if (AllocInit() == NULL) errcode = 101; /* Allocate scratch array & reaction rate array*/ X = (float *) calloc(MAX((Nnodes+1),(Nlinks+1)),sizeof(float)); R = (float *) calloc((Nlinks+1), sizeof(float)); ERRCODE(MEMCHECK(X)); ERRCODE(MEMCHECK(R)); /* Allocate memory for WQ solver */ n = Nlinks+Ntanks+1; FirstSeg = (Pseg *) calloc(n, sizeof(Pseg)); LastSeg = (Pseg *) calloc(n, sizeof(Pseg)); FlowDir = (char *) calloc(n, sizeof(char)); n = Nnodes+1; VolIn = (float *) calloc(n, sizeof(float)); MassIn = (float *) calloc(n, sizeof(float)); ERRCODE(MEMCHECK(FirstSeg)); ERRCODE(MEMCHECK(LastSeg)); ERRCODE(MEMCHECK(FlowDir)); ERRCODE(MEMCHECK(VolIn)); ERRCODE(MEMCHECK(MassIn)); return(errcode); }
void solve (Matrix& A, const Vector& b, Vector& x) const // Solve Ax=b { // declare variable (T=double, size_type=unsigned int) CS::cxsparse_type_traits<double, size_t>::lu_type cs_lu; // decompose cs_lu = CS::cs_ul_decompose (A, 1.0); // check MEMCHECK (cs_lu.first); MEMCHECK (cs_lu.first->q); MEMCHECK (cs_lu.second) MEMCHECK (cs_lu.second->U); MEMCHECK (cs_lu.second->L); MEMCHECK (cs_lu.second->pinv); // solve x = b; CS::cs_ul_solve (cs_lu, x); // free CS::cs_lu_free (cs_lu); }
OCerror ocfetch(OCstate* state, const char* constraint, OCdxd kind, OCnode** rootp) { OCtree* tree = NULL; OCnode* root = NULL; OCerror stat = OC_NOERR; tree = (OCtree*)ocmalloc(sizeof(OCtree)); MEMCHECK(tree,OC_ENOMEM); memset((void*)tree,0,sizeof(OCtree)); tree->dxdclass = kind; tree->state = state; tree->constraint = constraintescape(constraint); if(tree->constraint == NULL) tree->constraint = nulldup(constraint); ocbytesclear(state->packet); switch (kind) { case OCDAS: stat = readDAS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDAS; } break; case OCDDS: stat = readDDS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDDS; } break; case OCDATADDS: #ifdef OC_DISK_STORAGE /* Create the datadds file immediately so that DRNO can reference it*/ /* Make the tmp file*/ stat = createtempfile(state,tree); if(stat) {THROWCHK(stat); goto unwind;} stat = readDATADDS(state,tree); if(stat == OC_NOERR) { /* Separate the DDS from data and return the dds; will modify packet */ stat = ocextractdds(state,tree); } #else stat = readDATADDS(state,tree); if(stat == OC_NOERR) { /* Separate the DDS from data*/ stat = ocextractdds(state,tree); tree->data.xdrdata = ocbytesdup(state->packet); } #endif break; } if(stat != OC_NOERR) { /* Obtain any http code */ state->error.httpcode = ocfetchhttpcode(state->curl); if(state->error.httpcode >= 400) { oc_log(LOGWARN,"oc_open: Could not read url; http error = %l",state->error.httpcode); } else { oc_log(LOGWARN,"oc_open: Could not read url"); } return THROW(stat); } tree->nodes = NULL; stat = DAPparse(state,tree,tree->text); /* Check and report on an error return from the server */ if(stat == OC_EDAPSVC && state->error.code != NULL) { oc_log(LOGERR,"oc_open: server error retrieving url: code=%s message=\"%s\"", state->error.code, (state->error.message?state->error.message:"")); } if(stat) {THROWCHK(stat); goto unwind;} root = tree->root; /* make sure */ tree->root = root; root->tree = tree; /* Verify the parse */ switch (kind) { case OCDAS: if(root->octype != OC_Attributeset) {THROWCHK(stat=OC_EDAS); goto unwind;} break; case OCDDS: if(root->octype != OC_Dataset) {THROWCHK(stat=OC_EDDS); goto unwind;} break; case OCDATADDS: if(root->octype != OC_Dataset) {THROWCHK(stat=OC_EDATADDS); goto unwind;} /* Modify the tree kind */ tree->dxdclass = OCDATADDS; break; default: return OC_EINVAL; } if(kind != OCDAS) { /* Process ocnodes to fix various semantic issues*/ computeocsemantics(tree->nodes); } /* Process ocnodes to compute name info*/ computeocfullnames(tree->root); if(kind != OCDAS) { /* Process ocnodes to compute sizes when uniform in size*/ ocsetsize(tree->root); } if(kind == OCDATADDS) { tree->data.xdrs = (XDR*)ocmalloc(sizeof(XDR)); MEMCHECK(tree->data.xdrs,OC_ENOMEM); #ifdef OC_DISK_STORAGE ocxdrstdio_create(tree->data.xdrs,tree->data.file,XDR_DECODE); #else xdrmem_create(tree->data.xdrs,tree->data.xdrdata,tree->data.datasize,XDR_DECODE); #endif if(!xdr_setpos(tree->data.xdrs,tree->data.bod)) return xdrerror(); } #ifdef OC_DISK_STORAGE if(ocdebug == 0 && tree->data.filename != NULL) { unlink(tree->data.filename); } #endif /* Put root into the state->trees list */ oclistpush(state->trees,(ocelem)root); if(rootp) *rootp = root; return stat; unwind: ocfreetree(tree); return THROW(stat); }
static int occompile1(OCstate* state, OCnode* xnode, OCmemdata** memdatap, XDR* xdrs) { unsigned int i,j,xdrcount; int stat = OC_NOERR; size_t nelements; OCmemdata* memdata = NULL; OCmemdata* structdata = NULL; OClist* records = NULL; OCerror ocstat = OC_NOERR; OCmemdata** pmem = NULL; /* Allocate the space for this memdata chunk */ switch (xnode->octype) { case OC_Dataset: case OC_Grid: case OC_Structure: { if(xnode->array.rank == 0) { ocstat = occompilefields(state,xnode,&memdata,xdrs); if(ocstat != OC_NOERR) goto fail; } else { /* rank > 0 */ /* Compute the actual index count after projections */ nelements = totaldimsize(xnode); if(nelements == 0) return THROW(OC_ENODATA); memdata = makememdata(xnode->octype,OC_NAT,nelements); MEMCHECK(memdata,OC_ENOMEM); memdata->mode = Dimmode; pmem = (OCmemdata**)&memdata->data; /* Consume the leading count field */ if(!xdr_u_int(xdrs,&xdrcount)) {stat = OC_EXDR; goto fail;} /* validate the datadds dimensions */ if(xdrcount != nelements) {stat=OC_EINVALCOORDS; goto fail;} for(i=0;i<nelements;i++) { ocstat = occompilefields(state,xnode,&structdata,xdrs); if(ocstat != OC_NOERR) { if(ocstat != OC_ENODATA) goto fail; structdata = NULL; /* Leave a hole for this element */ } pmem[i] = structdata; structdata = NULL; } } } break; case OC_Sequence:{ /* Since we do not know the # records beforehand, use a oclist to collect the record instances. Query: this stores by recor (where e.g. original ocapi stores by column). How hard would it be to make the storage choice conditional on some user defined flag? */ records = oclistnew(); for(;;) { /* pick up the sequence record begin marker*/ char tmp[sizeof(unsigned int)]; /* extract the tag byte*/ if(!xdr_opaque(xdrs,tmp,sizeof(tmp))) {stat = OC_EXDR; goto fail;} if(tmp[0] == StartOfoclist) { /* Walk each member field*/ ocstat = occompilefields(state,xnode,&structdata,xdrs); if(ocstat != OC_NOERR) goto fail; oclistpush(records,(ocelem)structdata); structdata = NULL; } else if(tmp[0] == EndOfoclist) { break; /* we are done with the this sequence instance*/ } else { oc_log(LOGERR,"missing/invalid begin/end record marker\n"); stat = OC_EINVALCOORDS; goto fail; } } /* Convert the list to a proper OCmemdata */ nelements = oclistlength(records); memdata = makememdata(xnode->octype,OC_NAT,nelements); MEMCHECK(memdata,OC_ENOMEM); memdata->mode = Recordmode; pmem = (OCmemdata**)&memdata->data; for(j=0;j<nelements;j++) { OCmemdata* record = (OCmemdata*)oclistget(records,j); pmem[j] = record; } oclistfree(records); records = NULL; } break; case OC_Primitive: ocstat = occompileprim(state,xnode,&memdata,xdrs); if(ocstat != OC_NOERR) goto fail; break; default: OCPANIC1("ocmap: encountered unexpected node type: %x",xnode->octype); break; } /*ok:*/ if(memdatap) *memdatap = memdata; return THROW(ocstat); fail: if(records != NULL) for(i=0;i<oclistlength(records);i++) freeocmemdata((OCmemdata*)oclistget(records,i)); freeocmemdata(memdata); freeocmemdata(structdata); return THROW(ocstat); }
static int occompileprim(OCstate* state, OCnode* xnode, OCmemdata** memdatap, XDR* xdrs) { unsigned int xdrcount,i; size_t nelements = 0; OCerror ocstat = OC_NOERR; OCmemdata* memdata = NULL; OCASSERT((xnode->octype == OC_Primitive)); /* Use the count from the datadds */ nelements = totaldimsize(xnode); if(xnode->array.rank > 0) { /* Get first copy of the dimension count */ if(!xdr_u_int(xdrs,&xdrcount)) {ocstat = OC_EXDR; goto fail;} if(xdrcount != nelements) {ocstat=OC_EINVALCOORDS; goto fail;} if(xnode->etype != OC_String && xnode->etype != OC_URL) { /* Get second copy of the dimension count */ if(!xdr_u_int(xdrs,&xdrcount)) {ocstat = OC_EXDR; goto fail;} if(xdrcount != nelements) {ocstat=OC_EINVALCOORDS; goto fail;} } } else { nelements = 1; xdrcount = 1; } memdata = makememdata(xnode->octype,xnode->etype,nelements); MEMCHECK(memdata,OC_ENOMEM); memdata->mode = (xnode->array.rank > 0?Dimmode:Datamode); switch (xnode->etype) { case OC_String: case OC_URL: {/* Get the array of strings and store pointers in buf */ char** dst = (char**)memdata->data.data; for(i=0;i<xdrcount;i++) { char* s = NULL; if(!xdr_string(xdrs,(void*)&s,OC_INT32_MAX)) {ocstat = OC_EXDR; goto fail;} dst[i] = s; } } break; case OC_Byte: case OC_UByte: case OC_Char: { if(xnode->array.rank == 0) { /* Single unpacked character/byte */ union {unsigned int i; char c[BYTES_PER_XDR_UNIT];} u; if(!xdr_opaque(xdrs,u.c,BYTES_PER_XDR_UNIT)) {ocstat = OC_EXDR; goto fail;} u.i = ocntoh(u.i); memdata->data.data[0] = (char)u.i; } else { /* Packed characters; count will have already been read */ char* dst = memdata->data.data; if(!xdr_opaque(xdrs,dst,xdrcount)) {ocstat = OC_EXDR; goto fail;} } } break; case OC_Int16: case OC_UInt16: { unsigned short* dst = (unsigned short*)memdata->data.data; unsigned int* src; size_t xdrsize = xdrcount*BYTES_PER_XDR_UNIT; src = (unsigned int*)ocmalloc(xdrsize); if(!xdr_opaque(xdrs,(char*)src,xdrsize)) {ocfree(src); ocstat = OC_EXDR; goto fail;} if(!oc_network_order) { for(i=0;i<xdrcount;i++) { /* Write in place */ unsigned int hostint = src[i]; swapinline(dst[i],hostint); } } ocfree(src); } break; case OC_Int32: case OC_UInt32: case OC_Float32: { unsigned int* dst = (unsigned int*)memdata->data.data; size_t xdrsize = xdrcount*BYTES_PER_XDR_UNIT; if(!xdr_opaque(xdrs,(char*)dst,xdrsize)) {ocstat = OC_EXDR; goto fail;} if(!oc_network_order) { for(i=0;i<xdrcount;i++) { unsigned int hostint = dst[i]; swapinline(dst[i],hostint); } } } break; case OC_Int64: case OC_UInt64: case OC_Float64: { unsigned int* dst = (unsigned int*)memdata->data.data; size_t xdrsize = 2*xdrcount*BYTES_PER_XDR_UNIT; if(!xdr_opaque(xdrs,(char*)dst,xdrsize)) {ocstat = OC_EXDR; goto fail;} if(!oc_network_order) { for(i=0;i<2*xdrcount;i++) { unsigned int hostint = dst[i]; swapinline(dst[i],hostint); } } if(oc_invert_xdr_double) { /* May need to invert each pair */ for(i=0;i<2*xdrcount;i+=2) { unsigned int tmp = dst[i]; dst[i] = dst[i+1]; dst[i+1] = tmp; } } } break; default: OCPANIC1("unexpected etype: %d",xnode->etype); } /* switch */ /*ok:*/ if(memdatap) *memdatap = memdata; return THROW(ocstat); fail: freeocmemdata(memdata); return THROW(ocstat); }
OCerror ocfetchf(OCstate* state, const char* constraint, OCdxd kind, OCflags flags, OCnode** rootp) { OCtree* tree = NULL; OCnode* root = NULL; OCerror stat = OC_NOERR; tree = (OCtree*)ocmalloc(sizeof(OCtree)); MEMCHECK(tree,OC_ENOMEM); memset((void*)tree,0,sizeof(OCtree)); tree->dxdclass = kind; tree->state = state; tree->constraint = constraintescape(constraint); if(tree->constraint == NULL) tree->constraint = nulldup(constraint); /* Set curl properties: pwd, flags, proxies, ssl */ if((stat=ocset_user_password(state))!= OC_NOERR) goto fail; if((stat=ocset_curl_flags(state)) != OC_NOERR) goto fail; if((stat=ocset_proxy(state)) != OC_NOERR) goto fail; if((stat=ocset_ssl(state)) != OC_NOERR) goto fail; ocbytesclear(state->packet); switch (kind) { case OCDAS: stat = readDAS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDAS; } break; case OCDDS: stat = readDDS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDDS; } break; case OCDATADDS: if((flags & OCINMEMORY) == 0) {/* store in file */ /* Create the datadds file immediately so that DRNO can reference it*/ /* Make the tmp file*/ stat = createtempfile(state,tree); if(stat) {OCTHROWCHK(stat); goto unwind;} stat = readDATADDS(state,tree,flags); if(stat == OC_NOERR) { /* Separate the DDS from data and return the dds; will modify packet */ stat = ocextractddsinfile(state,tree,flags); } } else { /*inmemory*/ stat = readDATADDS(state,tree,flags); if(stat == OC_NOERR) { /* Separate the DDS from data and return the dds; will modify packet */ stat = ocextractddsinmemory(state,tree,flags); } } break; }/*switch*/ if(stat != OC_NOERR) { /* Obtain any http code */ state->error.httpcode = ocfetchhttpcode(state->curl); if(state->error.httpcode >= 400) { oc_log(LOGWARN,"oc_open: Could not read url; http error = %l",state->error.httpcode); } else { oc_log(LOGWARN,"oc_open: Could not read url"); } return OCTHROW(stat); } tree->nodes = NULL; stat = DAPparse(state,tree,tree->text); /* Check and report on an error return from the server */ if(stat == OC_EDAPSVC && state->error.code != NULL) { oc_log(LOGERR,"oc_open: server error retrieving url: code=%s message=\"%s\"", state->error.code, (state->error.message?state->error.message:"")); } if(stat) {OCTHROWCHK(stat); goto unwind;} root = tree->root; /* make sure */ tree->root = root; root->tree = tree; /* Verify the parse */ switch (kind) { case OCDAS: if(root->octype != OC_Attributeset) {OCTHROWCHK(stat=OC_EDAS); goto unwind;} break; case OCDDS: if(root->octype != OC_Dataset) {OCTHROWCHK(stat=OC_EDDS); goto unwind;} break; case OCDATADDS: if(root->octype != OC_Dataset) {OCTHROWCHK(stat=OC_EDATADDS); goto unwind;} /* Modify the tree kind */ tree->dxdclass = OCDATADDS; break; default: return OC_EINVAL; } if(kind != OCDAS) { /* Process ocnodes to assign offsets and sizes where possible */ occomputeskipdata(state,root); /* Process ocnodes to mark those that are cacheable */ ocmarkcacheable(state,root); /* Process ocnodes to handle various semantic issues*/ occomputesemantics(tree->nodes); } /* Process ocnodes to compute name info*/ occomputefullnames(tree->root); if(kind == OCDATADDS) { if((flags & OCINMEMORY) == 0) { tree->data.xdrs = xxdr_filecreate(tree->data.file,tree->data.bod); } else { /* Switch to zero based memory */ tree->data.xdrs = xxdr_memcreate(tree->data.memory,tree->data.datasize,tree->data.bod); } MEMCHECK(tree->data.xdrs,OC_ENOMEM); } /* Put root into the state->trees list */ oclistpush(state->trees,(ocelem)root); if(rootp) *rootp = root; return stat; unwind: ocfreetree(tree); fail: return OCTHROW(stat); }
int writeresults() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: writes simulation results to report file **-------------------------------------------------------------- */ { Pfloat *x; /* Array of pointers to floats */ int j,m,n,np,nnv,nlv; int errcode = 0; /* **----------------------------------------------------------- ** NOTE: The OutFile contains results for 4 node variables ** (demand, head, pressure, & quality) and 8 link ** variables (flow, velocity, headloss, quality, ** status, setting, reaction rate & friction factor) ** at each reporting time. **----------------------------------------------------------- */ /* Return if no output file */ if (OutFile == NULL) return(106); /* Return if no nodes or links selected for reporting */ /* or if no node or link report variables enabled. */ if (!Nodeflag && !Linkflag) return(errcode); nnv = 0; for (j=ELEV; j<=QUALITY; j++) nnv += Field[j].Enabled; nlv = 0; for (j=LENGTH; j<=FRICTION; j++) nlv += Field[j].Enabled; if (nnv == 0 && nlv == 0) return(errcode); /* Allocate memory for output variables. */ /* m = larger of # node variables & # link variables */ /* n = larger of # nodes & # links */ m = MAX( (QUALITY-DEMAND+1), (FRICTION-FLOW+1) ); n = MAX( (Nnodes+1), (Nlinks+1)); x = (Pfloat *) calloc(m, sizeof(Pfloat)); ERRCODE( MEMCHECK(x) ); if (errcode) return(errcode); for (j=0; j<m; j++) { x[j] = (float *) calloc(n, sizeof(float)); ERRCODE( MEMCHECK(x[j]) ); } if (errcode) return(errcode); /* Re-position output file & initialize report time. */ fseek(OutFile,OutOffset2,SEEK_SET); Htime = Rstart; /* For each reporting time: */ for (np=1; np<=Nperiods; np++) { /* Read in node results & write node table. */ /* (Remember to offset x[j] by 1 because array is zero-based). */ for (j=DEMAND; j<=QUALITY; j++) fread((x[j-DEMAND])+1,sizeof(float),Nnodes,OutFile); if (nnv > 0 && Nodeflag > 0) writenodetable(x); /* Read in link results & write link table. */ for (j=FLOW; j<=FRICTION; j++) fread((x[j-FLOW])+1,sizeof(float),Nlinks,OutFile); if (nlv > 0 && Linkflag > 0) writelinktable(x); Htime += Rstep; } /* Free allocated memory */ for (j=0; j<m; j++) free(x[j]); free(x); return(errcode); } /* End of writereport */
int linsolve(int n, double *Aii, double *Aij, double *B) /* **-------------------------------------------------------------- ** Input: n = number of equations ** Aii = diagonal entries of solution matrix ** Aij = non-zero off-diagonal entries of matrix ** B = right hand side coeffs. ** Output: B = solution values ** returns 0 if solution found, or index of ** equation causing system to be ill-conditioned ** Purpose: solves sparse symmetric system of linear ** equations using Cholesky factorization ** ** NOTE: This procedure assumes that the solution matrix has ** been symbolically factorized with the positions of ** the lower triangular, off-diagonal, non-zero coeffs. ** stored in the following integer arrays: ** XLNZ (start position of each column in NZSUB) ** NZSUB (row index of each non-zero in each column) ** LNZ (position of each NZSUB entry in Aij array) ** ** This procedure has been adapted from subroutines GSFCT and ** GSSLV in the book "Computer Solution of Large Sparse ** Positive Definite Systems" by A. George and J. W-H Liu ** (Prentice-Hall, 1981). **-------------------------------------------------------------- */ { int *link, *first; int i, istop, istrt, isub, j, k, kfirst, newk; int errcode = 0; double bj, diagj, ljk; double *temp; temp = (double *) calloc(n+1, sizeof(double)); link = (int *) calloc(n+1,sizeof(int)); first = (int *) calloc(n+1,sizeof(int)); ERRCODE(MEMCHECK(temp)); ERRCODE(MEMCHECK(link)); ERRCODE(MEMCHECK(first)); if (errcode) { errcode = -errcode; goto ENDLINSOLVE; } memset(temp,0,(n+1)*sizeof(double)); memset(link,0,(n+1)*sizeof(int)); /* Begin numerical factorization of matrix A into L */ /* Compute column L(*,j) for j = 1,...n */ for (j=1; j<=n; j++) { /* For each column L(*,k) that affects L(*,j): */ diagj = 0.0; newk = link[j]; k = newk; while (k != 0) { /* Outer product modification of L(*,j) by */ /* L(*,k) starting at first[k] of L(*,k). */ newk = link[k]; kfirst = first[k]; ljk = Aij[LNZ[kfirst]]; diagj += ljk*ljk; istrt = kfirst + 1; istop = XLNZ[k+1] - 1; if (istop >= istrt) { /* Before modification, update vectors 'first' */ /* and 'link' for future modification steps. */ first[k] = istrt; isub = NZSUB[istrt]; link[k] = link[isub]; link[isub] = k; /* The actual mod is saved in vector 'temp'. */ for (i=istrt; i<=istop; i++) { isub = NZSUB[i]; temp[isub] += Aij[LNZ[i]]*ljk; } } k = newk; } /* Apply the modifications accumulated */ /* in 'temp' to column L(*,j). */ diagj = Aii[j] - diagj; if (diagj <= 0.0) /* Check for ill-conditioning */ { errcode = j; goto ENDLINSOLVE; } diagj = sqrt(diagj); Aii[j] = diagj; istrt = XLNZ[j]; istop = XLNZ[j+1] - 1; if (istop >= istrt) { first[j] = istrt; isub = NZSUB[istrt]; link[j] = link[isub]; link[isub] = j; for (i=istrt; i<=istop; i++) { isub = NZSUB[i]; bj = (Aij[LNZ[i]] - temp[isub])/diagj; Aij[LNZ[i]] = bj; temp[isub] = 0.0; } } } /* next j */ /* Foward substitution */ for (j=1; j<=n; j++) { bj = B[j]/Aii[j]; B[j] = bj; istrt = XLNZ[j]; istop = XLNZ[j+1] - 1; if (istop >= istrt) { for (i=istrt; i<=istop; i++) { isub = NZSUB[i]; B[isub] -= Aij[LNZ[i]]*bj; } } } /* Backward substitution */ for (j=n; j>=1; j--) { bj = B[j]; istrt = XLNZ[j]; istop = XLNZ[j+1] - 1; if (istop >= istrt) { for (i=istrt; i<=istop; i++) { isub = NZSUB[i]; bj -= Aij[LNZ[i]]*B[isub]; } } B[j] = bj/Aii[j]; } ENDLINSOLVE: free(temp); free(link); free(first); return(errcode); } /* End of linsolve */
/* Extract data from the xdr packet into a chunk of memory. Normally, it is assumed that we are (at least virtually) "at" a single instance in the xdr packet; which we read. Virtually because for packed data, we need to point to the beginning of the packed data and use the index to indicate which packed element to get. */ int ocxdrread(XDR* xdrs, char* memory, size_t memsize, int packed, OCtype octype, unsigned int start, size_t count) { int stat = OC_NOERR; unsigned int i; size_t elemsize = octypesize(octype); char* localmem = NULL; char* startmem = NULL; size_t totalsize; size_t xdrsize; unsigned int xdrckp = xdr_getpos(xdrs); /* validate memory space*/ totalsize = elemsize*count; if(memsize < totalsize) return THROW(OC_EINVAL); /* Handle packed data specially*/ /* WARNING: assumes that the initial count has been read*/ if(packed) { char tmp[LOCALMEMMAX]; unsigned int readsize = start+count; if(readsize <= LOCALMEMMAX) /* avoid malloc/free for common case*/ localmem = tmp; else { localmem = (char*)ocmalloc(readsize); MEMCHECK(localmem,OC_ENOMEM); } if(!xdr_opaque(xdrs,(char*)localmem,readsize)) return xdrerror(); memcpy((void*)memory,(void*)(localmem+start),count); if(readsize > LOCALMEMMAX) ocfree(localmem); if(!xdr_setpos(xdrs,xdrckp)) return xdrerror(); /* revert to beginning*/ return THROW(OC_NOERR); } /* Not packed: extract count items; use xdr_opaque to speed up*/ if(octype == OC_String || octype == OC_URL) { /* do nothing here; handle below*/ } else if(octype == OC_Float64 || octype == OC_UInt64 || octype == OC_Int64) { unsigned int* p; xdrsize = 2*(start+count)*BYTES_PER_XDR_UNIT; localmem = (char*)ocmalloc(xdrsize); startmem = localmem+(2*start*BYTES_PER_XDR_UNIT); MEMCHECK(localmem,OC_ENOMEM); if(!xdr_opaque(xdrs,(char*)localmem,xdrsize)) return xdrerror(); if(!oc_network_order) { for(p=(unsigned int*)startmem,i=0;i<2*count;i++,p++) { unsigned int swap = *p; swapinline(*p,swap); } } } else { unsigned int* p; xdrsize = (start+count)*BYTES_PER_XDR_UNIT; localmem = (char*)ocmalloc(xdrsize); MEMCHECK(localmem,OC_ENOMEM); startmem = localmem+(start*BYTES_PER_XDR_UNIT); if(!xdr_opaque(xdrs,(char*)localmem,xdrsize)) return xdrerror(); if(!oc_network_order) { for(p=(unsigned int*)startmem,i=0;i<count;i++,p++) { unsigned int swap = *p; swapinline(*p,swap); } } } switch (octype) { case OC_Char: case OC_Byte: case OC_UByte: { char* pmem = (char*)memory; unsigned int* p = (unsigned int*)startmem; for(i=0;i<count;i++) {*pmem++ = (char)(*p++);} } break; case OC_Int16: case OC_UInt16: { unsigned short* pmem = (unsigned short*)memory; unsigned int* p = (unsigned int*)startmem; for(i=0;i<count;i++) {*pmem++ = (unsigned short)(*p++);} } break; case OC_Int32: case OC_UInt32: { memcpy((void*)memory,(void*)startmem,count*sizeof(unsigned int)); } break; case OC_Float32: { memcpy((void*)memory,(void*)startmem,count*sizeof(float)); } break; case OC_Int64: case OC_UInt64: case OC_Float64: { unsigned int* p; unsigned int* pmem = (unsigned int*)memory; /* Sometimes need to invert order*/ for(p=(unsigned int*)startmem,i=0;i<count;i++) { if(oc_invert_xdr_double) { pmem[1] = (unsigned int)(*p++); pmem[0] = (unsigned int)(*p++); } else { pmem[0] = (unsigned int)(*p++); pmem[1] = (unsigned int)(*p++); } pmem += 2; } } break; case OC_String: case OC_URL: { char* s = NULL; char** pmem = (char**)memory; /* First skip to the starting string */ for(i=0;i<start;i++) { s = NULL; /* make xdr_string alloc the space */ if(!xdr_string(xdrs,&s,OC_INT32_MAX)) return xdrerror(); ocfree(s); } /* Read count strings */ for(i=0;i<count;i++) { s = NULL; /* make xdr_string alloc the space */ if(!xdr_string(xdrs,&s,OC_INT32_MAX)) return xdrerror(); pmem[i] = s; } } break; default: return THROW(OC_EINVAL); } ocfree(localmem); if(!xdr_setpos(xdrs,xdrckp)) return xdrerror(); /* revert to beginning*/ return THROW(stat); }
int savetimestat(REAL4 *x, char objtype) /* **-------------------------------------------------------------- ** Input: *x = buffer for node values ** objtype = NODEHDR (for nodes) or LINKHDR (for links) ** Output: returns error code ** Purpose: computes time series statistic for nodes or links ** and saves to normal output file. ** ** NOTE: This routine is dependent on how the output reporting ** variables were assigned to FieldType in TYPES.H. **-------------------------------------------------------------- */ { int n, n1, n2; int i, j, p, errcode = 0; long startbyte, skipbytes; float *stat1, *stat2, xx; /* Compute number of bytes in temp output file to skip over (skipbytes) when moving from one time period to the next for a particular variable. */ if (objtype == NODEHDR) { /* For nodes, we start at 0 and skip over node output for all node variables minus 1 plus link output for all link variables. */ startbyte = 0; skipbytes = (Nnodes*(QUALITY-DEMAND) + Nlinks*(FRICTION-FLOW+1))*sizeof(REAL4); n = Nnodes; n1 = DEMAND; n2 = QUALITY; } else { /* For links, we start at the end of all node variables and skip over node output for all node variables plus link output for all link variables minus 1. */ startbyte = Nnodes*(QUALITY-DEMAND+1)*sizeof(REAL4); skipbytes = (Nnodes*(QUALITY-DEMAND+1) + Nlinks*(FRICTION-FLOW))*sizeof(REAL4); n = Nlinks; n1 = FLOW; n2 = FRICTION; } stat1 = (float *) calloc(n+1, sizeof(float)); stat2 = (float *) calloc(n+1, sizeof(float)); ERRCODE(MEMCHECK(stat1)); ERRCODE(MEMCHECK(stat2)); /* Process each output reporting variable */ if (!errcode) { for (j=n1; j<=n2; j++) { /* Initialize stat arrays */ if (Tstatflag == AVG) memset(stat1, 0, (n+1)*sizeof(float)); else for (i=1; i<=n; i++) { stat1[i] = -MISSING; /* +1E10 */ stat2[i] = MISSING; /* -1E10 */ } /* Position temp output file at start of output */ fseek(TmpOutFile, startbyte + (j-n1)*n*sizeof(REAL4), SEEK_SET); /* Process each time period */ for (p=1; p<=Nperiods; p++) { /* Get output results for time period & update stats */ fread(x+1, sizeof(REAL4), n, TmpOutFile); for (i=1; i<=n; i++) { xx = x[i]; if (objtype == LINKHDR) { if (j == FLOW) xx = ABS(xx); if (j == STATUS) { if (xx >= OPEN) xx = 1.0; else xx = 0.0; } } if (Tstatflag == AVG) stat1[i] += xx; else { stat1[i] = MIN(stat1[i], xx); stat2[i] = MAX(stat2[i], xx); } } /* Advance file to next period */ if (p < Nperiods) fseek(TmpOutFile, skipbytes, SEEK_CUR); } /* Compute resultant stat & save to regular output file */ switch (Tstatflag) { case AVG: for (i=1; i<=n; i++) x[i] = stat1[i]/(float)Nperiods; break; case MIN: for (i=1; i<=n; i++) x[i] = stat1[i]; break; case MAX: for (i=1; i<=n; i++) x[i] = stat2[i]; break; case RANGE: for (i=1; i<=n; i++) x[i] = stat2[i] - stat1[i]; break; } if (objtype == LINKHDR && j == STATUS) { for (i=1; i<=n; i++) { if (x[i] < 0.5f) x[i] = CLOSED; else x[i] = OPEN; } } if (fwrite(x+1, sizeof(REAL4), n, OutFile) < (unsigned) n) errcode = 308; /* Update internal output variables where applicable */ if (objtype == NODEHDR) switch (j) { case DEMAND: for (i=1; i<=n; i++) NodeDemand[i] = x[i]/Ucf[DEMAND]; break; case HEAD: for (i=1; i<=n; i++) NodeHead[i] = x[i]/Ucf[HEAD]; break; case QUALITY: for (i=1; i<=n; i++) NodeQual[i] = x[i]/Ucf[QUALITY]; break; } else if (j == FLOW) for (i=1; i<=n; i++) Q[i] = x[i]/Ucf[FLOW]; } } /* Free allocated memory */ free(stat1); free(stat2); return(errcode); }
int savenetdata() /* **--------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: saves input data in original units to binary ** output file using fixed-sized (4-byte) records **--------------------------------------------------------------- */ { int i,nmax; INT4 *ibuf; REAL4 *x; int errcode = 0; /* Allocate buffer arrays */ nmax = MAX(Nnodes,Nlinks) + 1; nmax = MAX(nmax,15); ibuf = (INT4 *) calloc(nmax, sizeof(INT4)); x = (REAL4 *) calloc(nmax, sizeof(REAL4)); ERRCODE(MEMCHECK(ibuf)); ERRCODE(MEMCHECK(x)); if (!errcode) { /* Write integer variables to OutFile */ ibuf[0] = MAGICNUMBER; /*** CODEVERSION replaces VERSION ***/ //(2.00.11 - LR) ibuf[1] = CODEVERSION; //(2.00.11 - LR) ibuf[2] = Nnodes; ibuf[3] = Ntanks; ibuf[4] = Nlinks; ibuf[5] = Npumps; ibuf[6] = Nvalves; ibuf[7] = Qualflag; ibuf[8] = TraceNode; ibuf[9] = Flowflag; ibuf[10] = Pressflag; ibuf[11] = Tstatflag; ibuf[12] = Rstart; ibuf[13] = Rstep; ibuf[14] = Dur; fwrite(ibuf,sizeof(INT4),15,OutFile); /* Write string variables to OutFile */ fwrite(Title[0],sizeof(char),MAXMSG+1,OutFile); fwrite(Title[1],sizeof(char),MAXMSG+1,OutFile); fwrite(Title[2],sizeof(char),MAXMSG+1,OutFile); fwrite(InpFname,sizeof(char),MAXFNAME+1,OutFile); fwrite(Rpt2Fname,sizeof(char),MAXFNAME+1,OutFile); fwrite(ChemName,sizeof(char),MAXID+1,OutFile); fwrite(Field[QUALITY].Units,sizeof(char),MAXID+1,OutFile); /* Write node ID information to OutFile */ for (i=1; i<=Nnodes; i++) fwrite(Node[i].ID, MAXID+1, 1, OutFile); /* Write link information to OutFile */ /* (Note: first transfer values to buffer array,*/ /* then fwrite buffer array at offset of 1 ) */ for (i=1; i<=Nlinks; i++) fwrite(Link[i].ID, MAXID+1, 1, OutFile); for (i=1; i<=Nlinks; i++) ibuf[i] = Link[i].N1; fwrite(ibuf+1,sizeof(INT4),Nlinks,OutFile); for (i=1; i<=Nlinks; i++) ibuf[i] = Link[i].N2; fwrite(ibuf+1,sizeof(INT4),Nlinks,OutFile); for (i=1; i<=Nlinks; i++) ibuf[i] = Link[i].Type; fwrite(ibuf+1,sizeof(INT4),Nlinks,OutFile); /* Write tank information to OutFile.*/ for (i=1; i<=Ntanks; i++) ibuf[i] = Tank[i].Node; fwrite(ibuf+1,sizeof(INT4),Ntanks,OutFile); for (i=1; i<=Ntanks; i++) x[i] = (REAL4)Tank[i].A; FSAVE(Ntanks); /* Save node elevations to OutFile.*/ for (i=1; i<=Nnodes; i++) x[i] = (REAL4)(Node[i].El*Ucf[ELEV]); FSAVE(Nnodes); /* Save link lengths & diameters to OutFile.*/ for (i=1; i<=Nlinks; i++) x[i] = (REAL4)(Link[i].Len*Ucf[ELEV]); FSAVE(Nlinks); for (i=1; i<=Nlinks; i++) { if (Link[i].Type != PUMP) x[i] = (REAL4)(Link[i].Diam*Ucf[DIAM]); else x[i] = 0.0f; } if (FSAVE(Nlinks) < (unsigned)Nlinks) errcode = 308; } /* Free memory used for buffer arrays */ free(ibuf); free(x); return(errcode); }
int readdata() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: reads contents of input data file **-------------------------------------------------------------- */ { char line[MAXLINE+1], /* Line from input data file */ wline[MAXLINE+1]; /* Working copy of input line */ int sect,newsect, /* Data sections */ errcode = 0, /* Error code */ inperr,errsum; /* Error code & total error count */ /* Allocate input buffer */ X = (double *) calloc(MAXTOKS, sizeof(double)); ERRCODE(MEMCHECK(X)); if (!errcode) { /* Initialize number of network components */ Ntitle = 0; Nnodes = 0; Njuncs = 0; Ntanks = 0; Nlinks = 0; Npipes = 0; Npumps = 0; Nvalves = 0; Ncontrols = 0; Nrules = 0; Ncurves = MaxCurves; Npats = MaxPats; PrevPat = NULL; PrevCurve = NULL; sect = -1; errsum = 0; /* Read each line from input file. */ while (fgets(line,MAXLINE,InFile) != NULL) { /* Make copy of line and scan for tokens */ strcpy(wline,line); Ntokens = gettokens(wline); /* Skip blank lines and comments */ if (Ntokens == 0) continue; if (*Tok[0] == ';') continue; /* Check if max. length exceeded */ if (strlen(line) >= MAXLINE) { sprintf(Msg,ERR214); writeline(Msg); writeline(line); errsum++; } /* Check if at start of a new input section */ if (*Tok[0] == '[') { newsect = findmatch(Tok[0],SectTxt); if (newsect >= 0) { sect = newsect; if (sect == _END) break; continue; } else { inperrmsg(201,sect,line); errsum++; break; } } /* Otherwise process next line of input in current section */ else { inperr = newline(sect,line); if (inperr > 0) { inperrmsg(inperr,sect,line); errsum++; } } /* Stop if reach end of file or max. error count */ if (errsum == MAXERRS) break; } /* End of while */ /* Check for errors */ if (errsum > 0) errcode = 200; } /* Check for unlinked nodes */ if (!errcode) errcode = unlinked(); /* Get pattern & curve data from temp. lists */ if (!errcode) errcode = getpatterns(); if (!errcode) errcode = getcurves(); if (!errcode) errcode = getpumpparams(); /* Free input buffer */ free(X); return(errcode); } /* End of readdata */
OCerror ocfetch(OCstate* state, const char* constraint, OCdxd kind, OCflags flags, OCnode** rootp) { OCtree* tree = NULL; OCnode* root = NULL; OCerror stat = OC_NOERR; tree = (OCtree*)ocmalloc(sizeof(OCtree)); MEMCHECK(tree,OC_ENOMEM); memset((void*)tree,0,sizeof(OCtree)); tree->dxdclass = kind; tree->state = state; tree->constraint = constraintescape(constraint); if(tree->constraint == NULL) tree->constraint = nulldup(constraint); /* Set per-fetch curl properties */ #if 0 /* temporarily make per-link */ if((stat=ocset_flags_perfetch(state))!= OC_NOERR) goto fail; #endif ocbytesclear(state->packet); switch (kind) { case OCDAS: stat = readDAS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDAS; } break; case OCDDS: stat = readDDS(state,tree); if(stat == OC_NOERR) { tree->text = ocbytesdup(state->packet); if(tree->text == NULL) stat = OC_EDDS; } break; case OCDATADDS: if((flags & OCONDISK) != 0) {/* store in file */ /* Create the datadds file immediately so that DRNO can reference it*/ /* Make the tmp file*/ stat = createtempfile(state,tree); if(stat) {OCTHROWCHK(stat); goto fail;} stat = readDATADDS(state,tree,flags); if(stat == OC_NOERR) { /* Separate the DDS from data and return the dds; will modify packet */ stat = ocextractddsinfile(state,tree,flags); } } else { /*inmemory*/ stat = readDATADDS(state,tree,flags); if(stat == OC_NOERR) { /* Separate the DDS from data and return the dds; will modify packet */ stat = ocextractddsinmemory(state,tree,flags); } } break; default: break; }/*switch*/ /* Obtain any http code */ state->error.httpcode = ocfetchhttpcode(state->curl); if(stat != OC_NOERR) { if(state->error.httpcode >= 400) { oclog(OCLOGWARN,"oc_open: Could not read url; http error = %l",state->error.httpcode); } else { oclog(OCLOGWARN,"oc_open: Could not read url"); } goto fail; } tree->nodes = NULL; stat = DAPparse(state,tree,tree->text); /* Check and report on an error return from the server */ if(stat == OC_EDAPSVC && state->error.code != NULL) { oclog(OCLOGERR,"oc_open: server error retrieving url: code=%s message=\"%s\"", state->error.code, (state->error.message?state->error.message:"")); } if(stat) {OCTHROWCHK(stat); goto fail;} root = tree->root; /* make sure */ tree->root = root; root->tree = tree; /* Verify the parse */ switch (kind) { case OCDAS: if(root->octype != OC_Attributeset) {OCTHROWCHK(stat=OC_EDAS); goto fail;} break; case OCDDS: if(root->octype != OC_Dataset) {OCTHROWCHK(stat=OC_EDDS); goto fail;} break; case OCDATADDS: if(root->octype != OC_Dataset) {OCTHROWCHK(stat=OC_EDATADDS); goto fail;} /* Modify the tree kind */ tree->dxdclass = OCDATADDS; break; default: return OC_EINVAL; } if(kind != OCDAS) { /* Process ocnodes to mark those that are cacheable */ ocmarkcacheable(state,root); /* Process ocnodes to handle various semantic issues*/ occomputesemantics(tree->nodes); } /* Process ocnodes to compute name info*/ occomputefullnames(tree->root); if(kind == OCDATADDS) { if((flags & OCONDISK) != 0) { tree->data.xdrs = xxdr_filecreate(tree->data.file,tree->data.bod); } else { #ifdef OCDEBUG fprintf(stderr,"ocfetch.datadds.memory: datasize=%lu bod=%lu\n", (unsigned long)tree->data.datasize,(unsigned long)tree->data.bod); #endif /* Switch to zero based memory */ tree->data.xdrs = xxdr_memcreate(tree->data.memory,tree->data.datasize,tree->data.bod); } MEMCHECK(tree->data.xdrs,OC_ENOMEM); /* Do a quick check to see if server returned an ERROR {} at the beginning of the data */ if(dataError(tree->data.xdrs,state)) { stat = OC_EDATADDS; oclog(OCLOGERR,"oc_open: server error retrieving url: code=%s message=\"%s\"", state->error.code, (state->error.message?state->error.message:"")); goto fail; } /* Compile the data into a more accessible format */ stat = occompile(state,tree->root); if(stat != OC_NOERR) goto fail; } /* Put root into the state->trees list */ oclistpush(state->trees,(void*)root); if(rootp) *rootp = root; return stat; fail: if(root != NULL) ocroot_free(root); else if(tree != NULL) octree_free(tree); return OCTHROW(stat); }
int disconnected() /* **------------------------------------------------------------------- ** Input: None ** Output: Returns number of disconnected nodes ** Purpose: Tests current hydraulic solution to see if any closed ** links have caused the network to become disconnected. **------------------------------------------------------------------- */ { int i, j; int count, mcount; int errcode = 0; int *nodelist; char *marked; /* Allocate memory for node list & marked list */ nodelist = (int *) calloc(Nnodes+1,sizeof(int)); marked = (char *) calloc(Nnodes+1,sizeof(char)); ERRCODE(MEMCHECK(nodelist)); ERRCODE(MEMCHECK(marked)); if (errcode) return(0); /* Place tanks on node list and marked list */ for (i=1; i<=Ntanks; i++) { j = Njuncs + i; nodelist[i] = j; marked[j] = 1; } /* Place junctions with negative demands on the lists */ mcount = Ntanks; for (i=1; i<=Njuncs; i++) { if (D[i] < 0.0) { mcount++; nodelist[mcount] = i; marked[i] = 1; } } /* Mark all nodes that can be connected to tanks */ /* and count number of nodes remaining unmarked. */ marknodes(mcount,nodelist,marked); j = 0; count = 0; for (i=1; i<=Njuncs; i++) { if (!marked[i] && D[i] != 0.0) /* Skip if no demand */ { count++; if (count <= MAXCOUNT && Messageflag) { sprintf(Msg,WARN03a,Node[i].ID,clocktime(Atime,Htime)); writeline(Msg); } j = i; /* Last unmarked node */ } } /* Report number of unmarked nodes and find closed link */ /* on path from node j back to a tank. */ if (count > 0 && Messageflag) { if (count > MAXCOUNT) { sprintf(Msg, WARN03b, count-MAXCOUNT, clocktime(Atime,Htime)); writeline(Msg); } getclosedlink(j,marked); } /* Free allocated memory */ free(nodelist); free(marked); return(count); } /* End of disconnected() */
void smooth_gbdry_1(unsigned char *cube, int nx, int ny, int nz, int nxy, int nxyz, int sten_sz, unsigned char this_phase, unsigned char other_phase) { void (*check_bdry)(unsigned char *, int, int, int, int, int, int *), (*set_sten)(int, int, int *); unsigned char is_edge; char *msg; int *is_in, *sten, *cnvt_list; int ind, nind, i; int num_nbrs; int realloc_sz, cnvt_sz, cnvt_ind; int isz = sizeof(int); is_in = (int *)MALLOC(sten_sz*isz); sten = (int *)MALLOC(sten_sz*isz); if( sten_sz == 6 ) { set_sten = set_6_stencil; check_bdry = check_bdry_6_nbr; } else { set_sten = set_stencil; check_bdry = check_bdry_26_nbr; } (*set_sten)(nx,nxy,sten); cnvt_sz = realloc_sz = nx; cnvt_list = (int *)MALLOC(cnvt_sz*isz); msg = "cnvt_list in smooth_gbdry_1()"; if( MEMCHECK(cnvt_list,msg,cnvt_sz*isz) ) clean_up(0); cnvt_ind = 0; for( ind = 0; ind < nxyz; ind++ ) { if( cube[ind] != this_phase ) continue; (*check_bdry)(&is_edge,ind,nx,ny,nz,nxy,is_in); num_nbrs = 0; if( is_edge ) { for( i = 0; i < sten_sz; i++ ) { if( is_in[i] ) Check_nbr(this_phase) } } else { for( i = 0; i < sten_sz; i++ ) Check_nbr(this_phase) } if( num_nbrs == 1 ) { if( cnvt_ind == cnvt_sz ) { cnvt_sz += realloc_sz; cnvt_list = (int *)REALLOC(cnvt_list,cnvt_sz*isz); msg = "cnvt_list realloc in smooth_gbdry_1()"; if( MEMCHECK(cnvt_list,msg,realloc_sz*isz) ) clean_up(0); } cnvt_list[cnvt_ind] = ind; cnvt_ind++; } }
int dumpmetadata(int ncid, NChdr** hdrp) { int stat,i,j,k; NChdr* hdr = (NChdr*)calloc(1,sizeof(NChdr)); MEMCHECK(hdr,NC_ENOMEM); hdr->ncid = ncid; hdr->content = ncbytesnew(); if(hdrp) *hdrp = hdr; stat = nc_inq(hdr->ncid, &hdr->ndims, &hdr->nvars, &hdr->ngatts, &hdr->unlimid); CHECK(stat); if(ncdap3debug > 0) { fprintf(stdout,"ncid=%d ngatts=%d ndims=%d nvars=%d unlimid=%d\n", hdr->ncid,hdr->ngatts,hdr->ndims,hdr->nvars,hdr->unlimid); } hdr->gatts = (NCattribute*)calloc(1,hdr->ngatts*sizeof(NCattribute)); MEMCHECK(hdr->gatts,NC_ENOMEM); if(hdr->ngatts > 0) fprintf(stdout,"global attributes:\n"); for(i=0;i<hdr->ngatts;i++) { NCattribute* att = &hdr->gatts[i]; char attname[NC_MAX_NAME]; nc_type nctype; size_t typesize; size_t nvalues; stat = nc_inq_attname(hdr->ncid,NC_GLOBAL,i,attname); CHECK(stat); att->name = nulldup(attname); stat = nc_inq_att(hdr->ncid,NC_GLOBAL,att->name,&nctype,&nvalues); CHECK(stat); att->etype = nctypetodap(nctype); typesize = nctypesizeof(att->etype); fprintf(stdout,"\t[%d]: name=%s type=%s values(%lu)=", i,att->name,nctypetostring(octypetonc(att->etype)), (unsigned long)nvalues); if(nctype == NC_CHAR) { size_t len = typesize*nvalues; char* values = (char*)malloc(len+1);/* for null terminate*/ MEMCHECK(values,NC_ENOMEM); stat = nc_get_att(hdr->ncid,NC_GLOBAL,att->name,values); CHECK(stat); values[len] = '\0'; fprintf(stdout," '%s'",values); } else { size_t len = typesize*nvalues; char* values = (char*)malloc(len); MEMCHECK(values,NC_ENOMEM); stat = nc_get_att(hdr->ncid,NC_GLOBAL,att->name,values); CHECK(stat); for(k=0;k<nvalues;k++) { fprintf(stdout," "); dumpdata1(octypetonc(att->etype),k,values); } } fprintf(stdout,"\n"); } hdr->dims = (Dim*)malloc(hdr->ndims*sizeof(Dim)); MEMCHECK(hdr->dims,NC_ENOMEM); for(i=0;i<hdr->ndims;i++) { hdr->dims[i].dimid = i; stat = nc_inq_dim(hdr->ncid, hdr->dims[i].dimid, hdr->dims[i].name, &hdr->dims[i].size); CHECK(stat); fprintf(stdout,"dim[%d]: name=%s size=%lu\n", i,hdr->dims[i].name,(unsigned long)hdr->dims[i].size); } hdr->vars = (Var*)malloc(hdr->nvars*sizeof(Var)); MEMCHECK(hdr->vars,NC_ENOMEM); for(i=0;i<hdr->nvars;i++) { Var* var = &hdr->vars[i]; nc_type nctype; var->varid = i; stat = nc_inq_var(hdr->ncid, var->varid, var->name, &nctype, &var->ndims, var->dimids, &var->natts); CHECK(stat); var->nctype = (nctype); fprintf(stdout,"var[%d]: name=%s type=%s |dims|=%d", i, var->name, nctypetostring(var->nctype), var->ndims); fprintf(stdout," dims={"); for(j=0;j<var->ndims;j++) { fprintf(stdout," %d",var->dimids[j]); } fprintf(stdout,"}\n"); var->atts = (NCattribute*)malloc(var->natts*sizeof(NCattribute)); MEMCHECK(var->atts,NC_ENOMEM); for(j=0;j<var->natts;j++) { NCattribute* att = &var->atts[j]; char attname[NC_MAX_NAME]; size_t typesize; char* values; nc_type nctype; size_t nvalues; stat = nc_inq_attname(hdr->ncid,var->varid,j,attname); CHECK(stat); att->name = nulldup(attname); stat = nc_inq_att(hdr->ncid,var->varid,att->name,&nctype,&nvalues); CHECK(stat); att->etype = nctypetodap(nctype); typesize = nctypesizeof(att->etype); values = (char*)malloc(typesize*nvalues); MEMCHECK(values,NC_ENOMEM); stat = nc_get_att(hdr->ncid,var->varid,att->name,values); CHECK(stat); fprintf(stdout,"\tattr[%d]: name=%s type=%s values(%lu)=", j,att->name,nctypetostring(octypetonc(att->etype)),(unsigned long)nvalues); for(k=0;k<nvalues;k++) { fprintf(stdout," "); dumpdata1(octypetonc(att->etype),k,values); } fprintf(stdout,"\n"); } } fflush(stdout); return NC_NOERR; }
static int setauthfield(NCauth* auth, const char* flag, const char* value) { int ret = NC_NOERR; if(value == NULL) goto done; if(strcmp(flag,"HTTP.DEFLATE")==0) { if(atoi(value)) auth->curlflags.compress = 1; #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.DEFLATE: %ld", infoflags.compress); #endif } if(strcmp(flag,"HTTP.VERBOSE")==0) { if(atoi(value)) auth->curlflags.verbose = 1; #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.VERBOSE: %ld", auth->curlflags.verbose); #endif } if(strcmp(flag,"HTTP.TIMEOUT")==0) { if(atoi(value)) auth->curlflags.timeout = atoi(value); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.TIMEOUT: %ld", auth->curlflags.timeout); #endif } if(strcmp(flag,"HTTP.USERAGENT")==0) { if(atoi(value)) auth->curlflags.useragent = strdup(value); MEMCHECK(auth->curlflags.useragent); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.USERAGENT: %s", auth->curlflags.useragent); #endif } if( strcmp(flag,"HTTP.COOKIEFILE")==0 || strcmp(flag,"HTTP.COOKIE_FILE")==0 || strcmp(flag,"HTTP.COOKIEJAR")==0 || strcmp(flag,"HTTP.COOKIE_JAR")==0 ) { nullfree(auth->curlflags.cookiejar); auth->curlflags.cookiejar = strdup(value); MEMCHECK(auth->curlflags.cookiejar); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.COOKIEJAR: %s", auth->curlflags.cookiejar); #endif } if(strcmp(flag,"HTTP.PROXY.SERVER")==0 || strcmp(flag,"HTTP.PROXY_SERVER")==0) { ret = NC_parseproxy(auth,value); if(ret != NC_NOERR) goto done; #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.PROXY.SERVER: %s", value); #endif } if(strcmp(flag,"HTTP.SSL.VALIDATE")==0) { if(atoi(value)) { auth->ssl.verifypeer = 1; auth->ssl.verifyhost = 1; #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.VALIDATE: %ld", 1); #endif } } if(strcmp(flag,"HTTP.SSL.CERTIFICATE")==0) { nullfree(auth->ssl.certificate); auth->ssl.certificate = strdup(value); MEMCHECK(auth->ssl.certificate); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.CERTIFICATE: %s", auth->ssl.certificate); #endif } if(strcmp(flag,"HTTP.SSL.KEY")==0) { nullfree(auth->ssl.key); auth->ssl.key = strdup(value); MEMCHECK(auth->ssl.key); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.KEY: %s", auth->ssl.key); #endif } if(strcmp(flag,"HTTP.SSL.KEYPASSWORD")==0) { nullfree(auth->ssl.keypasswd) ; auth->ssl.keypasswd = strdup(value); MEMCHECK(auth->ssl.keypasswd); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.KEYPASSWORD: %s", auth->ssl.keypasswd); #endif } if(strcmp(flag,"HTTP.SSL.CAINFO")==0) { nullfree(auth->ssl.cainfo) ; auth->ssl.cainfo = strdup(value); MEMCHECK(auth->ssl.cainfo); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.CAINFO: %s", auth->ssl.cainfo); #endif } if(strcmp(flag,"HTTP.SSL.CAPATH")==0) { nullfree(auth->ssl.capath) ; auth->ssl.capath = strdup(value); MEMCHECK(auth->ssl.capath); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.CAPATH: %s", auth->ssl.capath); #endif } if(strcmp(flag,"HTTP.SSL.VERIFYPEER")==0) { const char* s = value; int tf = 0; if(s == NULL || strcmp(s,"0")==0 || strcasecmp(s,"false")==0) tf = 0; else if(strcmp(s,"1")==0 || strcasecmp(s,"true")==0) tf = 1; else tf = 1; /* default if not null */ auth->ssl.verifypeer = tf; #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.SSL.VERIFYPEER: %d", auth->ssl.verifypeer); #endif } if(strcmp(flag,"HTTP.NETRC")==0) { nullfree(auth->curlflags.netrc); auth->curlflags.netrc = strdup(value); MEMCHECK(auth->curlflags.netrc); #ifdef D4DEBUG nclog(NCLOGNOTE,"HTTP.NETRC: %s", auth->curlflags.netrc); #endif } if(strcmp(flag,"HTTP.CREDENTIALS.USERNAME")==0) { nullfree(auth->creds.user); auth->creds.user = strdup(value); MEMCHECK(auth->creds.user); } if(strcmp(flag,"HTTP.CREDENTIALS.PASSWORD")==0) { nullfree(auth->creds.pwd); auth->creds.pwd = strdup(value); MEMCHECK(auth->creds.pwd); } done: return (ret); nomem: return (NC_ENOMEM); }