Skip to content

Commit

Permalink
Merge 7bdc3e1 into f7e0462
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasberbuer committed Jan 17, 2020
2 parents f7e0462 + 7bdc3e1 commit 7916b0e
Show file tree
Hide file tree
Showing 9 changed files with 35 additions and 37 deletions.
4 changes: 2 additions & 2 deletions examples/ex3_timepicker.py
Expand Up @@ -44,7 +44,7 @@ def plot(t, y, y_picker, index_picker, name_picker):
ax1.tick_params(axis="y", labelcolor="g")

ax2 = ax1.twinx()
ax2.set_ylabel("{:s}".format(name_picker), color="r")
ax2.set_ylabel(f"{name_picker}", color="r")
ax2.plot(t, y_picker, color="r")
ax2.tick_params(axis="y", labelcolor="r")

Expand Down Expand Up @@ -106,7 +106,7 @@ def timeit(callable, loops=100):
}

for name, time in timer_results.items():
print("{:s}: {:0.3f} µs".format(name, time))
print(f"{name}: {time:0.3f} µs")

plt.figure(figsize=(8, 3), tight_layout=True)
plt.bar(timer_results.keys(), timer_results.values())
Expand Down
4 changes: 2 additions & 2 deletions examples/ex4_location.py
Expand Up @@ -144,7 +144,7 @@ def main():
mutation=1.3,
)
end = time.perf_counter()
print("Runtime for 1 call to differential_evolution(): {:0.4} s".format(end - start))
print(f"Runtime for 1 call to differential_evolution(): {(end - start):0.4} s")
print(location_result)

# Plot location result
Expand All @@ -161,7 +161,7 @@ def main():

# Plot sensor positions
for channel, (x, y) in pos_dict.items():
text = "S{:d} (x={:0.2f}m | y={:0.2f}m)".format(channel, x, y)
text = f"S{channel} (x={x:0.2f}m | y={y:0.2f}m)"
plt.scatter(x, y, marker="o", color="w")
plt.text(x + text_delta_x, y + text_delta_y, text, fontsize=9, color="w")

