Archived
Freeze naive-ordering complete scores and bounded LOG parser
This commit is contained in:
1 parent
81dede0bd1
commit
9b7121a407
30 files changed
+1735298
No files matched your search
@@ -0,0 +1,113 @@
|
||||
"""Read-only LOG diagnostics under tolerances fixed before numeric rows were read."""
|
||||
import math
|
||||
import re
|
||||
|
||||
|
||||
FIELDS = ('time_s', 'fill_percent', 'injection_pressure_Pa', 'clamp_force_N',
|
||||
'flow_m3_s', 'frozen_percent')
|
||||
|
||||
|
||||
def parse(raw):
|
||||
# LF is the archive's physical line delimiter; retain raw CR bytes in raw files.
|
||||
lines = raw.decode('utf-8', errors='strict').split('\n')
|
||||
rows, headers, units, unsupported, mentions, transitions = [], [], [], [], [], []
|
||||
active = False
|
||||
for number, original in enumerate(lines, 1):
|
||||
text = original.rstrip('\r').strip()
|
||||
if re.search(r'V/P|velocity/pressure|switch.over', text, re.I):
|
||||
mentions.append(dict(line=number, text=text))
|
||||
if '|' in text and 'Time' in text:
|
||||
active = 'Fill Vol' in text and 'Flow Rate' in text
|
||||
if active:
|
||||
headers.append(dict(line=number, text=text))
|
||||
continue
|
||||
if text.startswith('End of filling') or text.startswith('Pack Analysis'):
|
||||
active = False
|
||||
if not active or not text.startswith('|'):
|
||||
continue
|
||||
columns = [v.strip() for v in text.strip('|').split('|')]
|
||||
if '(s)' in text:
|
||||
units.append(dict(line=number, text=text))
|
||||
continue
|
||||
if set(text) <= set('|-+ '):
|
||||
continue
|
||||
try:
|
||||
if len(columns) != 7:
|
||||
raise ValueError('expected seven table columns')
|
||||
values = [float(v) for v in columns[:6]]
|
||||
if not all(math.isfinite(v) for v in values):
|
||||
raise ValueError('nonfinite printed value')
|
||||
except ValueError as exc:
|
||||
unsupported.append(dict(line=number, text=text, reason=str(exc)))
|
||||
continue
|
||||
row = dict(zip(FIELDS, values), line=number, status=columns[6],
|
||||
printed_columns=columns, raw_line=original.rstrip('\r'))
|
||||
rows.append(row)
|
||||
if len(rows) == 1 or rows[-2]['status'] != row['status']:
|
||||
transitions.append(dict(line=number, time_s=row['time_s'],
|
||||
fill_percent=row['fill_percent'], status=row['status']))
|
||||
expected_units = ('(s)', '(%)', '(Pa)', '(N)', '(m^3/s)', 'Vol (%)')
|
||||
units_supported = bool(units) and all(all(x in u['text'] for x in expected_units) for u in units)
|
||||
return dict(table_present=bool(headers), headers=headers, units=units,
|
||||
units_supported=units_supported, rows=rows, unsupported_rows=unsupported,
|
||||
status_transitions=transitions, switch_mentions=mentions,
|
||||
physical_line_count=len(lines))
|
||||
|
||||
|
||||
def flow_window(rows, tolerance):
|
||||
if len(rows) < 2 or rows[-1]['time_s'] <= rows[0]['time_s']:
|
||||
return dict(defined=False, reason='insufficient_time_span', rows=len(rows))
|
||||
span = rows[-1]['time_s'] - rows[0]['time_s']
|
||||
integral = sum((b['time_s']-a['time_s'])*(a['flow_m3_s']+b['flow_m3_s'])/2
|
||||
for a, b in zip(rows, rows[1:]))
|
||||
mean = integral/span
|
||||
common = dict(rows=len(rows), first_time_s=rows[0]['time_s'], last_time_s=rows[-1]['time_s'],
|
||||
first_fill_percent=rows[0]['fill_percent'], last_fill_percent=rows[-1]['fill_percent'],
|
||||
printed_flow_time_weighted_mean=mean,
|
||||
all_printed_flow_zero=all(r['flow_m3_s'] == 0 for r in rows))
|
||||
if mean == 0:
|
||||
return dict(common, defined=False, reason='zero_printed_mean_cannot_assess_relative_flatness')
|
||||
departure = max(abs(r['flow_m3_s']-mean) for r in rows)/abs(mean)
|
||||
return dict(common, defined=True, max_relative_departure=departure,
|
||||
within_fixed_tolerance=departure <= tolerance)
|
||||
|
||||
|
||||
def diagnose(parsed, contract):
|
||||
rows = parsed['rows']
|
||||
if not parsed['table_present']:
|
||||
return dict(status='NO_MATCHING_TABLE_HEADER', quantitative_defined=False)
|
||||
if parsed['unsupported_rows'] or not parsed['units_supported'] or len(rows) < 2:
|
||||
return dict(status='TABLE_PRESENT_BUT_UNSUPPORTED_OR_INSUFFICIENT', quantitative_defined=False)
|
||||
epsilon = contract['monotonicity_numeric_tolerance']
|
||||
end = next((i for i, r in enumerate(rows) if r['fill_percent'] >= 100-epsilon), None)
|
||||
fill = rows[:end+1] if end is not None else rows
|
||||
violations = [dict(left_line=a['line'], right_line=b['line']) for a,b in zip(fill,fill[1:])
|
||||
if b['time_s'] < a['time_s']-epsilon or b['fill_percent'] < a['fill_percent']-epsilon]
|
||||
if violations or any(r['fill_percent'] < -epsilon or r['fill_percent'] > 100+epsilon or r['time_s'] < 0 for r in fill):
|
||||
return dict(status='NONMONOTONE_OR_OUT_OF_RANGE', quantitative_defined=False, violations=violations)
|
||||
first, last = fill[0], fill[-1]
|
||||
span = last['time_s']-first['time_s']
|
||||
if span <= 0:
|
||||
return dict(status='INSUFFICIENT_TIME_SPAN', quantitative_defined=False)
|
||||
residuals = [r['fill_percent']-(first['fill_percent']+(last['fill_percent']-first['fill_percent'])*
|
||||
(r['time_s']-first['time_s'])/span) for r in fill]
|
||||
maximum = max(map(abs,residuals))
|
||||
switch = [dict(line=r['line'], time_s=r['time_s'], fill_percent=r['fill_percent'], status=r['status'])
|
||||
for r in fill if re.search(r'V\s*/\s*P|switch.over',r['status'],re.I)]
|
||||
pre = [r for r in fill if switch and r['line'] < switch[0]['line']]
|
||||
supplement = None
|
||||
if end is not None and last['time_s'] > 0:
|
||||
supp = max(abs(r['fill_percent']-100*r['time_s']/last['time_s']) for r in fill)
|
||||
supplement = dict(assumed_origin=[0,0], max_deviation_percentage_points=supp,
|
||||
within_fixed_tolerance=supp <= contract['linearity_tolerance_percentage_points'])
|
||||
return dict(status='PARSED', quantitative_defined=True, filling_rows=len(fill),
|
||||
first_row=first, last_row=last, reached_printed_100_percent=end is not None,
|
||||
equal_printed_time_intervals=sum(a['time_s']==b['time_s'] for a,b in zip(fill,fill[1:])),
|
||||
observed_switch_rows=switch, no_switch_time_inferred_from_settings=True,
|
||||
linearity=dict(max_deviation_percentage_points=maximum,
|
||||
within_fixed_tolerance=maximum <= contract['linearity_tolerance_percentage_points'],
|
||||
endpoint_residuals_pp=residuals, assumed_origin_supplement=supplement),
|
||||
flow=dict(whole_fill=flow_window(fill,contract['flow_flatness_relative_tolerance']),
|
||||
fixed_5_to_95_percent=flow_window([r for r in fill if 5<=r['fill_percent']<=95],contract['flow_flatness_relative_tolerance']),
|
||||
before_explicit_VP=flow_window(pre,contract['flow_flatness_relative_tolerance']) if switch else
|
||||
dict(defined=False,reason='no_explicit_switch_row')))
|
||||
@@ -0,0 +1,104 @@
|
||||
"""One bounded 624-LOG read-only diagnostic. Never reads VTU/model labels."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import time
|
||||
from zipfile import ZipFile
|
||||
from moldflow_time_map import parse, diagnose
|
||||
from s2_recovery_supervisor import save, supervise
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def quantiles(values):
|
||||
if not values:return None
|
||||
v=sorted(values)
|
||||
def q(p):
|
||||
i=(len(v)-1)*p;j=int(i)
|
||||
return v[j]+(v[min(j+1,len(v)-1)]-v[j])*(i-j)
|
||||
return dict(n=len(v),min=v[0],p10=q(.1),median=q(.5),p90=q(.9),max=v[-1])
|
||||
|
||||
|
||||
def checked(root):
|
||||
c=json.loads((root/'tolerances.json').read_text())
|
||||
f=json.loads((root/'code-freeze.json').read_text())
|
||||
if sha(root/'tolerances.json')!=f['tolerances_sha256']:raise ValueError('Tolerance mutation')
|
||||
for p,h in f['source_sha256'].items():
|
||||
if sha(p)!=h:raise ValueError('Source mutation '+p)
|
||||
a=c['archive_stat'];st=Path(c['archive']).stat()
|
||||
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(a['bytes'],a['mtime_ns'],a['inode']):raise ValueError('Archive changed')
|
||||
return c,f
|
||||
|
||||
|
||||
def worker(root):
|
||||
c,f=checked(root)
|
||||
if (root/'started.json').exists():raise FileExistsError('No repeat LOG pass')
|
||||
os.sched_setaffinity(0,[24]);start=time.process_time()
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),code_freeze=f))
|
||||
dest=root/'logs';dest.mkdir(exist_ok=False);records=[]
|
||||
with ZipFile(c['archive']) as z:
|
||||
members=sorted(n for n in z.namelist() if n.endswith('.log'))
|
||||
if len(members)!=624:raise ValueError('LOG count changed')
|
||||
if len({Path(n).name for n in members})!=624:raise ValueError('Basename collision')
|
||||
for member in members:
|
||||
info=z.getinfo(member)
|
||||
if info.file_size>c['limits']['per_log_bytes']:raise ValueError('Per-LOG size cap')
|
||||
raw=z.read(member);path=dest/Path(member).name;path.write_bytes(raw)
|
||||
try:
|
||||
p=parse(raw);d=diagnose(p,c)
|
||||
except Exception as exc:
|
||||
p=dict(parse_error=repr(exc));d=dict(status='PARSE_ERROR_RAW_RETAINED',quantitative_defined=False)
|
||||
report=dict(member=member,raw_path=str(path),raw_sha256=sha(path),parsed=p,diagnostic=d)
|
||||
out=path.with_suffix('.json');save(out,report)
|
||||
records.append(dict(member=member,report=str(out),report_sha256=sha(out),diagnostic=d))
|
||||
save(root/'progress.json',dict(logs=len(records),CPU_s=time.process_time()-start))
|
||||
valid=[r['diagnostic'] for r in records if r['diagnostic']['quantitative_defined']]
|
||||
save(root/'index.json',records)
|
||||
flow={}
|
||||
for window in ('whole_fill','fixed_5_to_95_percent','before_explicit_VP'):
|
||||
a=[r['flow'][window] for r in valid];defined=[r for r in a if r['defined']]
|
||||
flow[window]=dict(defined=len(defined),within_tolerance=sum(r['within_fixed_tolerance'] for r in defined),
|
||||
undefined_reasons=dict(Counter(r.get('reason') for r in a if not r['defined'])),
|
||||
departures=quantiles([r['max_relative_departure'] for r in defined]))
|
||||
summary=dict(status='LOG_DIAGNOSTIC_COMPLETE',logs=len(records),parsed=len(valid),
|
||||
parse_statuses=dict(Counter(r['diagnostic']['status'] for r in records)),
|
||||
tolerance_commit='81dede0bd1775c02712a1e83467a0e4832e93424',tolerances_sha256=sha(root/'tolerances.json'),
|
||||
index_sha256=sha(root/'index.json'),printed_100_rows=sum(r['reached_printed_100_percent'] for r in valid),
|
||||
linearity_within_tolerance=sum(r['linearity']['within_fixed_tolerance'] for r in valid),
|
||||
max_linearity_deviation_pp=quantiles([r['linearity']['max_deviation_percentage_points'] for r in valid]),
|
||||
explicit_switch_parts=sum(bool(r['observed_switch_rows']) for r in valid),
|
||||
switch_volume_percent=quantiles([r['observed_switch_rows'][0]['fill_percent'] for r in valid if r['observed_switch_rows']]),
|
||||
flow=flow,worker_analysis_CPU_s=time.process_time()-start,
|
||||
limitations=['Printed LOG rows are rounded, not full simulation fields.',
|
||||
'Zero printed flow cannot establish zero actual flow or flatness.',
|
||||
'Linearity uses observed window and fixed 1 percentage point tolerance; not exact constant flow.',
|
||||
'V/P rows and filling end are distinct from retained-tet labelled endpoint.',
|
||||
'No model inputs, labels, fits, frozen predictions or other task sources changed.'])
|
||||
save(root/'summary.json',summary)
|
||||
return 0
|
||||
|
||||
|
||||
def guard(root):
|
||||
c,f=checked(root);limits=c['limits'];sample=json.loads((root/'format-sample-receipt.json').read_text())
|
||||
# Include format inspection once in the independent one CPU-hour LOG ledger.
|
||||
remaining=limits['worker_CPU_s']-sample['CPU_s']
|
||||
os.sched_setaffinity(0,[26])
|
||||
receipt=supervise([sys.executable,__file__,str(root),'--worker'],root,'log-worker',dict(
|
||||
total_cpu_seconds=remaining,job_cpu_seconds=remaining,job_wall_seconds=limits['wall_s'],
|
||||
tree_rss_bytes=limits['RSS_bytes'],disk_bytes=limits['disk_bytes'],max_processes=1),poll=.2)
|
||||
save(root/'guard-result.json',dict(worker=receipt,format_sample_CPU_s=sample['CPU_s'],
|
||||
cumulative_worker_CPU_s=sample['CPU_s']+receipt['cpu_seconds'],CPU_cap=limits['worker_CPU_s'],
|
||||
guard_CPU_s=sum(resource.getrusage(resource.RUSAGE_SELF)[:2])))
|
||||
return 0 if receipt['status']=='PASS' else 1
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('--worker',action='store_true');a=p.parse_args()
|
||||
raise SystemExit(worker(a.root) if a.worker else guard(a.root))
|
||||
@@ -0,0 +1,60 @@
|
||||
import unittest
|
||||
from moldflow_time_map import parse, diagnose, flow_window
|
||||
|
||||
C = dict(monotonicity_numeric_tolerance=1e-9, linearity_tolerance_percentage_points=1.,
|
||||
flow_flatness_relative_tolerance=.05)
|
||||
HEADER = '| Time | Fill Vol | Inj Press | Clamp F | Flow Rate | Frozen | Status |\n| (s) | (%) | (Pa) | (N) | (m^3/s) | Vol (%) | |\n'
|
||||
|
||||
|
||||
def sample(rows, prefix=''):
|
||||
text = prefix+HEADER+'\n'.join('| '+str(t)+' | '+str(v)+' | 12 | 3 | '+str(q)+' | 0 | '+status+' |' for t,v,q,status in rows)
|
||||
return parse(text.encode())
|
||||
|
||||
|
||||
class Cases(unittest.TestCase):
|
||||
def test_linear_positive_flow(self):
|
||||
d=diagnose(sample([(0,0,2,'V'),(1,50,2,'V'),(2,100,2,'Filled')]),C)
|
||||
self.assertEqual(d['linearity']['max_deviation_percentage_points'],0)
|
||||
self.assertTrue(d['flow']['whole_fill']['within_fixed_tolerance'])
|
||||
|
||||
def test_nonlinear_and_unflat(self):
|
||||
d=diagnose(sample([(0,0,1,'V'),(1,70,2,'V'),(2,100,3,'Filled')]),C)
|
||||
self.assertEqual(d['linearity']['max_deviation_percentage_points'],20)
|
||||
self.assertFalse(d['flow']['whole_fill']['within_fixed_tolerance'])
|
||||
|
||||
def test_rounded_zero_is_undefined(self):
|
||||
d=diagnose(sample([(0,0,0,'V'),(1,100,0,'Filled')]),C)
|
||||
self.assertFalse(d['flow']['whole_fill']['defined'])
|
||||
|
||||
def test_switch_from_row_not_setting(self):
|
||||
d=diagnose(sample([(0,0,1,'V'),(1,100,1,'Filled')], 'V/P setting = 99%\n'),C)
|
||||
self.assertEqual(d['observed_switch_rows'],[])
|
||||
d=diagnose(sample([(0,0,1,'V'),(1,98,1,'V/P'),(2,100,1,'Filled')]),C)
|
||||
self.assertEqual(d['observed_switch_rows'][0]['fill_percent'],98)
|
||||
|
||||
def test_time_weighting_and_equal_times(self):
|
||||
d=diagnose(sample([(0,0,1,'V'),(1,10,1,'V'),(1,20,3,'V'),(4,100,3,'Filled')]),C)
|
||||
self.assertEqual(d['flow']['whole_fill']['printed_flow_time_weighted_mean'],2.5)
|
||||
self.assertEqual(d['equal_printed_time_intervals'],1)
|
||||
|
||||
def test_nonmonotone_rejected(self):
|
||||
self.assertFalse(diagnose(sample([(0,0,1,'V'),(1,50,1,'V'),(2,40,1,'V')]),C)['quantitative_defined'])
|
||||
|
||||
def test_malformed_is_not_absent(self):
|
||||
p=parse((HEADER+'| 1 | BAD | 0 | 0 | 0 | 0 | V |').encode())
|
||||
self.assertTrue(p['table_present']);self.assertEqual(len(p['unsupported_rows']),1)
|
||||
self.assertEqual(diagnose(p,C)['status'],'TABLE_PRESENT_BUT_UNSUPPORTED_OR_INSUFFICIENT')
|
||||
|
||||
def test_stop_at_full_and_ignore_packing(self):
|
||||
p=sample([(0,0,1,'V'),(1,100,1,'Filled'),(2,99,1,'P')])
|
||||
self.assertEqual(diagnose(p,C)['filling_rows'],2)
|
||||
p=parse((HEADER+'| 0 | 0 | 0 | 0 | 1 | 0 | V |\nPack Analysis\n| 2 | 100 | 0 | 0 | 0 | 0 | P |').encode())
|
||||
self.assertEqual(len(p['rows']),1)
|
||||
|
||||
def test_missing_end_no_origin_supplement(self):
|
||||
d=diagnose(sample([(1,20,1,'V'),(2,80,1,'V')]),C)
|
||||
self.assertFalse(d['reached_printed_100_percent'])
|
||||
self.assertIsNone(d['linearity']['assumed_origin_supplement'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user