def create_table( row, # AtomsRow header, # List[str] keys, # List[str] key_descriptions, # Dict[str, Tuple[str, str, str]] digits=3 # int ): # -> Dict[str, Any] """Create table-dict from row.""" table = [] for key in keys: if key == 'age': age = float_to_time_string(now() - row.ctime, True) table.append(('Age', age)) continue value = row.get(key) if value is not None: if isinstance(value, float): value = '{:.{}f}'.format(value, digits) elif not isinstance(value, str): value = str(value) desc, unit = key_descriptions.get(key, ['', key, ''])[1:] if unit: value += ' ' + unit table.append((desc, value)) return {'type': 'table', 'header': header, 'rows': table}
def row2dct( row, key_descriptions: Dict[str, Tuple[str, str, str]] = {}) -> Dict[str, Any]: """Convert row to dict of things for printing or a web-page.""" from ase.db.core import float_to_time_string, now dct = {} atoms = Atoms(cell=row.cell, pbc=row.pbc) dct['size'] = kptdensity2monkhorstpack(atoms, kptdensity=1.8, even=False) dct['cell'] = [['{:.3f}'.format(a) for a in axis] for axis in row.cell] par = ['{:.3f}'.format(x) for x in cell_to_cellpar(row.cell)] dct['lengths'] = par[:3] dct['angles'] = par[3:] stress = row.get('stress') if stress is not None: dct['stress'] = ', '.join('{0:.3f}'.format(s) for s in stress) dct['formula'] = Formula(row.formula).format('abc') dipole = row.get('dipole') if dipole is not None: dct['dipole'] = ', '.join('{0:.3f}'.format(d) for d in dipole) data = row.get('data') if data: dct['data'] = ', '.join(data.keys()) constraints = row.get('constraints') if constraints: dct['constraints'] = ', '.join(c.__class__.__name__ for c in constraints) keys = ({'id', 'energy', 'fmax', 'smax', 'mass', 'age'} | set(key_descriptions) | set(row.key_value_pairs)) dct['table'] = [] for key in keys: if key == 'age': age = float_to_time_string(now() - row.ctime, True) dct['table'].append(('ctime', 'Age', age)) continue value = row.get(key) if value is not None: if isinstance(value, float): value = '{:.3f}'.format(value) elif not isinstance(value, str): value = str(value) desc, unit = key_descriptions.get(key, ['', '', ''])[1:] if unit: value += ' ' + unit dct['table'].append((key, desc, value)) return dct
def set_columns(self, columns): self.values = [] for c in columns: if c == 'age': value = float_to_time_string(now() - self.dct.ctime) elif c == 'pbc': value = ''.join('FT'[int(p)] for p in self.dct.pbc) else: value = getattr(self.dct, c, None) self.values.append(value)
def set_columns(self, columns): self.values = [] for c in columns: if c == 'age': value = float_to_time_string(now() - self.dct.ctime) elif c == 'pbc': value = ''.join('FT'[p] for p in self.dct.pbc) else: value = getattr(self.dct, c, None) self.values.append(value)
def age(self, d): return float_to_time_string(now() - d.ctime)
def __init__(self, dct, subscript=None): self.dct = dct self.cell = [['{0:.3f}'.format(a) for a in axis] for axis in dct.cell] forces = dict2forces(dct) if forces is None: fmax = None self.forces = None else: fmax = (forces**2).sum(1).max()**0.5 N = len(forces) self.forces = [] for n, f in enumerate(forces): if n < 5 or n >= N - 5: f = tuple('{0:10.3f}'.format(x) for x in f) symbol = chemical_symbols[dct.numbers[n]] self.forces.append((n, symbol) + f) elif n == 5: self.forces.append((' ...', '', ' ...', ' ...', ' ...')) self.stress = dct.get('stress') if self.stress is not None: self.stress = ', '.join('{0:.3f}'.format(s) for s in self.stress) if 'masses' in dct: mass = dct.masses.sum() else: mass = atomic_masses[dct.numbers].sum() formula = hill(dct.numbers) if subscript: formula = subscript.sub(r'<sub>\1</sub>', formula) table = [ ('id', dct.id), ('age', float_to_time_string(now() - dct.ctime, True)), ('formula', formula), ('user', dct.user), ('calculator', dct.get('calculator')), ('energy [eV]', dct.get('energy')), ('fmax [eV/Ang]', fmax), ('charge [|e|]', dct.get('charge')), ('mass [au]', mass), ('unique id', dct.unique_id), ('volume [Ang^3]', abs(np.linalg.det(dct.cell)))] self.table = [(name, value) for name, value in table if value is not None] if 'key_value_pairs' in dct: self.key_value_pairs = sorted(dct.key_value_pairs.items()) else: self.key_value_pairs = None if 'keywords' in dct: self.keywords = ', '.join(sorted(dct.keywords)) else: self.keywords = None self.dipole = dct.get('dipole') if self.dipole is not None: self.dipole = ', '.join('{0:.3f}'.format(d) for d in self.dipole) self.data = dct.get('data') if self.data: self.data = ', '.join(self.data.keys()) self.constraints = dct.get('constraints') if self.constraints: self.constraints = ', '.join(d['name'] for d in self.constraints)
def age(self, d): return float_to_time_string((time() - T0) / YEAR - d.timestamp)
def __init__(self, row, meta={}, subscript=None, prefix='', tmpdir='.'): self.row = row self.cell = [['{:.3f}'.format(a) for a in axis] for axis in row.cell] par = ['{:.3f}'.format(x) for x in cell_to_cellpar(row.cell)] self.lengths = par[:3] self.angles = par[3:] forces = row.get('constrained_forces') if forces is None: fmax = None self.forces = None else: fmax = (forces**2).sum(1).max()**0.5 N = len(forces) self.forces = [] for n, f in enumerate(forces): if n < 5 or n >= N - 5: f = tuple('{0:10.3f}'.format(x) for x in f) symbol = chemical_symbols[row.numbers[n]] self.forces.append((n, symbol) + f) elif n == 5: self.forces.append( (' ...', '', ' ...', ' ...', ' ...')) self.stress = row.get('stress') if self.stress is not None: self.stress = ', '.join('{0:.3f}'.format(s) for s in self.stress) if 'masses' in row: mass = row.masses.sum() else: mass = atomic_masses[row.numbers].sum() self.formula = formula_metal(row.numbers) if subscript: self.formula = subscript.sub(r'<sub>\1</sub>', self.formula) age = float_to_time_string(now() - row.ctime, True) table = dict( (key, value) for key, value in [('id', row.id), ('age', age), ('formula', self.formula), ('user', row.user), ('calculator', row.get('calculator')), ( 'energy', row.get('energy')), ('fmax', fmax), ('charge', row.get('charge')), ('mass', mass), ('magmom', row.get('magmom')), ( 'unique id', row.unique_id), ('volume', row.get('volume'))] if value is not None) table.update(row.key_value_pairs) for key, value in table.items(): if isinstance(value, float): table[key] = '{:.3f}'.format(value) kd = meta.get('key_descriptions', {}) misc = set(table.keys()) self.layout = [] for headline, columns in meta['layout']: empty = True newcolumns = [] for column in columns: newcolumn = [] for block in column: if block is None: pass elif isinstance(block, tuple): title, keys = block rows = [] for key in keys: value = table.get(key, None) if value is not None: if key in misc: misc.remove(key) desc, unit = kd.get(key, [0, key, ''])[1:] rows.append((desc, value, unit)) if rows: block = (title, rows) else: continue elif any(block.endswith(ext) for ext in ['.png', '.csv']): name = op.join(tmpdir, prefix + block) if not op.isfile(name): self.create_figures(row, prefix, tmpdir, meta['functions']) if op.getsize(name) == 0: # Skip empty files: block = None elif block.endswith('.csv'): block = read_csv_table(name) else: assert block in ['ATOMS', 'CELL', 'FORCES'], block newcolumn.append(block) if block is not None: empty = False newcolumns.append(newcolumn) if not empty: self.layout.append((headline, newcolumns)) if misc: rows = [] for key in sorted(misc): value = table[key] desc, unit = kd.get(key, [0, key, ''])[1:] rows.append((desc, value, unit)) self.layout.append(('Miscellaneous', [[('Items', rows)]])) self.dipole = row.get('dipole') if self.dipole is not None: self.dipole = ', '.join('{0:.3f}'.format(d) for d in self.dipole) self.data = row.get('data') if self.data: self.data = ', '.join(self.data.keys()) self.constraints = row.get('constraints') if self.constraints: self.constraints = ', '.join(d['name'] for d in self.constraints)
def __init__(self, dct, subscript=None): self.dct = dct self.cell = [['{0:.3f}'.format(a) for a in axis] for axis in dct.cell] forces = dict2forces(dct) if forces is None: fmax = None self.forces = None else: fmax = (forces**2).sum(1).max()**0.5 N = len(forces) self.forces = [] for n, f in enumerate(forces): if n < 5 or n >= N - 5: f = tuple('{0:10.3f}'.format(x) for x in f) symbol = chemical_symbols[dct.numbers[n]] self.forces.append((n, symbol) + f) elif n == 5: self.forces.append( (' ...', '', ' ...', ' ...', ' ...')) self.stress = dct.get('stress') if self.stress is not None: self.stress = ', '.join('{0:.3f}'.format(s) for s in self.stress) if 'masses' in dct: mass = dct.masses.sum() else: mass = atomic_masses[dct.numbers].sum() formula = hill(dct.numbers) if subscript: formula = subscript.sub(r'<sub>\1</sub>', formula) table = [('id', dct.id), ('age', float_to_time_string(now() - dct.ctime, True)), ('formula', formula), ('user', dct.user), ('calculator', dct.get('calculator')), ('energy [eV]', dct.get('energy')), ('fmax [eV/Ang]', fmax), ('charge [|e|]', dct.get('charge')), ('mass [au]', mass), ('unique id', dct.unique_id), ('volume [Ang^3]', abs(np.linalg.det(dct.cell)))] self.table = [(name, value) for name, value in table if value is not None] if 'key_value_pairs' in dct: self.key_value_pairs = sorted(dct.key_value_pairs.items()) else: self.key_value_pairs = None if 'keywords' in dct: self.keywords = ', '.join(sorted(dct.keywords)) else: self.keywords = None self.dipole = dct.get('dipole') if self.dipole is not None: self.dipole = ', '.join('{0:.3f}'.format(d) for d in self.dipole) self.data = dct.get('data') if self.data: self.data = ', '.join(self.data.keys()) self.constraints = dct.get('constraints') if self.constraints: self.constraints = ', '.join(d['name'] for d in self.constraints)
def __init__(self, row, subscript=None): self.row = row self.cell = [["{0:.3f}".format(a) for a in axis] for axis in row.cell] forces = row.get("constrained_forces") if forces is None: fmax = None self.forces = None else: fmax = (forces ** 2).sum(1).max() ** 0.5 N = len(forces) self.forces = [] for n, f in enumerate(forces): if n < 5 or n >= N - 5: f = tuple("{0:10.3f}".format(x) for x in f) symbol = chemical_symbols[row.numbers[n]] self.forces.append((n, symbol) + f) elif n == 5: self.forces.append((" ...", "", " ...", " ...", " ...")) self.stress = row.get("stress") if self.stress is not None: self.stress = ", ".join("{0:.3f}".format(s) for s in self.stress) if "masses" in row: mass = row.masses.sum() else: mass = atomic_masses[row.numbers].sum() formula = hill(row.numbers) if subscript: formula = subscript.sub(r"<sub>\1</sub>", formula) table = [ ("id", "", row.id), ("age", "", float_to_time_string(now() - row.ctime, True)), ("formula", "", formula), ("user", "", row.user), ("calculator", "", row.get("calculator")), ("energy", "eV", row.get("energy")), ("fmax", "eV/Ang", fmax), ("charge", "|e|", row.get("charge")), ("mass", "au", mass), ("magnetic moment", "au", row.get("magmom")), ("unique id", "", row.unique_id), ("volume", "Ang^3", row.get("volume")), ] self.table = [(name, unit, value) for name, unit, value in table if value is not None] self.key_value_pairs = sorted(row.key_value_pairs.items()) or None self.dipole = row.get("dipole") if self.dipole is not None: self.dipole = ", ".join("{0:.3f}".format(d) for d in self.dipole) self.plots = [] self.data = row.get("data") if self.data: plots = [] for name, value in self.data.items(): if isinstance(value, dict) and "xlabel" in value: plots.append((value.get("number"), name)) self.plots = [name for number, name in sorted(plots)] self.data = ", ".join(self.data.keys()) self.constraints = row.get("constraints") if self.constraints: self.constraints = ", ".join(d["name"] for d in self.constraints)