Expand Down
2 changes: 1 addition & 1 deletion src/vallenae/io/__init__.py
Expand Up @@ -44,7 +44,7 @@
>>> pridb = vae.io.PriDatabase("./examples/steel_plate/sample.pridb")
>>> for hit in pridb.iread_hits():
... print("time: {:0.4f}, channel: {:d}".format(hit.time, hit.channel))
... print(f"time: {hit.time:0.4f}, channel: {hit.channel}")
...
time: 3.9928, channel: 3
time: 3.9928, channel: 2
Expand Down
30 changes: 15 additions & 15 deletions src/vallenae/io/_database.py
Expand Up @@ -37,14 +37,15 @@ def __init__(
file_ext = Path(self._filename).suffix[1:]
if file_ext.lower() != required_file_ext.lower():
raise ValueError(
"File extension '{:s}' must match '{:s}'".format(
file_ext, required_file_ext,
)
f"File extension '{file_ext}' must match '{required_file_ext}'"
)

self._connected: bool = False
self._connection = sqlite3.connect(
"file:{:s}?mode={:s}".format(self._filename, "ro" if readonly else "rw"),
"file:{filename}?mode={mode}".format(
filename=self._filename,
mode="ro" if readonly else "rw",
),
uri=True,
check_same_thread=(not readonly), # allow multithreading only for readonly access
)
Expand All @@ -61,14 +62,15 @@ def __init__(
)

self._table_prefix: str = table_prefix
self._table_main: str = "{:s}_data".format(table_prefix)
self._table_globalinfo: str = "{:s}_globalinfo".format(table_prefix)
self._table_params: str = "{:s}_params".format(table_prefix)
self._table_main: str = f"{table_prefix}_data"
self._table_fieldinfo: str = f"{table_prefix}_fieldinfo"
self._table_globalinfo: str = f"{table_prefix}_globalinfo"
self._table_params: str = f"{table_prefix}_params"

# check if main table (<prefix>_data) exists
if self._table_main not in self.tables():
raise ValueError(
"Main table '{:s}' does not exist in database".format(self._table_main)
f"Main table '{self._table_main}' does not exist in database"
)

@property
Expand Down Expand Up @@ -100,14 +102,14 @@ def connection(self) -> sqlite3.Connection:
def rows(self) -> int:
"""Number of rows in data table."""
con = self.connection()
cur = con.execute("SELECT COUNT(*) FROM {:s}".format(self._table_main))
cur = con.execute(f"SELECT COUNT(*) FROM {self._table_main}")
return cur.fetchone()[0]

def columns(self) -> Tuple[str, ...]:
"""Columns of data table."""
con = self.connection()
# empty dummy query
cur = con.execute("SELECT * FROM {:s} LIMIT 0".format(self._table_main))
cur = con.execute(f"SELECT * FROM {self._table_main} LIMIT 0")
return tuple(str(column[0]) for column in cur.description)

def tables(self) -> Set[str]:
Expand All @@ -125,7 +127,7 @@ def try_convert_string(value: str) -> Any:
except SyntaxError:
return str(value)
con = self.connection()
cur = con.execute("SELECT Key, Value FROM {:s}".format(self._table_globalinfo))
cur = con.execute(f"SELECT Key, Value FROM {self._table_globalinfo}")
return {
row[0]: try_convert_string(str(row[1])) for row in cur.fetchall()
}
Expand Down Expand Up @@ -156,7 +158,7 @@ def _parameter_table(self) -> Dict[int, Dict[str, Any]]:
def parameter_by_id():
for row in read_sql_generator(
self.connection(),
"SELECT * FROM {:s}".format(self._table_params),
f"SELECT * FROM {self._table_params}",
):
param_id = row.pop("ID")
yield (param_id, row)
Expand All @@ -168,9 +170,7 @@ def _parameter(self, param_id: int) -> Dict[str, Any]:
return self._parameter_table()[param_id]
except KeyError:
raise ValueError(
"Parameter ID {:d} not found in {:s}".format(
param_id, self._table_params
)
f"Parameter ID {param_id} not found in {self._table_params}"
)

def close(self):
Expand Down
16 changes: 7 additions & 9 deletions src/vallenae/io/_sql.py
Expand Up @@ -63,8 +63,8 @@ def query_conditions(
if value is None:
continue
if isinstance(value, str):
value = "'{:s}'".format(value) # add quotation marks
cond.append("{:s} {:s} {}".format(key, comp_operator, value))
value = f"'{value}'" # add quotation marks
cond.append(f"{key} {comp_operator} {value}")

return "WHERE " + " AND ".join(cond) if cond else ""

Expand Down Expand Up @@ -93,7 +93,7 @@ def read_sql_generator(


def count_sql_results(connection: sqlite3.Connection, query: str) -> int:
count_query = "SELECT COUNT(*) FROM ({:s})".format(query)
count_query = f"SELECT COUNT(*) FROM ({query})"
cur = connection.execute(count_query)
return cur.fetchone()[0]

Expand Down Expand Up @@ -122,17 +122,15 @@ def sql_binary_search(

def get_value(index):
cur = connection.execute(
"SELECT {:s} FROM {:s} WHERE {:s} == {:d}".format(
col_value, table, col_index, index
)
f"SELECT {col_value} FROM {table} WHERE {col_index} == {index}"
)
return cur.fetchone()[0]

i_min = connection.execute(
"SELECT MIN({:s}) FROM {:s}".format(col_index, table)
f"SELECT MIN({col_index}) FROM {table}"
).fetchone()[0]
i_max = connection.execute(
"SELECT MAX({:s}) FROM {:s}".format(col_index, table)
f"SELECT MAX({col_index}) FROM {table}"
).fetchone()[0]

while True:
Expand Down Expand Up @@ -162,7 +160,7 @@ def create_new_database(filename: str, schema: str):

# open database in read-write-create mode
with contextlib.closing(
sqlite3.connect("file:{:s}?mode=rwc".format(filename), uri=True)
sqlite3.connect(f"file:{filename}?mode=rwc", uri=True)
) as con:
con.executescript(schema)

Expand Down
6 changes: 3 additions & 3 deletions src/vallenae/io/pridb.py
Expand Up @@ -32,9 +32,9 @@ def wrapper(self: "PriDatabase", record: RecordType, *args, **kwargs):
max_time = get_max_time(self)
if record.time < max_time:
raise ValueError(
"Time column has to be monotonic increasing. \
Time of current / last row: {:0.2f} / {:0.2f} s".format(
record.time, max_time
(
f"Time column has to be monotonic increasing."
f"Time of current / last row: {record.time} / {max_time} s"
)
)
return func(self, record, *args, **kwargs)
Expand Down
6 changes: 3 additions & 3 deletions tests/data/gen_signal.py
Expand Up @@ -10,8 +10,8 @@
signal = 2 * np.random.rand(SAMPLES) - 1

with open(SIGNALFILE, "w") as f:
f.write("{:f}\n".format(DT_NS))
f.write("{:d}\n".format(SAMPLES))
f.write(f"{DT_NS:f}\n")
f.write(f"{SAMPLES:d}\n")

for value in signal:
f.write("{:f}\n".format(value))
f.write(f"{value:f}\n")
2 changes: 1 addition & 1 deletion tests/test_io_sql.py
Expand Up @@ -20,7 +20,7 @@ def fixture_memory_abc():
# add 10 rows of dummy data
for i in range(10):
con.execute(
"INSERT INTO abc (a, b, c) VALUES ({:d}, {:d}, {:d})".format(i, 10 + i, 20 + i)
f"INSERT INTO abc (a, b, c) VALUES ({i}, {10 + i}, {20 + i})"
)
yield con
con.close()
Expand Down
2 changes: 1 addition & 1 deletion tests/test_io_trfdb.py
Expand Up @@ -109,7 +109,7 @@ def test_write(fresh_trfdb):
def get_by_trai(trai):
gen = read_sql_generator(
fresh_trfdb.connection(),
"SELECT * FROM trf_data WHERE TRAI == {:d}".format(trai),
f"SELECT * FROM trf_data WHERE TRAI == {trai}",
)
return list(gen)[0]

Expand Down

0 comments on commit 7916b0e

Please sign in to comment.