高温氦气物性补全;三通四通能量计算bug修正
This commit is contained in:
1 parent
6fc9afe41d
commit
2b07d996cf
133 files changed
+5230
-253310
No files matched your search
+78
-21
@@ -30,21 +30,34 @@ double native_cpu_time(void) {
|
||||
#endif
|
||||
}
|
||||
|
||||
int native_fail(NativeRun *r,const char *reason,const char *operation,const char *message) {
|
||||
if (!r->status) {
|
||||
r->status=2; r->failure_reason=reason; r->failure_operation=operation;
|
||||
snprintf(r->message_buffer,sizeof(r->message_buffer),"%s",message);
|
||||
r->message=r->message_buffer;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int native_poll(NativeRun *r, double t) {
|
||||
double now=native_wall_time();
|
||||
if (r->status) return 0;
|
||||
if (r->options.timeout > 0 && now-r->wall_start > r->options.timeout) {
|
||||
r->status=2; r->message="Native solve exceeded its time limit."; return 0;
|
||||
}
|
||||
if (now-r->last_progress >= 0.1) {
|
||||
r->last_progress=now;
|
||||
if (r->options.cancel_path) {
|
||||
FILE *f=fopen(r->options.cancel_path,"rb");
|
||||
if (f) { fclose(f); r->status=1; r->message="Simulation cancelled."; return 0; }
|
||||
if (f) {
|
||||
fclose(f); r->status=1; r->message="Simulation cancelled.";
|
||||
r->failure_reason="cancelled"; r->failure_operation="cancel-check"; return 0;
|
||||
}
|
||||
}
|
||||
fprintf(stderr,"{\"phase\":\"integrating\",\"time\":%.17g,\"nfev\":%lu,\"acceptedSteps\":%lu}\n",t,r->nfev,r->accepted);
|
||||
fflush(stderr);
|
||||
}
|
||||
if (r->options.timeout > 0 && now-r->wall_start > r->options.timeout)
|
||||
return native_fail(r,r->stagnating?"time-stagnation":"timeout","integration",
|
||||
r->stagnating?"Native solver kept returning without advancing time until the run time limit expired.":
|
||||
"Native solve exceeded its time limit.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -70,20 +83,55 @@ int native_jacobian_rhs(NativeRun *r, double t, const double *y, double *dy) {
|
||||
int native_append(NativeRun *r, double t, const double *y) {
|
||||
r->final_time=t; memcpy(r->final_state,y,NSTATES*sizeof(double));
|
||||
if (!r->options.record_samples) return 1;
|
||||
if (r->count && r->times[r->count-1] == t) r->count--;
|
||||
if (r->count == r->capacity) {
|
||||
size_t cap=r->capacity ? r->capacity*2 : 1024;
|
||||
if (cap > 2000000 || cap > 268435456u / NSTATES / sizeof(double)) return 0;
|
||||
double *times=realloc(r->times,cap*sizeof(double));
|
||||
if (!times) return 0;
|
||||
r->times=times;
|
||||
double *states=realloc(r->states,cap*NSTATES*sizeof(double));
|
||||
if (!states) return 0;
|
||||
r->states=states; r->capacity=cap;
|
||||
return native_samples_append(r,t,y);
|
||||
}
|
||||
|
||||
/* Amesim helium data domains: EOS, ideal Cp/h, viscosity. Warnings describe
|
||||
* the property use, not a component. Trial/Newton/Jacobian evaluations never
|
||||
* publish warnings; replay of output samples is also side-effect free. */
|
||||
static const double property_lower[3]={2.2,200,200};
|
||||
static const double property_upper[3]={1500,20000,15000};
|
||||
static const char *property_domain[3]={"equation-of-state","ideal-caloric","dynamic-viscosity"};
|
||||
static void property_warning_json(FILE *f,int slot,const NativePropertyWarning *w) {
|
||||
int domain=slot/2,upper=slot%2;
|
||||
fprintf(f,"{\"code\":\"helium-%s-%s\",\"medium\":\"helium\",\"property\":\"%s\","
|
||||
"\"direction\":\"%s\",\"limit\":%.17g,\"time\":%.17g,\"temperature\":%.17g,"
|
||||
"\"extremeTime\":%.17g,\"extremeTemperature\":%.17g}",
|
||||
property_domain[domain],upper?"high":"low",property_domain[domain],upper?"high":"low",
|
||||
upper?property_upper[domain]:property_lower[domain],w->first_time,w->first_temperature,
|
||||
w->extreme_time,w->extreme_temperature);
|
||||
}
|
||||
void native_property_warnings_json(NativeRun *r,FILE *f) {
|
||||
int comma=0;fputc('[',f);
|
||||
for(int i=0;i<6;i++)if(r->property_warnings[i].seen) {
|
||||
if(comma++)fputc(',',f);
|
||||
property_warning_json(f,i,&r->property_warnings[i]);
|
||||
}
|
||||
r->times[r->count]=t;
|
||||
memcpy(r->states+r->count*NSTATES,y,NSTATES*sizeof(double));
|
||||
r->count++; return 1;
|
||||
fputc(']',f);
|
||||
}
|
||||
static void check_property_temperatures(NativeRun *r,double t,const double *y) {
|
||||
#if defined(MODEL_PROPERTY_TEMPERATURES) && MODEL_PROPERTY_TEMPERATURES
|
||||
NativePropertyTemperatures temperatures={0};
|
||||
/* Additional diagnostic evaluation does not alter states or solver counters. */
|
||||
if(!model_property_temperatures(t,y,&temperatures))return;
|
||||
for(int d=0;d<3;d++)if(temperatures.seen&(1u<<d))for(int upper=0;upper<2;upper++) {
|
||||
double T=upper?temperatures.maximum[d]:temperatures.minimum[d];
|
||||
double limit=upper?property_upper[d]:property_lower[d];
|
||||
/* Ignore inversion roundoff at an exact domain endpoint. */
|
||||
double tolerance=1e-9*fmax(limit,1);
|
||||
if(upper ? T<=limit+tolerance : T>=limit-tolerance)continue;
|
||||
int slot=2*d+upper;NativePropertyWarning *w=&r->property_warnings[slot];
|
||||
if(!w->seen) {
|
||||
w->seen=1;w->first_time=w->extreme_time=t;w->first_temperature=w->extreme_temperature=T;
|
||||
fputs("{\"phase\":\"property-warning\",\"warning\":",stderr);
|
||||
property_warning_json(stderr,slot,w);fputs("}\n",stderr);fflush(stderr);
|
||||
} else if(upper ? T>w->extreme_temperature : T<w->extreme_temperature) {
|
||||
w->extreme_temperature=T;w->extreme_time=t;
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)r;(void)t;(void)y;
|
||||
#endif
|
||||
}
|
||||
|
||||
static double locate(int idx, double bound, int lower, double left, double right,
|
||||
@@ -213,6 +261,7 @@ int native_accept(NativeRun *r, double t, double next, const double *old,
|
||||
} else memcpy(accepted_state,trial,NSTATES*sizeof(double));
|
||||
*accepted_time=stop;
|
||||
r->final_time=stop; memcpy(r->final_state,accepted_state,NSTATES*sizeof(double));
|
||||
check_property_temperatures(r,stop,accepted_state);
|
||||
return count ? 1 : 0;
|
||||
}
|
||||
|
||||
@@ -229,16 +278,24 @@ int native_solve(NativeRun *r) {
|
||||
}
|
||||
#endif
|
||||
r->sample_index=1;
|
||||
if (!native_append(r,r->options.start,y)) { r->status=2; r->message="Cannot allocate samples."; return 0; }
|
||||
check_property_temperatures(r,r->options.start,y);
|
||||
if (!native_append(r,r->options.start,y)) return 0;
|
||||
r->wall_start=native_wall_time(); r->cpu_start=native_cpu_time();
|
||||
r->last_progress=r->wall_start-1;
|
||||
int ok=r->options.bdf ? native_bdf(r) : native_rk45(r);
|
||||
r->solve_seconds=native_wall_time()-r->wall_start;
|
||||
r->solve_cpu_seconds=native_cpu_time()-r->cpu_start;
|
||||
if (!ok && !r->status) { r->status=2; r->message="Native integration failed to advance."; }
|
||||
if (!native_append(r,r->final_time,r->final_state)) { r->status=2; r->message="Cannot save final state."; }
|
||||
if (!ok && !r->status) native_fail(r,"integration-failure","integration","Native integration failed.");
|
||||
if (ok && !r->status && r->final_time!=r->options.stop)
|
||||
native_fail(r,"incomplete-result","integration","Native solver returned before the requested stop time.");
|
||||
if (!r->storage_failed) native_append(r,r->final_time,r->final_state);
|
||||
native_samples_flush(r);
|
||||
if (!r->message) r->message=r->status ? "Native integration failed." : "Simulation completed.";
|
||||
return !r->status;
|
||||
}
|
||||
|
||||
void native_run_free(NativeRun *r) { free(r->times); free(r->states); }
|
||||
void native_run_free(NativeRun *r) {
|
||||
free(r->times); free(r->states);
|
||||
if(r->sample_file) fclose(r->sample_file);
|
||||
if(r->output_file) fclose(r->output_file);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <sunmatrix/sunmatrix_dense.h>
|
||||
#include <sunlinsol/sunlinsol_dense.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sundials/sundials_math.h>
|
||||
#ifndef MODEL_JACOBIAN_COLORED
|
||||
@@ -195,59 +196,126 @@ static void counters(NativeRun *r, void *solver) {
|
||||
CVodeGetNumLinRhsEvals(solver,&value); r->linear_rhs+=(unsigned long)value;
|
||||
}
|
||||
|
||||
static void cv_snapshot(NativeRun *r,void *solver) {
|
||||
CVodeGetCurrentTime(solver,&r->cvode_internal_time);
|
||||
CVodeGetLastStep(solver,&r->cvode_last_step);
|
||||
CVodeGetCurrentStep(solver,&r->cvode_next_step);
|
||||
}
|
||||
|
||||
static void cv_failure(NativeRun *r,int flag,const char *operation) {
|
||||
char message[256];
|
||||
r->cvode_flag=flag;
|
||||
snprintf(message,sizeof(message),"CVODE operation %s failed (return code %d) at simulation time %.17g s.",
|
||||
operation,flag,r->final_time);
|
||||
native_fail(r,"solver-error",operation,message);
|
||||
}
|
||||
|
||||
#define CV_CHECK(call) do { int code_=(call); if(code_<0) { \
|
||||
cv_failure(r,code_,#call); goto cleanup; } } while(0)
|
||||
|
||||
int native_bdf(NativeRun *r) {
|
||||
SUNContext ctx=NULL;
|
||||
if (SUNContext_Create(SUN_COMM_NULL,&ctx)) return 0;
|
||||
if (SUNContext_Create(SUN_COMM_NULL,&ctx))
|
||||
return native_fail(r,"initialization-failure","SUNContext_Create","Cannot create SUNDIALS context.");
|
||||
N_Vector y=N_VNew_Serial(NSTATES,ctx), atol=N_VNew_Serial(NSTATES,ctx), scratch=N_VNew_Serial(NSTATES,ctx);
|
||||
SUNMatrix matrix=NULL; SUNLinearSolver linear=NULL; void *solver=NULL;
|
||||
int success=0;
|
||||
int success=0, initialized=0;
|
||||
CvContext context={.run=r};
|
||||
if (!y || !atol || !scratch) goto cleanup;
|
||||
const char *allocation="N_VNew_Serial";
|
||||
if (!y || !atol || !scratch) goto allocation_failure;
|
||||
memcpy(N_VGetArrayPointer(y),r->final_state,NSTATES*sizeof(double));
|
||||
memcpy(N_VGetArrayPointer(atol),model_atol,NSTATES*sizeof(double));
|
||||
matrix=SUNDenseMatrix(NSTATES,NSTATES,ctx);
|
||||
if (!matrix) goto cleanup;
|
||||
allocation="SUNDenseMatrix";
|
||||
if (!matrix) goto allocation_failure;
|
||||
linear=SUNLinSol_Dense(y,matrix,ctx);
|
||||
if (!linear) goto cleanup;
|
||||
allocation="SUNLinSol_Dense";
|
||||
if (!linear) goto allocation_failure;
|
||||
solver=CVodeCreate(CV_BDF,ctx);
|
||||
if (!solver) goto cleanup;
|
||||
allocation="CVodeCreate";
|
||||
if (!solver) goto allocation_failure;
|
||||
context.solver=solver;
|
||||
double t=r->options.start;
|
||||
if (CVodeInit(solver,cv_rhs,t,y)<0 || CVodeSetUserData(solver,&context)<0 ||
|
||||
CVodeSVtolerances(solver,r->options.rtol,atol)<0 ||
|
||||
CVodeSetLinearSolver(solver,linear,matrix)<0 ||
|
||||
CVodeSetMaxStep(solver,r->options.max_step)<0) goto cleanup;
|
||||
r->cvode_return_time=t;
|
||||
CV_CHECK(CVodeInit(solver,cv_rhs,t,y));
|
||||
initialized=1;
|
||||
CV_CHECK(CVodeSetUserData(solver,&context));
|
||||
CV_CHECK(CVodeSVtolerances(solver,r->options.rtol,atol));
|
||||
CV_CHECK(CVodeSetLinearSolver(solver,linear,matrix));
|
||||
CV_CHECK(CVodeSetMaxStep(solver,r->options.max_step));
|
||||
#if MODEL_JACOBIAN_COLORED
|
||||
if (valid_coloring()) {
|
||||
context.weights=N_VClone(y);
|
||||
if (!context.weights) goto cleanup;
|
||||
allocation="N_VClone";
|
||||
if (!context.weights) goto allocation_failure;
|
||||
if (r->jacobian_verify) {
|
||||
context.reference=SUNDenseMatrix(NSTATES,NSTATES,ctx);
|
||||
if (!context.reference) goto cleanup;
|
||||
allocation="SUNDenseMatrix (verification)";
|
||||
if (!context.reference) goto allocation_failure;
|
||||
}
|
||||
context.colored=1; r->jacobian_colored=1;
|
||||
if (CVodeSetJacFn(solver,cv_jacobian)<0) goto cleanup;
|
||||
CV_CHECK(CVodeSetJacFn(solver,cv_jacobian));
|
||||
}
|
||||
#endif
|
||||
r->starts++;
|
||||
CvDense dense={solver,scratch};
|
||||
while (t<r->options.stop) {
|
||||
double boundary=model_next_break(t,r->options.stop);
|
||||
if (!isfinite(boundary) || boundary<=t || boundary>r->options.stop) {
|
||||
native_fail(r,"invalid-boundary","model_next_break","Model returned an invalid next time boundary.");
|
||||
goto cleanup;
|
||||
}
|
||||
double end=boundary<r->options.stop?nextafter(boundary,-INFINITY):boundary;
|
||||
if (CVodeSetStopTime(solver,end)<0) goto cleanup;
|
||||
CV_CHECK(CVodeSetStopTime(solver,end));
|
||||
while (t<end) {
|
||||
if (!native_poll(r,t) || r->accepted>10000000 || r->events>10000) goto cleanup;
|
||||
if (!native_poll(r,t)) goto cleanup;
|
||||
if (r->accepted>10000000 || r->events>10000) {
|
||||
native_fail(r,"resource-limit","integration",r->events>10000?
|
||||
"Native state-transition limit exceeded.":"Native accepted-step limit exceeded.");
|
||||
goto cleanup;
|
||||
}
|
||||
double old[NSTATES], accepted[NSTATES], next=t;
|
||||
memcpy(old,N_VGetArrayPointer(y),sizeof(old));
|
||||
int flag=CVode(solver,end,y,&next,CV_ONE_STEP);
|
||||
if (flag<0 || next<=t) goto cleanup;
|
||||
r->cvode_flag=flag; r->cvode_return_time=next;
|
||||
if (flag<0) { cv_failure(r,flag,"CVode"); goto cleanup; }
|
||||
if (!isfinite(next)) {
|
||||
native_fail(r,"nonfinite-time","CVode","CVODE returned a non-finite simulation time."); goto cleanup;
|
||||
}
|
||||
for (int i=0;i<NSTATES;i++) if (!isfinite(N_VGetArrayPointer(y)[i])) {
|
||||
native_fail(r,"nonfinite-state","CVode","CVODE returned a non-finite accepted state."); goto cleanup;
|
||||
}
|
||||
if (next<t || next>end) {
|
||||
native_fail(r,next<t?"time-regression":"time-overshoot","CVode",
|
||||
next<t?"CVODE returned a time earlier than the last accepted time.":
|
||||
"CVODE advanced beyond the requested time boundary."); goto cleanup;
|
||||
}
|
||||
if (next==t) {
|
||||
/* A successful internal step may be smaller than one time ULP.
|
||||
* Retain CVODE's history/state and continue under the existing
|
||||
* wall-clock timeout/cancellation checks. Never fabricate time,
|
||||
* reinitialize, or evaluate zero-length dense/event intervals. */
|
||||
r->same_time_returns++; r->same_time_streak++;
|
||||
if (r->same_time_streak>r->max_same_time_streak) r->max_same_time_streak=r->same_time_streak;
|
||||
if (!r->stagnating)
|
||||
fprintf(stderr,"{\"event\":\"solver-time-stagnation\",\"time\":%.17g,\"returnCode\":%d}\n",t,flag);
|
||||
r->stagnating=1;
|
||||
continue;
|
||||
}
|
||||
if (r->stagnating)
|
||||
fprintf(stderr,"{\"event\":\"solver-time-resumed\",\"time\":%.17g,\"sameTimeReturns\":%lu}\n",next,r->same_time_streak);
|
||||
r->stagnating=0; r->same_time_streak=0;
|
||||
if (!native_poll(r,t)) goto cleanup;
|
||||
r->accepted++; r->max_accepted_step=fmax(r->max_accepted_step,next-t);
|
||||
int impact=native_accept(r,t,next,old,N_VGetArrayPointer(y),cv_dense,&dense,&t,accepted);
|
||||
if (impact<0) goto cleanup;
|
||||
if (impact<0) {
|
||||
native_fail(r,"sampling-event-failure","native_accept","Cannot evaluate an accepted step's samples or events.");
|
||||
goto cleanup;
|
||||
}
|
||||
memcpy(N_VGetArrayPointer(y),accepted,sizeof(accepted));
|
||||
if (impact) {
|
||||
counters(r,solver);
|
||||
if (CVodeReInit(solver,t,y)<0) goto cleanup;
|
||||
CV_CHECK(CVodeReInit(solver,t,y));
|
||||
r->starts++;
|
||||
}
|
||||
}
|
||||
@@ -255,17 +323,23 @@ int native_bdf(NativeRun *r) {
|
||||
memcpy(r->final_state,N_VGetArrayPointer(y),NSTATES*sizeof(double));
|
||||
double sample=r->options.start+r->sample_index*r->options.sample_step;
|
||||
if (r->options.record_samples && sample<=t && sample<=r->options.stop) {
|
||||
if (!native_append(r,sample,r->final_state)) goto cleanup;
|
||||
if (!native_append(r,sample,r->final_state)) {
|
||||
native_fail(r,"sample-storage-failure","native_append","Cannot store a boundary sample."); goto cleanup;
|
||||
}
|
||||
r->sample_index++;
|
||||
}
|
||||
if (t<r->options.stop) {
|
||||
counters(r,solver);
|
||||
if (CVodeReInit(solver,t,y)<0) goto cleanup;
|
||||
CV_CHECK(CVodeReInit(solver,t,y));
|
||||
r->starts++;
|
||||
}
|
||||
}
|
||||
success=1;
|
||||
goto cleanup;
|
||||
allocation_failure:
|
||||
native_fail(r,"allocation-failure",allocation,"Cannot allocate native solver resources.");
|
||||
cleanup:
|
||||
if (initialized) cv_snapshot(r,solver);
|
||||
if (solver) { counters(r,solver); CVodeFree(&solver); }
|
||||
if (context.reference) SUNMatDestroy(context.reference);
|
||||
if (context.weights) N_VDestroy(context.weights);
|
||||
@@ -277,3 +351,4 @@ cleanup:
|
||||
SUNContext_Free(&ctx);
|
||||
return success;
|
||||
}
|
||||
#undef CV_CHECK
|
||||
@@ -62,22 +62,27 @@ int native_json_write_number(FILE *file, double value) {
|
||||
return length>0 && write_bytes(file,text,(size_t)length);
|
||||
}
|
||||
|
||||
int native_json_write_array(FILE *file, const double *values, size_t count, size_t stride) {
|
||||
int native_json_write_values(FILE *file, const double *values, size_t count, size_t stride, int leading_comma) {
|
||||
if (!file || ferror(file) || (count && !values)) return 0;
|
||||
if (count>1 && (!stride || stride>(size_t)PTRDIFF_MAX/sizeof(double)/(count-1))) return 0;
|
||||
char buffer[65536];
|
||||
size_t used=1;
|
||||
buffer[0]='[';
|
||||
size_t used=0;
|
||||
for (size_t i=0;i<count;i++) {
|
||||
if (used>sizeof(buffer)-NATIVE_JSON_DOUBLE_CAPACITY-2) {
|
||||
if (!write_bytes(file,buffer,used)) return 0;
|
||||
used=0;
|
||||
}
|
||||
if (i) buffer[used++]=',';
|
||||
if (i || leading_comma) buffer[used++]=',';
|
||||
int length=native_json_format_double(buffer+used,values[i*stride]);
|
||||
if (!length) return 0;
|
||||
used+=(size_t)length;
|
||||
}
|
||||
buffer[used++]=']';
|
||||
return write_bytes(file,buffer,used);
|
||||
}
|
||||
|
||||
int native_json_write_array(FILE *file, const double *values, size_t count, size_t stride) {
|
||||
if (!file || ferror(file) || (count && !values)) return 0;
|
||||
if (count>1 && (!stride || stride>(size_t)PTRDIFF_MAX/sizeof(double)/(count-1))) return 0;
|
||||
if (fputc('[',file)==EOF) return 0;
|
||||
return native_json_write_values(file,values,count,stride,0) && fputc(']',file)!=EOF;
|
||||
}
|
||||
+30
-24
@@ -31,13 +31,13 @@ static int probe(void) {
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static int write_result_index(const char *path, long series_start, long series_end,
|
||||
long result_bytes, size_t sample_count) {
|
||||
static int write_result_index(const char *path, int64_t series_start, int64_t series_end,
|
||||
int64_t result_bytes, size_t sample_count) {
|
||||
if(series_start<0 || series_end<series_start || result_bytes<series_end) return 0;
|
||||
FILE *index=fopen(path,"wb"); if(!index) return 0;
|
||||
int ok=fprintf(index,"{\"version\":1,\"seriesStart\":%ld,\"seriesEnd\":%ld,"
|
||||
"\"resultBytes\":%ld,\"sampleCount\":%zu}\n",
|
||||
series_start,series_end,result_bytes,sample_count)>=0;
|
||||
int ok=fprintf(index,"{\"version\":1,\"seriesStart\":%lld,\"seriesEnd\":%lld,"
|
||||
"\"resultBytes\":%lld,\"sampleCount\":%zu}\n",
|
||||
(long long)series_start,(long long)series_end,(long long)result_bytes,sample_count)>=0;
|
||||
if(ferror(index)) ok=0;
|
||||
if(fclose(index)) ok=0;
|
||||
return ok;
|
||||
@@ -46,19 +46,23 @@ static int write_result(NativeRun *r, const char *path, const char *index_path)
|
||||
if(index_path && !strcmp(path,index_path)) return 0;
|
||||
double dy[NSTATES], final[NOUTPUTS];
|
||||
int final_ok=model_eval(r->final_time,r->final_state,dy,final);
|
||||
size_t length=r->count*NOUTPUTS;
|
||||
if (length>268435456u/sizeof(double)) return 0;
|
||||
double *values=length?malloc(length*sizeof(double)):NULL;
|
||||
if (length && !values) return 0;
|
||||
for (size_t i=0;i<r->count;i++) {
|
||||
if (!model_eval(r->times[i],r->states+i*NSTATES,dy,values+i*NOUTPUTS)) {
|
||||
free(values); return 0;
|
||||
}
|
||||
}
|
||||
FILE *f=fopen(path,"wb"); if (!f) { free(values); return 0; }
|
||||
if (!native_samples_outputs(r)) return 0;
|
||||
FILE *f=fopen(path,"wb"); if (!f) return 0;
|
||||
fprintf(f,"{\"success\":%s,\"status\":",!r->status?"true":"false");
|
||||
json_string(f,r->status==0?"completed":r->status==1?"cancelled":"failed");
|
||||
fprintf(f,",\"message\":"); json_string(f,r->message);
|
||||
fprintf(f,",\"propertyWarnings\":"); native_property_warnings_json(r,f);
|
||||
fprintf(f,",\"solverControl\":{\"reason\":"); json_string(f,r->failure_reason?r->failure_reason:"");
|
||||
fprintf(f,",\"operation\":"); json_string(f,r->failure_operation?r->failure_operation:"");
|
||||
fprintf(f,",\"returnCode\":%d,\"sameTimeReturns\":%lu,\"maxSameTimeStreak\":%lu",
|
||||
r->cvode_flag,r->same_time_returns,r->max_same_time_streak);
|
||||
const char *names[]={"returnTime","internalTime","lastStep","nextStep"};
|
||||
double diagnostic[]={r->cvode_return_time,r->cvode_internal_time,r->cvode_last_step,r->cvode_next_step};
|
||||
for(int i=0;i<4;i++) {
|
||||
fprintf(f,",\"%s\":",names[i]);
|
||||
if(isfinite(diagnostic[i])) fprintf(f,"%.17g",diagnostic[i]); else fputs("null",f);
|
||||
}
|
||||
fputc('}',f);
|
||||
fprintf(f,",\"jacobianMode\":\"%s\",\"jacobianRhsCalls\":%lu,"
|
||||
"\"jacobianColoredEvals\":%lu,\"jacobianFallbacks\":%lu,"
|
||||
"\"jacobianChecks\":%lu,\"jacobianMismatches\":%lu,"
|
||||
@@ -75,22 +79,22 @@ static int write_result(NativeRun *r, const char *path, const char *index_path)
|
||||
r->events,r->starts,r->njev,r->nlu,r->max_accepted_step);
|
||||
/* Binary-mode positions delimit the complete series object, including
|
||||
both braces. The optional index avoids scanning or parsing its values. */
|
||||
long series_start=-1,series_end=-1,result_bytes=-1;
|
||||
int64_t series_start=-1,series_end=-1,result_bytes=-1;
|
||||
if(index_path) {
|
||||
series_start=ftell(f);
|
||||
series_start=native_file_tell(f);
|
||||
if(series_start>0) series_start--; else series_start=-1;
|
||||
}
|
||||
int output_ok=1;
|
||||
if (r->count) {
|
||||
fprintf(f,"\"time\":");
|
||||
output_ok=native_json_write_array(f,r->times,r->count,1);
|
||||
output_ok=native_samples_json(r,f,0);
|
||||
for (int j=0;j<NOUTPUTS && output_ok;j++) {
|
||||
fputc(',',f); json_string(f,model_output_keys[j]); fputc(':',f);
|
||||
output_ok=native_json_write_array(f,values+j,r->count,NOUTPUTS);
|
||||
output_ok=native_samples_json(r,f,(size_t)j+1);
|
||||
}
|
||||
}
|
||||
fputc('}',f);
|
||||
if(index_path) series_end=ftell(f);
|
||||
if(index_path) series_end=native_file_tell(f);
|
||||
fprintf(f,",\"final\":{");
|
||||
if (final_ok) for (int j=0;j<NOUTPUTS && output_ok;j++) {
|
||||
if (j) fputc(',',f);
|
||||
@@ -101,14 +105,14 @@ static int write_result(NativeRun *r, const char *path, const char *index_path)
|
||||
if (output_ok) output_ok=native_json_write_array(f,r->final_state,NSTATES,1);
|
||||
fprintf(f,"}\n"); int ok=output_ok && !ferror(f);
|
||||
if(index_path) {
|
||||
result_bytes=ftell(f);
|
||||
result_bytes=native_file_tell(f);
|
||||
if(series_start<0 || series_end<0 || result_bytes<0) ok=0;
|
||||
}
|
||||
if (fclose(f)) ok=0;
|
||||
/* Publish the index only after the complete result was successfully
|
||||
flushed and closed. An index I/O failure is a failed result write. */
|
||||
if(ok && index_path) ok=write_result_index(index_path,series_start,series_end,result_bytes,r->count);
|
||||
free(values); return ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
@@ -122,11 +126,14 @@ int main(int argc, char **argv) {
|
||||
double y[NSTATES]; if (!model_init(y)) return 2;
|
||||
vector(stdout,y,NSTATES); fputc('\n',stdout); return 0;
|
||||
}
|
||||
if (!strcmp(arg,"--storage-control")) { r.storage_control=1; continue; }
|
||||
if (!strcmp(arg,"--solve-only")) { r.options.record_samples=0; continue; }
|
||||
if (!strcmp(arg,"--verify-jacobian")) { r.jacobian_verify=1; continue; }
|
||||
if (i+1==argc) return 64;
|
||||
const char *value=argv[++i];
|
||||
if (!strcmp(arg,"--output")) output=value;
|
||||
else if (!strcmp(arg,"--sample-file")) r.sample_path=value;
|
||||
else if (!strcmp(arg,"--output-block-file")) r.output_blocks_path=value;
|
||||
else if (!strcmp(arg,"--result-index")) index_path=value;
|
||||
else if (!strcmp(arg,"--cancel-file")) r.options.cancel_path=value;
|
||||
else if (!strcmp(arg,"--method")) {
|
||||
@@ -150,8 +157,7 @@ int main(int argc, char **argv) {
|
||||
r.options.start+r.options.max_step==r.options.start ||
|
||||
!isfinite(r.options.stop-r.options.start)) return 64;
|
||||
if (r.options.record_samples &&
|
||||
((r.options.stop-r.options.start)/r.options.sample_step>1000000 ||
|
||||
((r.options.stop-r.options.start)/r.options.sample_step+1024)*(NSTATES+NOUTPUTS)*sizeof(double)>268435456)) return 64;
|
||||
((r.options.stop-r.options.start)/r.options.sample_step>1000000)) return 64;
|
||||
native_solve(&r);
|
||||
int saved=write_result(&r,output,index_path);
|
||||
int code=saved?(r.status==2?2:0):3;
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/* Append-only, little-endian binary64 blocks. No output evaluation during solve.
|
||||
* Each block: SIMBLK01, u64 sequence/rows/columns/crc32, column-major payload,
|
||||
* COMMIT01. A truncated/uncommitted tail is never a valid block.
|
||||
* Synchronous buffered writes provide backpressure without a producer queue. */
|
||||
#include "runtime.h"
|
||||
#include "json_numbers.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <float.h>
|
||||
#include <limits.h>
|
||||
#include <sys/types.h>
|
||||
#ifndef NATIVE_SAMPLE_BUFFER_BYTES
|
||||
#define NATIVE_SAMPLE_BUFFER_BYTES 1048576u
|
||||
#endif
|
||||
|
||||
_Static_assert(sizeof(double)==8 && DBL_MANT_DIG==53 && DBL_MAX_EXP==1024,
|
||||
"Result blocks require IEEE-754 binary64");
|
||||
|
||||
int64_t native_file_tell(FILE *f) {
|
||||
/* MinGW/MSVCRT can overcount a buffered final newline in _ftelli64 even
|
||||
for a binary FILE. Query the committed byte position instead. */
|
||||
if(fflush(f)) return -1;
|
||||
#ifdef _WIN32
|
||||
return _ftelli64(f);
|
||||
#else
|
||||
return (int64_t)ftello(f);
|
||||
#endif
|
||||
}
|
||||
static int seek_file(FILE *f, uint64_t offset) {
|
||||
if(offset>INT64_MAX) return 0;
|
||||
#ifdef _WIN32
|
||||
return _fseeki64(f,(int64_t)offset,SEEK_SET)==0;
|
||||
#else
|
||||
return fseeko(f,(off_t)offset,SEEK_SET)==0;
|
||||
#endif
|
||||
}
|
||||
static void put64(unsigned char *p,uint64_t n) {
|
||||
for(int i=0;i<8;i++) {p[i]=(unsigned char)n;n>>=8;}
|
||||
}
|
||||
static uint64_t get64(const unsigned char *p) {
|
||||
uint64_t n=0;for(int i=7;i>=0;i--) n=(n<<8)|p[i];return n;
|
||||
}
|
||||
static void little_endian(double *values,size_t count) {
|
||||
const uint16_t one=1;
|
||||
if(*(const unsigned char *)&one) return;
|
||||
unsigned char *p=(unsigned char *)values;
|
||||
for(size_t i=0;i<count;i++,p+=8) for(int j=0;j<4;j++) {
|
||||
unsigned char v=p[j];p[j]=p[7-j];p[7-j]=v;
|
||||
}
|
||||
}
|
||||
static uint32_t checksum(const void *data,size_t length) {
|
||||
uint32_t table[256];
|
||||
for(unsigned i=0;i<256;i++) {
|
||||
uint32_t c=i;
|
||||
for(int j=0;j<8;j++) c=(c>>1)^((c&1)?UINT32_C(0xedb88320):0);
|
||||
table[i]=c;
|
||||
}
|
||||
uint32_t c=UINT32_MAX;const unsigned char *p=data;
|
||||
for(size_t i=0;i<length;i++) c=table[(c^p[i])&255]^(c>>8);
|
||||
return c^UINT32_MAX;
|
||||
}
|
||||
static int storage_error(NativeRun *r,const char *reason,const char *message) {
|
||||
r->storage_failed=1;
|
||||
/* Storage failure must also be visible when flushing a cancelled run. */
|
||||
r->status=2;r->failure_reason=reason;r->failure_operation="sample-storage";
|
||||
snprintf(r->message_buffer,sizeof(r->message_buffer),"%s",message);
|
||||
r->message=r->message_buffer;
|
||||
r->count=r->committed;r->buffered=0;
|
||||
return 0;
|
||||
}
|
||||
static int write_block(FILE *f,uint64_t sequence,size_t rows,size_t columns,double *data) {
|
||||
size_t length=rows*columns*sizeof(double);
|
||||
unsigned char header[40];memcpy(header,"SIMBLK01",8);
|
||||
put64(header+8,sequence);put64(header+16,rows);put64(header+24,columns);
|
||||
little_endian(data,rows*columns);
|
||||
put64(header+32,checksum(data,length));
|
||||
int ok=fwrite(header,1,sizeof(header),f)==sizeof(header) &&
|
||||
fwrite(data,1,length,f)==length && fwrite("COMMIT01",1,8,f)==8 &&
|
||||
fflush(f)==0 && !ferror(f);
|
||||
little_endian(data,rows*columns);
|
||||
return ok;
|
||||
}
|
||||
static int read_block(FILE *f,uint64_t sequence,size_t rows,size_t columns,double *data) {
|
||||
unsigned char header[40],tail[8];size_t length=rows*columns*sizeof(double);
|
||||
if(fread(header,1,40,f)!=40 || memcmp(header,"SIMBLK01",8) ||
|
||||
get64(header+8)!=sequence || get64(header+16)!=rows || get64(header+24)!=columns ||
|
||||
fread(data,1,length,f)!=length || fread(tail,1,8,f)!=8 || memcmp(tail,"COMMIT01",8) ||
|
||||
get64(header+32)!=checksum(data,length)) return 0;
|
||||
little_endian(data,rows*columns);return 1;
|
||||
}
|
||||
int native_samples_flush(NativeRun *r) {
|
||||
if(r->storage_failed) return 0;
|
||||
if(!r->buffered) return 1;
|
||||
size_t rows=r->buffered;
|
||||
/* Reserve both this state block and its future output block before writing.
|
||||
The parent serializes quota grants across concurrent simulations. */
|
||||
uint64_t bytes=96+(uint64_t)rows*(NSTATES+NOUTPUTS+2)*8;
|
||||
if(r->storage_control) {
|
||||
char reply[16];
|
||||
fprintf(stderr,"{\"phase\":\"storage-reserve\",\"bytes\":%llu}\n",(unsigned long long)bytes);
|
||||
fflush(stderr);
|
||||
if(!fgets(reply,sizeof(reply),stdin))
|
||||
return storage_error(r,"storage-control","Result storage controller disconnected; complete blocks were retained.");
|
||||
if(!strcmp(reply,"full\n"))
|
||||
return storage_error(r,"storage-quota","Result storage quota exhausted; complete blocks were retained.");
|
||||
if(strcmp(reply,"ok\n"))
|
||||
return storage_error(r,"storage-io","Result storage I/O failed; complete blocks were retained.");
|
||||
}
|
||||
double *data=malloc(rows*(NSTATES+1)*sizeof(double));
|
||||
if(!data) return storage_error(r,"storage-memory","Cannot allocate result block.");
|
||||
memcpy(data,r->times,rows*sizeof(double));
|
||||
for(int j=0;j<NSTATES;j++) for(size_t i=0;i<rows;i++)
|
||||
data[(j+1)*rows+i]=r->states[i*NSTATES+j];
|
||||
int ok=write_block(r->sample_file,r->committed/r->capacity,rows,NSTATES+1,data);
|
||||
free(data);
|
||||
if(!ok) return storage_error(r,"storage-io","Cannot write result block; complete blocks were retained.");
|
||||
r->committed+=rows;r->buffered=0;return 1;
|
||||
}
|
||||
int native_samples_append(NativeRun *r,double t,const double *state) {
|
||||
if(r->storage_failed) return 0;
|
||||
if(!r->capacity) {
|
||||
size_t columns=NSTATES>NOUTPUTS?NSTATES+1:NOUTPUTS+1;
|
||||
r->capacity=NATIVE_SAMPLE_BUFFER_BYTES/(columns*sizeof(double));
|
||||
if(!r->capacity) r->capacity=1;
|
||||
if(r->capacity>1024) r->capacity=1024;
|
||||
r->times=malloc(r->capacity*sizeof(double));
|
||||
r->states=malloc(r->capacity*NSTATES*sizeof(double));
|
||||
r->sample_file=r->sample_path?fopen(r->sample_path,"w+b"):tmpfile();
|
||||
if(!r->times || !r->states || !r->sample_file)
|
||||
return storage_error(r,"storage-io","Cannot initialize result storage.");
|
||||
setvbuf(r->sample_file,NULL,_IOFBF,65536);
|
||||
}
|
||||
/* Hold the newest sample until a distinct time arrives, preserving the
|
||||
pre-existing same-time replacement policy even at block boundaries. */
|
||||
if(r->buffered && r->times[r->buffered-1]==t) {r->buffered--;r->count--;}
|
||||
if(r->buffered==r->capacity && !native_samples_flush(r)) return 0;
|
||||
r->times[r->buffered]=t;
|
||||
memcpy(r->states+r->buffered*NSTATES,state,NSTATES*sizeof(double));
|
||||
r->buffered++;r->count++;return 1;
|
||||
}
|
||||
int native_samples_outputs(NativeRun *r) {
|
||||
if(!r->committed) return 1;
|
||||
r->output_file=r->output_blocks_path?fopen(r->output_blocks_path,"w+b"):tmpfile();
|
||||
if(!r->output_file || !seek_file(r->sample_file,0)) return 0;
|
||||
setvbuf(r->output_file,NULL,_IOFBF,65536);
|
||||
double *states=malloc(r->capacity*(NSTATES+1)*sizeof(double));
|
||||
double *outputs=malloc(r->capacity*(NOUTPUTS+1)*sizeof(double));
|
||||
int ok=states && outputs;
|
||||
for(size_t start=0;ok && start<r->committed;start+=r->capacity) {
|
||||
size_t rows=r->committed-start;if(rows>r->capacity) rows=r->capacity;
|
||||
ok=read_block(r->sample_file,start/r->capacity,rows,NSTATES+1,states);
|
||||
for(size_t i=0;ok && i<rows;i++) {
|
||||
double y[NSTATES],dy[NSTATES],w[NOUTPUTS];
|
||||
for(int j=0;j<NSTATES;j++) y[j]=states[(j+1)*rows+i];
|
||||
ok=model_eval(states[i],y,dy,w);
|
||||
outputs[i]=states[i];
|
||||
if(ok) for(int j=0;j<NOUTPUTS;j++) outputs[(j+1)*rows+i]=w[j];
|
||||
}
|
||||
if(ok) ok=write_block(r->output_file,start/r->capacity,rows,NOUTPUTS+1,outputs);
|
||||
if(ok) r->output_count+=rows;
|
||||
}
|
||||
free(states);free(outputs);return ok;
|
||||
}
|
||||
int native_samples_json(NativeRun *r,FILE *f,size_t column) {
|
||||
if(column>NOUTPUTS || r->output_count!=r->count || fputc('[',f)==EOF) return 0;
|
||||
double *values=malloc((r->capacity?r->capacity:1)*sizeof(double));
|
||||
if(!values) return 0;
|
||||
int ok=1;
|
||||
for(size_t start=0;ok && start<r->count;start+=r->capacity) {
|
||||
size_t rows=r->count-start;if(rows>r->capacity) rows=r->capacity;
|
||||
uint64_t offset=(uint64_t)(start/r->capacity)*(48+(uint64_t)r->capacity*(NOUTPUTS+1)*8);
|
||||
ok=seek_file(r->output_file,offset+40+(uint64_t)column*rows*8) &&
|
||||
fread(values,sizeof(double),rows,r->output_file)==rows;
|
||||
if(ok) {little_endian(values,rows);ok=native_json_write_values(f,values,rows,1,start!=0);}
|
||||
}
|
||||
free(values);return ok && fputc(']',f)!=EOF;
|
||||
}
|
||||
Reference in new issue
Block a user