-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodels.py
More file actions
636 lines (495 loc) · 21.1 KB
/
Copy pathmodels.py
File metadata and controls
636 lines (495 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
"""Pydantic models for the amorphouspy API.
Defines request/response schemas for the ``/jobs`` and ``/glasses`` endpoints.
"""
from enum import StrEnum
from io import StringIO
from typing import Annotated, Any, Literal, cast
from amorphouspy.potentials.potential import POTENTIAL_PREFERENCE
from ase import Atoms
from ase.io import read, write
from pydantic import (
AfterValidator,
BaseModel,
ConfigDict,
Discriminator,
Field,
PlainSerializer,
PlainValidator,
RootModel,
Tag,
WithJsonSchema,
)
from amorphouspy import DsfConfig, EwaldConfig, PppmConfig, WolfConfig
from amorphouspy_api.config import API_BASE_URL
# ---------------------------------------------------------------------------
# Composition
# ---------------------------------------------------------------------------
def _fmt_value(v: float) -> str:
rounded = round(v, 2)
if rounded == int(rounded):
return str(int(rounded))
return f"{rounded:g}"
class Composition(RootModel[dict[str, float]]):
"""Oxide glass composition (mol%).
Accepts and serialises as a plain ``dict[str, float]``.
Values represent mol% and will be rescaled to sum to 100% where needed.
Examples:
>>> c = Composition({"Na2O": 15, "SiO2": 70, "CaO": 15})
>>> c.canonical
'CaO 15 - Na2O 15 - SiO2 70'
"""
# Open WebUI / OpenAI function-calling requires all "object" schemas to
# include a "properties" key. RootModel[dict[...]] emits only
# additionalProperties; adding an empty properties object satisfies the
# validator without changing semantics.
model_config = ConfigDict(json_schema_extra={"properties": {}})
@property
def canonical(self) -> str:
"""Canonical string for DB storage and exact-match comparison.
Components sorted alphabetically; values rounded to 2 dp,
trailing zeros stripped.
"""
components = sorted(self.root.items())
return " - ".join(f"{oxide} {_fmt_value(val)}" for oxide, val in components)
@classmethod
def from_canonical(cls, canonical: str) -> "Composition":
"""Construct from a canonical DB string.
>>> Composition.from_canonical("CaO 15 - Na2O 15 - SiO2 70")
Composition({'CaO': 15.0, 'Na2O': 15.0, 'SiO2': 70.0})
"""
result: dict[str, float] = {}
for part in canonical.split(" - "):
token = part.strip()
if not token:
continue
oxide, value_str = token.rsplit(" ", 1)
result[oxide] = float(value_str)
return cls(result)
# ---------------------------------------------------------------------------
# ASE Atoms serialisation helpers (used by database & visualization)
# ---------------------------------------------------------------------------
def serialize_atoms(atoms: Atoms) -> str:
"""Serialize ASE Atoms to JSON string."""
buf = StringIO()
write(buf, atoms, format="json")
return buf.getvalue()
def validate_atoms(v: Atoms | dict | str | None) -> Atoms | None:
"""Validate and convert input to ASE Atoms object."""
if v is None:
return None
if isinstance(v, Atoms):
return v
if isinstance(v, dict):
try:
return Atoms(**v)
except Exception as e:
msg = f"Could not reconstruct Atoms from dict: {e}"
raise ValueError(msg) from e
if isinstance(v, str):
try:
result = read(StringIO(v), format="json")
if isinstance(result, list):
return cast("Atoms", result[-1])
return result
except Exception as e:
msg = f"Could not parse Atoms from string: {e}"
raise ValueError(msg) from e
msg = f"Expected ASE Atoms, dict, str, or None — got {type(v)}"
raise TypeError(msg)
AtomsType = Annotated[
Atoms | None,
PlainValidator(validate_atoms),
PlainSerializer(serialize_atoms, return_type=str, when_used="unless-none"),
]
# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------
def validate_potential(value: str) -> str:
"""Validate that *value* is one of the registered core potentials."""
if value not in POTENTIAL_PREFERENCE:
msg = f"Unsupported potential: {value}"
raise ValueError(msg)
return value
type Potential = Annotated[
str,
AfterValidator(validate_potential),
WithJsonSchema({"type": "string", "enum": list(POTENTIAL_PREFERENCE), "title": "Potential"}),
]
class LongRangeMethod(StrEnum):
"""Coulomb solver method."""
dsf = "dsf"
wolf = "wolf"
pppm = "pppm"
ewald = "ewald"
class StepStatus(StrEnum):
"""Status of an individual pipeline step."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
class JobStatus(StrEnum):
"""Overall status of a simulation job."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
# ---------------------------------------------------------------------------
# Analysis configurations (discriminated union)
# ---------------------------------------------------------------------------
class StructureAnalysis(BaseModel):
"""Configuration for structural analysis (RDF, coordination, bond angles)."""
type: Literal["structure_characterization"] = "structure_characterization"
rdf_cutoff: float = Field(default=8.0, description="RDF cutoff in Å")
bin_width: float = Field(default=0.02, description="RDF bin width in Å")
class ViscosityAnalysis(BaseModel):
"""Configuration for viscosity analysis (Green-Kubo).
Viscosity is computed by running additional MD production runs at each
requested temperature. The melt-quench structure is sequentially cooled
from high to low temperature, and at each step a Green-Kubo viscosity
calculation is performed.
"""
type: Literal["viscosity"] = "viscosity"
temperatures: list[float] = Field(default=[1500, 2000, 2500], description="Simulation temperatures in K")
timestep: float = Field(default=1.0, description="MD timestep in fs for the viscosity production run")
n_timesteps: int = Field(
default=10_000_000,
description="MD steps per production run",
)
n_print: int = Field(default=1, description="Output frequency in steps")
max_lag: int | None = Field(
default=1_000_000,
description="Maximum correlation lag (steps) for Green-Kubo post-processing; None uses full trajectory",
)
class ElasticAnalysis(BaseModel):
"""Configuration for elastic moduli analysis (stress-strain finite differences).
Calculates the full Cij stiffness tensor via central differences and
derives isotropic moduli (B, G, E, nu) using Voigt-Reuss-Hill averaging.
"""
type: Literal["elastic"] = "elastic"
temperature: float = Field(default=300.0, description="Simulation temperature in K")
pressure: float | None = Field(default=None, description="Pressure in GPa; None = NVT")
timestep: float = Field(default=1.0, description="MD timestep in fs")
equilibration_steps: int = Field(default=1_000_000, description="Equilibration MD steps")
production_steps: int = Field(default=10_000, description="Production MD steps per strain direction")
n_print: int = Field(default=1, description="Thermodynamic output frequency")
strain: float = Field(default=1e-3, description="Strain magnitude for finite differences")
class _CTEBase(BaseModel):
"""Shared CTE simulation parameters."""
type: Literal["cte"] = "cte"
pressure: float = Field(default=1e-4, description="Pressure in GPa (default ≈ 1 bar)")
timestep: float = Field(default=1.0, description="MD timestep in fs")
equilibration_steps: int = Field(default=100_000, description="Equilibration steps")
production_steps: int = Field(default=200_000, description="Production steps per run")
class CTEFluctuations(_CTEBase):
"""CTE via enthalpy-volume fluctuations at a single temperature.
Iteratively runs production MD until convergence criteria are met,
returning CTE values with uncertainty estimates.
"""
method: Literal["fluctuations"] = "fluctuations"
temperature: float = Field(default=300.0, description="Simulation temperature in K")
min_production_runs: int = Field(
default=2,
description="Minimum production runs before convergence check",
)
max_production_runs: int = Field(
default=25,
description="Maximum production runs",
)
cte_uncertainty_criterion: float = Field(
default=1e-6,
description="Convergence criterion for linear CTE uncertainty in 1/K",
)
class CTETemperatureScan(_CTEBase):
"""CTE via NPT production runs at multiple temperatures.
Returns raw volume / box-length data at each temperature for
user-side CTE fitting (e.g. linear or polynomial V-T fit).
"""
method: Literal["temperature_scan"] = "temperature_scan"
temperatures: list[float] = Field(
default=[300, 400, 500, 600],
description="Temperatures in K",
)
CTEAnalysis = Annotated[
CTEFluctuations | CTETemperatureScan,
Field(discriminator="method"),
]
def _analysis_tag(v: dict[str, Any] | BaseModel) -> str:
"""Return a unique tag for each Analysis variant.
Most types are identified by their ``type`` field alone. CTE variants
share ``type="cte"`` and are further distinguished by ``method``.
"""
if isinstance(v, dict):
t = str(v.get("type", ""))
if t == "cte":
return f"cte_{v.get('method', 'fluctuations')}"
return t
t = getattr(v, "type", "")
if t == "cte":
return f"cte_{getattr(v, 'method', 'fluctuations')}"
return t
Analysis = Annotated[
Annotated[StructureAnalysis, Tag("structure_characterization")]
| Annotated[ViscosityAnalysis, Tag("viscosity")]
| Annotated[ElasticAnalysis, Tag("elastic")]
| Annotated[CTEFluctuations, Tag("cte_fluctuations")]
| Annotated[CTETemperatureScan, Tag("cte_temperature_scan")],
Discriminator(_analysis_tag),
]
# ---------------------------------------------------------------------------
# Viscosity result data (stored inside result_data["viscosity"])
# ---------------------------------------------------------------------------
class ViscosityResultData(BaseModel):
"""Result of a multi-temperature viscosity analysis."""
temperatures: list[float] = Field(..., description="Simulation temperatures (K)")
viscosities: list[float] = Field(..., description="Viscosities at each temperature (Pa·s)")
max_lag: list[float] = Field(..., description="Max cutoff correlation time per temperature (ps)")
simulation_steps: list[int] = Field(..., description="MD steps per temperature")
lag_times_ps: list[list[float]] = Field(
default_factory=list, description="Downsampled lag time arrays per temperature (ps)"
)
viscosity_integral: list[list[float]] = Field(
default_factory=list,
description="Cumulative viscosity integral per temperature (Pa·s)",
)
# ---------------------------------------------------------------------------
# Simulation parameters
# ---------------------------------------------------------------------------
class MeltQuenchParams(BaseModel):
"""Parameters for the melt-quench MD simulation."""
melt_temperature: float | None = Field(
default=None,
description="Melt temperature in K; None = protocol default",
)
quench_rate: float = Field(default=1e12, description="Quench rate in K/s")
n_atoms: int = Field(default=6000, description="Number of atoms")
timestep: float = Field(default=1.0, description="MD timestep in fs")
equilibration_steps: int | None = Field(
default=None,
description="Equilibration steps override; None = protocol default",
)
target_density: float | None = Field(
default=None,
description="Target density in g/cm³ for initial structure generation. If None, estimated from Fluegel's empirical model.",
)
structure_seed: int = Field(
default=42,
ge=0,
le=2**32 - 1,
description="Random seed for initial structure generation",
)
# ---------------------------------------------------------------------------
# Electrostatics settings
# ---------------------------------------------------------------------------
class ElectrostaticsParams(BaseModel):
"""Coulomb solver and cutoff settings for LAMMPS potentials."""
method: LongRangeMethod = Field(default=LongRangeMethod.dsf, description="Coulomb solver")
long_range_cutoff: float | None = Field(default=None, description="Coulomb cutoff in Å")
alpha: float | None = Field(default=None, description="Damping parameter (Å⁻¹) for DSF/Wolf")
kspace_accuracy: float = Field(default=1e-5, description="Relative accuracy for PPPM/Ewald")
def to_electrostatics_config(self):
"""Convert to the appropriate ``InteractionConfig`` subclass for the core library."""
return {
LongRangeMethod.dsf: lambda: DsfConfig(long_range_cutoff=self.long_range_cutoff, alpha=self.alpha),
LongRangeMethod.wolf: lambda: WolfConfig(long_range_cutoff=self.long_range_cutoff, alpha=self.alpha),
LongRangeMethod.pppm: lambda: PppmConfig(
long_range_cutoff=self.long_range_cutoff, kspace_accuracy=self.kspace_accuracy
),
LongRangeMethod.ewald: lambda: EwaldConfig(
long_range_cutoff=self.long_range_cutoff, kspace_accuracy=self.kspace_accuracy
),
}[self.method]()
# ---------------------------------------------------------------------------
# Job submission / response
# ---------------------------------------------------------------------------
class JobSubmission(BaseModel):
"""Request body for ``POST /jobs``."""
composition: Composition = Field(
...,
description="Oxide glass composition as {oxide: mol%}, rescaled to 100%",
)
potential: Potential = Field(default="pmmcs")
simulation: MeltQuenchParams = Field(default_factory=MeltQuenchParams)
analyses: list[Analysis] = Field( # type: ignore[ty:invalid-assignment]
default_factory=lambda: [StructureAnalysis(), ViscosityAnalysis(), CTEFluctuations(), ElasticAnalysis()],
description="Analyses to run; defaults to all available",
)
electrostatics: ElectrostaticsParams = Field(
default_factory=ElectrostaticsParams,
description="Coulomb solver and cutoff settings. Defaults to DSF with potential-specific parameters.",
)
tags: list[str] = Field(
default_factory=list,
description=("User-defined tags for labelling or grouping jobs (e.g. project names, batch identifiers)."),
)
def _job_urls(job_id: str) -> dict[str, str]:
"""Build user-facing URLs for a job.
Uses the ``API_BASE_URL`` environment variable. When unset the URLs
will contain relative paths only (empty base).
"""
base = API_BASE_URL.rstrip("/")
return {
"status": f"{base}/jobs/{job_id}",
"results": f"{base}/jobs/{job_id}/results",
"visualization": f"{base}/jobs/{job_id}/visualize",
"structure": f"{base}/jobs/{job_id}/structure",
}
class JobCreatedResponse(BaseModel):
"""Response for ``POST /jobs``."""
id: str = Field(..., description="Job identifier")
status: JobStatus = Field(default=JobStatus.PENDING)
composition: Composition
potential: Potential
tags: list[str] = Field(default_factory=list)
created_at: str
errors: dict[str, str] = Field(
default_factory=dict,
description="Non-empty when the job has recorded errors; maps step/category to error message.",
)
urls: dict[str, str] = Field(
default_factory=dict,
description=(
"Useful URLs for this job: 'status' to poll progress, "
"'results' for analysis data, 'visualization' for an interactive "
"HTML dashboard, 'structure' to download the quenched structure."
),
)
class JobProgress(BaseModel):
"""Per-step progress for ``GET /jobs/{id}``."""
structure_generation: StepStatus = StepStatus.PENDING
melt_quench: StepStatus = StepStatus.PENDING
analyses: dict[str, StepStatus] = Field(
default_factory=dict,
description="Progress of each analysis (structure_characterization, viscosity, cte, elastic, …)",
)
class JobStatusResponse(BaseModel):
"""Response for ``GET /jobs/{id}``."""
id: str
status: JobStatus
composition: Composition
potential: Potential
tags: list[str] = Field(default_factory=list)
progress: JobProgress
errors: dict[str, str] = Field(default_factory=dict)
created_at: str
completed_at: str | None = None
urls: dict[str, str] = Field(
default_factory=dict,
description=(
"Useful URLs for this job: 'status' to poll progress, "
"'results' for analysis data, 'visualization' for an interactive "
"HTML dashboard, 'structure' to download the quenched structure."
),
)
class JobResultsResponse(BaseModel):
"""Response for ``GET /jobs/{id}/results``."""
job_id: str
composition: Composition
analyses: dict[str, dict] = Field(
default_factory=dict,
description="Results keyed by analysis type (structure_characterization, viscosity, cte, elastic, …)",
)
visualization_url: str = Field(
default="",
description="URL for an interactive HTML visualization dashboard of these results.",
)
class JobSearchRequest(BaseModel):
"""Request body for ``POST /jobs:search``."""
composition: Composition = Field(
...,
description=(
"Oxide glass composition as a mapping of oxide formula to mol%. "
"Values are rescaled to sum to 100%. "
"Example: {'SiO2': 70, 'Na2O': 15, 'CaO': 15}"
),
)
potential: Potential | None = None
analyses: list[str] | None = None
tags: list[str] | None = Field(
default=None,
description="Filter to jobs with all specified tags",
)
threshold: float = Field(
default=0.05,
description="Max distance in atom-fraction space; 0 = exact only",
)
max_results: int = Field(
default=10,
ge=1,
le=100,
description="Max close matches to return",
)
class JobSearchMatch(BaseModel):
"""A single match from a job search."""
job_id: str
composition: Composition
potential: Potential
tags: list[str] = Field(default_factory=list)
analyses: list[str]
similarity: float = 1.0
match_type: str = Field(
default="exact",
description="'exact' for identical composition, 'close' for nearby.",
)
distance: float = Field(
default=0.0,
description="Euclidean distance in elemental atom-fraction space (0 for exact matches).",
)
completed_at: str | None = None
visualization_url: str = Field(
default="",
description="URL for an interactive HTML visualization dashboard of this job's results.",
)
class JobSearchResponse(BaseModel):
"""Response for ``POST /jobs:search``."""
matches: list[JobSearchMatch]
class TagsUpdate(BaseModel):
"""Request body for ``PUT /jobs/{id}/tags``."""
tags: list[str] = Field(
...,
description="New set of tags for the job (replaces existing tags).",
)
class TagsResponse(BaseModel):
"""Response for tag operations on a job."""
job_id: str
tags: list[str]
# ---------------------------------------------------------------------------
# Glasses (materials) layer
# ---------------------------------------------------------------------------
class GlassSummary(BaseModel):
"""Summary entry for one glass composition."""
composition: Composition
n_jobs: int
class GlassListResponse(BaseModel):
"""Response for ``GET /glasses``."""
glasses: list[GlassSummary]
class GlassPropertySource(BaseModel):
"""Provenance info linking a property back to its source job."""
source_job: str
potential: Potential
computed_at: str | None = None
class AvailableStructure(BaseModel):
"""A quenched structure available for download."""
job_id: str
potential: Potential
n_atoms: int
visualization_url: str = Field(
default="",
description="URL for an interactive HTML visualization dashboard of this job's results.",
)
class GlassLookupRequest(BaseModel):
"""Request body for ``POST /glasses:lookup``."""
composition: Composition = Field(
...,
description=(
"Oxide glass composition as a mapping of oxide formula to mol%. "
"Example: {'SiO2': 70, 'Na2O': 15, 'CaO': 15}"
),
)
class GlassPropertiesResponse(BaseModel):
"""Aggregated properties for ``POST /glasses:lookup``."""
composition: Composition
properties: dict[str, dict] = Field(default_factory=dict)
available_structures: list[AvailableStructure] = Field(default_factory=list)
missing: list[str] = Field(default_factory=list)