The Python API¶
Everything import samplekit offers, read from the package itself: its
docstrings are the source of this page. Examples use import samplekit as sk.
Loading and saving¶
load reads samples from files and folders, as the command line does, the
project's model applied. A Sample is one file; a SampleList is several,
and filters, sorts and tabulates them. keep records what a script saved as
one snapshot of the project's history.
- samplekit.load(*paths)¶
Read samples as the command line reads its targets.
A folder is read as a
SampleListof its samples, as its project declares them, and a file as oneSample; each is read with its project's model. Several paths are oneSampleList, in the order given, each sample once.- Parameters:
*paths -- Folders and sample files.
- Returns:
A
Samplefor one file, otherwise aSampleList.- Raises:
FileNotFoundError -- A path does not exist; the message names the nearest.
ValueError -- A file is not a sample.
Example
>>> specimens = sk.load("samples") >>> steel = sk.load("samples/steel-01.md") >>> steel.area Property(value=25.05586444444445, uncertainty=0.05217296159913354, unit='mm²')
- class samplekit.Sample(*args, **kwargs)¶
One sample, read from and saved to a Markdown file.
Sample(path)reads the file with the model its project declares;Sample(name=...)makes a sample with no file, whichsave(path)gives one. A model is a subclass ofSamplewhose__init__declares its properties and tables, and passespathon tosuper().__init__.A property, a table or an attribute is read as an attribute or an item,
steel.areaorsteel["area"], and any other field path as an item:steel["curve.force[0.2]"]is that cell's value. What is assigned decides what a name becomes: aPropertyor aTableis one; abool,int,float,str,date,datetime, or a list of one of them, is an attribute; and a name with a leading_is ordinary Python state, never saved. Nothing assigned without a leading ``_`` is lost on save: it is saved, or refused.- Parameters:
path -- The sample's file.
name -- The sample's name; a name the file holds wins over it.
model -- The class to read the file with, or
Falseto read the data alone. By default, the class the project's[model]declares.
- Raises:
FileNotFoundError -- The file does not exist; the message names the nearest.
Sample.newmakes a sample for a new file.IsADirectoryError -- The path is a folder:
sk.loadreads a folder.ValueError -- The file is not a sample.
AttributeError -- An unknown field, read as an attribute; the message names the nearest.
KeyError -- An unknown field, read as an item.
TypeError -- A value of a kind that cannot be saved; a leading
_keeps it in Python only.
Example
>>> steel = sk.Sample("samples/steel-01.md") >>> steel.material 'steel' >>> steel["curve.force[0.2]"] 9.516
- classmethod new(path, name=None, model=None)¶
Make a new sample for a file that does not exist yet.
The sample is of the model the project of that folder declares — or of this class, when called on a model — and is named by the file, which writes no
name:unlessnameis given.save()writes the file.- Parameters:
path -- The file to create.
name -- The sample's name, instead of the file's.
model -- The class to make it with, or
Falsefor a plainSample.
- Returns:
The new sample, not saved yet.
- Raises:
FileExistsError -- The file exists already:
Sample(path)reads it.FileNotFoundError -- The folder does not exist.
Example
>>> specimen = sk.Sample.new("samples/steel-02.md") >>> specimen.material = "steel" >>> specimen.save()
- affected_by_change(input)¶
Every value a change to this one would make outdated, directly or through other values.
- Parameters:
input -- A property's name, or
table.column.- Returns:
Their names, sorted.
- Raises:
KeyError -- An unknown name; the message names the nearest.
Example
>>> steel.affected_by_change("thickness") ['area', 'curve.stress', 'tensile_strength', 'yield_strength', 'young_modulus']
- compute(*names, rerun=False, force=False)¶
Compute the sample's values that are not current, in dependency order.
Without names, every value a formula gives is considered; only those outdated or never computed run. A value whose inputs nobody entered waits, with a warning saying for what, and a formula that raises is recorded as failed while the others run. The file is not written:
save()does that.- Parameters:
*names -- The values to compute: properties,
table.column, or a table's name for all its computed columns. Their inputs run first when needed.rerun -- Run them even when they are current.
force -- Run them even when they are edited, giving them back to their formula.
- Raises:
KeyError -- An unknown name; the message names the nearest.
ValueError -- A named value has no formula.
Exception -- The first formula that raised, with a note naming the value and the others that failed.
Example
>>> steel.compute() >>> steel.save()
- dependencies(output)¶
What a value's formula is declared to read.
- Parameters:
output -- A property's name, or
table.column.- Returns:
The input names, sorted.
- Raises:
KeyError -- An unknown name; the message names the nearest.
Example
>>> steel.dependencies("area") ['thickness', 'width']
- dependents(input)¶
The values whose formula reads this one directly.
- Parameters:
input -- A property's name, or
table.column.- Returns:
Their names, sorted.
- Raises:
KeyError -- An unknown name; the message names the nearest.
- edited()¶
The edited values — those typed over their formula.
- Returns:
The names of the edited properties, and
table.columnfor a column with an edited cell.
- filename¶
The name of the sample's file, without its folder, or
None.
- files(pattern=None)¶
The sample's own files: images, reports, anything found by the sample's name in the folders
[collection] filesdeclares.- Parameters:
pattern -- A glob on the files' names, such as
"*.png".- Returns:
The files' paths.
- Raises:
ValueError -- The sample has no file, or belongs to no project.
- items()¶
Each name with its attribute, property or table, in the order they were declared.
- keys()¶
The names of the sample's attributes, properties and tables, in the order they were declared.
- linked(field)¶
The sample an attribute links to, read as
sk.loadreads it, or the file it leads to.A link is an attribute written
"[[NAME]]", as Obsidian writes one: the sample of the project whose file is NAME.md, else whosenameis NAME; or a Markdown link to a file,"[the second](NAME.md)", its path read from this sample's folder. A sample's file gives the sample; any other file its path. A list of links gives a list, in order.- Parameters:
field -- The attribute holding the link, or the links.
- Returns:
The sample it names, or a
pathlib.Pathfor a file that is no sample; for a list, a list of them, in order.- Raises:
KeyError -- The sample holds no such attribute.
ValueError -- The attribute is no link: text, or a web address; or several samples answer to it.
FileNotFoundError -- No sample answers to it, or nothing is at its path.
Example
>>> steel.linked("reference").name 'aluminium-01'
- name¶
The sample's name, or
None.
- not_current()¶
Every value that is not current, and why: what
samplekit statusreports.outdated()andedited()answer one question each; this one also sees values that failed, were never computed, or wait for an input.- Returns:
"outdated","formula changed","edited","failed","never computed"or"waits for notch".- Return type:
A dict from each name — a property, or
table.column— to a reason
Example
>>> steel.not_current() {}
- note¶
The note — the Markdown text below the frontmatter, kept as written.
- open(pattern=None, navigate=False, many=False)¶
Open the sample's own files with the system's application.
- Parameters:
pattern -- A glob on the files' names, such as
"*.pdf".navigate -- Open the folders holding the files, in the file manager, instead of the files.
many -- Allow opening more than five.
- Returns:
The paths opened.
- Raises:
FileNotFoundError -- No file of the sample matches.
ValueError -- More than five would open and
manyis false.RuntimeError -- Over SSH without a display —
DISPLAYandWAYLAND_DISPLAYunset — there is nothing to open them on. Elsewhere the system's opener is started, and what it does without a display is its own.
- outdated()¶
The outdated values — those an input changed under since they were computed.
- Returns:
The names of the outdated properties, and
table.columnfor a column with an outdated cell.
- path¶
The file the sample was read from or last saved to, or
Nonefor a sample never saved.save(path)changes it.
- project¶
The project the sample's file belongs to — what its
.samplekitrcdeclares.
- remove()¶
Delete the sample's file.
The project's history keeps it, and
samplekit FILE restore --writegives it back; the sample's own files, under[collection] files, stay. The sample keeps its values:save()writes it again.- Raises:
ValueError -- The sample has no file, or the script runs under
samplekit run, whose preview cannot hold a removal.FileNotFoundError -- Its file was removed or moved since it was read.
OSError -- The file changed on disk since it was read.
Example
>>> sk.Sample("samples/steel-01.md").remove()
- rename(new)¶
Rename the sample: its file, its own files, and every link of its project leading to it.
The file becomes
NEW.mdbeside the old one, its own files under[collection] filesrenamed with it, itsnametoo where it was the file's name; each link of the project that led to it,[[OLD]]or[text](OLD.md), is written to lead to it again. The history keeps the samples; renamed back, the files and the links go back too.- Parameters:
new -- The new name: the file's, without its folder or
.md.- Returns:
The sample's new path.
- Raises:
ValueError -- The sample has no file, the name is no file's name, or the script runs under
samplekit run, whose preview cannot hold a rename.FileExistsError -- Another sample, or one of its files, has the name.
OSError -- The file changed on disk since it was read.
Example
>>> sk.Sample("samples/steel-01.md").rename("steel-04") PosixPath('samples/steel-04.md')
- save(path=None, overwrite=False)¶
Write the sample to its file.
Nothing is overwritten unless asked: a file changed on disk since it was read, or an existing file at a new path, is refused. Saving runs no formula: a value never computed is written without a value.
- Parameters:
path -- Where to write it instead. The sample then belongs to that file: a later
save()writes there.overwrite -- Write even over a file changed since it was read, or over an existing file at
path.
- Raises:
ValueError -- The sample has no file yet and no
pathis given. Also: another process is saving the same file at this moment.FileExistsError --
pathexists already.FileNotFoundError -- The folder does not exist, or the sample's file was removed or moved since it was read.
IsADirectoryError --
pathis a folder.OSError -- The file changed on disk since it was read.
PermissionError -- The file is read-only.
Example
>>> steel.grade = "S275" >>> steel.save()
- set_dependencies(output, *, depends_on)¶
Declare what a formula reads.
A change to one of the inputs makes the value outdated, and a computation runs the inputs first. A later declaration replaces an earlier one.
- Parameters:
output -- The value the formula gives: a property's name, or
table.column.depends_on -- What it reads: a list of names, or
{"v": [...], "u": [...]}where the value and the uncertainty have a formula each.[]says it reads nothing of the sample.
- Raises:
KeyError -- An unknown name, once the model is built.
ValueError -- The declaration makes a cycle, or names a channel with no formula.
Example
>>> class Specimen(sk.Sample): ... def __init__(self, path=None, name=None): ... super().__init__(path, name=name) ... self.area = sk.Property(unit="mm²", compute_value=self._area) ... self.set_dependencies("area", depends_on=["width", "thickness"]) ... ... def _area(self): ... return self.width.value * self.thickness.value
- tags¶
The sample's tags, as a list whose changes are saved with the sample.
Each tag is an identifier, and none appears twice.
- to_text(style=None)¶
The sample as
samplekit viewshows it — its values, then its tables — each value in a style's forms.- Parameters:
style -- A style's name:
"plain", one SampleKit gives, or one.samplekitrcdeclares. Without it,[render] style's.- Returns:
The text.
- Raises:
ValueError -- No style has that name.
Example
>>> print(steel.to_text())
- class samplekit.SampleList(source=None, pattern=None, model=None)¶
An ordered list of samples, read like a Python list.
A list is read from a folder, or built from samples already read. An item is a sample, by position or by name —
specimens["steel-01"]— and a slice is a list. Lists join with+.filter,query,sortedandgroup_bymake new lists; the samples in them are the same objects.- Parameters:
source -- A folder, whose samples are read as the project declares, or an iterable of samples.
pattern -- A glob choosing the folder's files, instead of what
[collection]declares.model -- The model class to read the samples with, or
Falseto read the data alone. By default, the project's model.
- Raises:
TypeError -- The iterable holds something other than samples, such as paths:
sk.loadreads paths.ValueError -- A sample appears twice, or
patternormodelis given without a folder.FileNotFoundError -- The folder does not exist.
Example
>>> specimens = sk.SampleList("samples") >>> len(specimens) 3 >>> specimens["steel-01"].material 'steel'
- compute(*names, rerun=False, force=False)¶
Compute every sample of the list, as
Sample.computedoes.Every sample is computed even when one fails; the failures are raised at the end. A
KeyboardInterruptstops at once.- Parameters:
*names -- The values to compute; every value that is not current by default.
rerun -- Run them even when they are current.
force -- Run them even when they are edited.
- Raises:
Exception -- The one failure, with a note naming the sample and the value.
ExceptionGroup -- Several failures, in the order they happened.
- count(value)¶
How many times a sample is in the list: 0 or 1 for a sample, and, for a name, the number of samples of that name.
- export(export, output=None, overwrite=False)¶
Write an export declared in
.samplekitrc, assamplekit export --writedoes.The export's own query, if it declares one, narrows the list first. An export of a figure draws it as
sk.plotdoes, to its file.- Parameters:
export -- The export's name, or an
Export.output -- Write here instead of the declared file.
overwrite -- Replace an existing file.
- Returns:
The path written, absolute.
- Raises:
KeyError -- No export has that name, or its profile or figure is not declared.
FileExistsError -- The file exists and
overwriteis false.ValueError --
output's extension does not match the export's format.
Example
>>> specimens.export("paper", output="paper/results.tex").name 'results.tex'
- fields¶
Every field the samples of the list can be addressed by, as
samplekit list fieldslists them.
- filter(predicate)¶
The samples an expression selects, as
-fselects them.- Parameters:
predicate -- A filter expression —
"elongation > 20 && material == steel"— or a function taking a sample and returning whether to keep it.- Returns:
A new list, in this list's order.
- Raises:
KeyError -- The expression names an unknown field; the message names the nearest.
ValueError -- The expression does not parse, or names a tag no sample carries.
TypeError -- The expression compares a field in a way its values do not allow.
Example
>>> [specimen.name for specimen in specimens.filter("tensile_strength > 300")] ['aluminium-01', 'steel-01']
- group_by(fields)¶
Split the list into groups by the values of fields, as
--groupdoes.- Parameters:
fields -- A field, or several — a list, or comma-separated as
--groupwrites them.- Returns:
A dict from each value — a tuple of values for several fields — to the list of samples holding it. The groups come in the order their values sort; for a sorted list, in the order of their first samples.
- Raises:
KeyError -- An unknown field; the message names the nearest.
ValueError -- The field is a whole table.
RuntimeError -- The field is
state, which a sample holds several of.
Example
>>> list(specimens.group_by("material")) ['aluminium', 'copper', 'steel']
- index(value, start=0, stop=None)¶
The position of a sample in the list.
- Parameters:
value -- A sample, or a sample's name.
start -- Where to start looking.
stop -- Where to stop looking.
- Raises:
ValueError -- It is not in the list.
- project¶
The project of the list's samples — what their
.samplekitrcdeclares.- Raises:
ValueError -- The samples belong to several projects.
- query(name)¶
The samples a saved query selects, as
-Qselects them.- Parameters:
name -- The query's name in
.samplekitrc, or aQuery.- Returns:
A new list, in this list's order.
- Raises:
KeyError -- No query has that name; the message names the nearest.
ValueError -- The list spans several projects that declare it differently.
Example
>>> len(specimens.query("ductile")) 2
- save_all(directory=None, overwrite=False)¶
Write every sample of the list: back where each was read, or into a folder.
Without a folder, each sample is written to its own file, as
save()writes it: a file changed since it was read — by another object, or an editor — is refused rather than written over. Into a folder, each is written under its file's name, or its name, and nothing is written if any file is refused.- Parameters:
directory -- The folder, which must exist; each sample's own file when left out.
overwrite -- Replace existing files in the folder.
- Returns:
The paths written.
- Raises:
FileNotFoundError -- The folder does not exist.
NotADirectoryError -- It is a file.
FileExistsError -- A file exists and
overwriteis false.ValueError -- Two samples would be written to the same file, or, without a folder, a sample has no file of its own.
OSError -- Without a folder, a file changed on disk since it was read.
- sort(key)¶
Sort the list in place, and return
None.- Parameters:
key -- A field —
"area", or"-area"for descending — several in a list or comma-separated, or a function of a sample assortedtakes one.- Raises:
KeyError -- An unknown field; the message names the nearest.
TypeError -- A sort by
state, which a sample holds several of.
- sorted(key)¶
A new list in sorted order; this one is unchanged.
- Parameters:
key -- A field —
"area", or"-area"for descending — several in a list or comma-separated, or a function of a sample assortedtakes one.- Returns:
A new list.
- Raises:
KeyError -- An unknown field; the message names the nearest.
TypeError -- A sort by
state, which a sample holds several of.
Example
>>> specimens.sorted("-tensile_strength")[0].name 'steel-01'
- stats(field)¶
The statistics of one field over the list, as
--summarygives them.- Parameters:
field -- A field:
"area","area.u","curve.force[0.2]".- Returns:
A
Summary. Its mean is weighted by 1/u² where every value has an uncertainty above zero.- Raises:
KeyError -- An unknown field; the message names the nearest.
ValueError -- No sample of the list holds a number there.
Example
>>> round(specimens.stats("tensile_strength").mean, 1) 352.3
- to_csv(path=None, columns=None, profile=None, overwrite=False)¶
The list as CSV, as the command line exports it.
- Parameters:
path -- The file to write. Without it, the text is returned.
columns -- The fields to include: a list, or comma-separated as
-cwrites them, eachFIELD[:PRECISION][=LABEL].profile -- A profile's name in
.samplekitrc, or aProfile, instead ofcolumns.overwrite -- Replace an existing file.
- Returns:
The text, when no
pathis given; otherwiseNone.- Raises:
ValueError -- Neither
columnsnorprofileis given, or both.KeyError -- An unknown field or profile; the message names the nearest.
FileExistsError --
pathexists andoverwriteis false.
Example
>>> text = specimens.to_csv(columns="name,area")
- to_dict(columns=None, profile=None)¶
The list as a dict of columns, one list of values per column heading.
Values are the stored numbers, unrounded.
- Parameters:
columns -- The fields to include: a list, or comma-separated as
-cwrites them, eachFIELD[:PRECISION][=LABEL].profile -- A profile's name in
.samplekitrc, or aProfile, instead ofcolumns.
- Returns:
A dict from each heading to its values, one per sample.
- Raises:
ValueError -- Neither
columnsnorprofileis given, or both.KeyError -- An unknown field or profile; the message names the nearest.
Example
>>> columns = specimens.to_dict(columns="name,area") >>> list(columns) ['name', 'area_value', 'area_uncertainty']
- to_json(path=None, columns=None, profile=None, overwrite=False)¶
The list as JSON, as the command line exports it.
- Parameters:
path -- The file to write. Without it, the text is returned.
columns -- The fields to include: a list, or comma-separated as
-cwrites them, eachFIELD[:PRECISION][=LABEL].profile -- A profile's name in
.samplekitrc, or aProfile, instead ofcolumns.overwrite -- Replace an existing file.
- Returns:
The text, when no
pathis given; otherwiseNone.- Raises:
ValueError -- Neither
columnsnorprofileis given, or both.KeyError -- An unknown field or profile; the message names the nearest.
FileExistsError --
pathexists andoverwriteis false.
Example
>>> text = specimens.to_json(columns="name,area")
- to_text(style, path=None, columns=None, profile=None, overwrite=False)¶
The list as a document in a style:
"latex","markdown","html", or one[style.NAME]declares, as--style NAME -o -writes it.- Parameters:
style -- The style's name.
path -- The file to write. Without it, the text is returned.
columns -- The fields to include: a list, or comma-separated as
-cwrites them, eachFIELD[:PRECISION][=LABEL].profile -- A profile's name in
.samplekitrc, or aProfile, instead ofcolumns.overwrite -- Replace an existing file.
- Returns:
The text, when no
pathis given; otherwiseNone.- Raises:
ValueError -- No style writing documents has that name, or neither
columnsnorprofileis given, or both.KeyError -- An unknown field or profile; the message names the nearest.
FileExistsError --
pathexists andoverwriteis false.
Example
>>> table = specimens.to_text("latex", columns="name,area")
- to_tsv(path=None, columns=None, profile=None, overwrite=False)¶
The list as TSV, as the command line exports it.
- Parameters:
path -- The file to write. Without it, the text is returned.
columns -- The fields to include: a list, or comma-separated as
-cwrites them, eachFIELD[:PRECISION][=LABEL].profile -- A profile's name in
.samplekitrc, or aProfile, instead ofcolumns.overwrite -- Replace an existing file.
- Returns:
The text, when no
pathis given; otherwiseNone.- Raises:
ValueError -- Neither
columnsnorprofileis given, or both.KeyError -- An unknown field or profile; the message names the nearest.
FileExistsError --
pathexists andoverwriteis false.
Example
>>> text = specimens.to_tsv(columns="name,area")
- samplekit.keep(message=None)¶
Keep what the script has saved so far as one snapshot of the history.
A script's saves are kept as one snapshot when it ends, with the script's source beside it;
keeptakes that snapshot now, so that the history shows the script's steps apart.- Parameters:
message -- What the snapshot says; the script's command line when not given. A blank message says nothing, and several lines are kept on one.
- Warns:
UserWarning -- Nothing was saved in a project since the last snapshot, so nothing is kept.
- Raises:
TypeError -- The message is not text.
Example
>>> steel.save() >>> sk.keep("thickness measured again")
Values¶
A sample's properties are Property objects: a value, an uncertainty, a unit,
readings. A value that does not apply to a sample is NA. An attribute that
holds a list is a BoundList, which writes its changes through to the
sample.
- class samplekit.Property(value=None, uncertainty=None, unit=None, symbol=None, precision=None, compute=None, compute_value=None, compute_uncertainty=None, compute_column=None, depends_on=None)¶
A property: a value, its uncertainty and its unit.
A property stands for its value in arithmetic and comparisons, so
steel.area * 2andsteel.area > 25work on the number, and it prints as the whole property,25.056 ± 0.053 mm². A model declares its properties in its__init__; a property a model does not declare is made the same way and assigned to the sample.A property is one of four kinds, by what is given: a value entered by hand; readings, whose value and uncertainty a statistic gives; a value a formula computes (
compute, orcompute_valueandcompute_uncertainty); or nothing yet.A
Tabledeclares its columns with it too: there a property describes every cell of its column, with the same keywords, and its formula is given the row,f(row). A column takes no value nor uncertainty: each cell holds its own, in the file.- Parameters:
value -- The value — a number, text, a boolean, a date,
samplekit.NA— or a list of readings, or a statistic fromsamplekit.statsthat gives the value from the readings.uncertainty -- The absolute standard uncertainty, in the value's unit, or a spread from
samplekit.stats.unit -- The unit, as the file writes it:
"g","degC".symbol -- Not taken here: a symbol is declared in
.samplekitrc, under[property.NAME].precision -- Not taken here: a precision is declared in
.samplekitrc, under[property.NAME].compute -- A function of no argument returning the property: a number, or
(value, uncertainty).compute_value -- A function of no argument returning the value alone, beside an uncertainty entered, given by readings or computed apart.
compute_uncertainty -- A function of no argument returning the uncertainty, beside a value entered or computed apart.
compute_column -- For a table's column only: a function given the columns it reads, by name, and returning a list, one cell per row, each a number or
(value, uncertainty).depends_on -- What the formula reads: a list of names —
["width", "thickness"],"curve.force"for a column,"row.force"for a cell of the same row — or, where the value and the uncertainty have a formula each,{"v": [...], "u": [...]}.[]says it reads nothing of the sample. It can also be declared later withSample.set_dependencies.
- Raises:
ValueError -- Two arguments give the same thing —
valueand a formula,computeandcompute_value,compute_columnand another — or a value is not a number where a unit is given.TypeError -- A formula is not callable, or a symbol or a precision is given.
Example
>>> import samplekit as sk >>> sk.Property(3.2, 0.1, unit="kg") Property(value=3.2, uncertainty=0.1, unit='kg') >>> width = sk.Property(unit="mm", value=sk.stats.mean, ... uncertainty=sk.stats.standard_error)
- compute(rerun=False, force=False)¶
Compute the value, after the inputs it needs.
Only a value that is outdated or never computed runs, unless asked otherwise. The file is not written:
save()does that.- Parameters:
rerun -- Run it even when it is current.
force -- Run it even when it is edited, giving it back to its formula.
- Raises:
ValueError -- The value has no formula.
Exception -- Whatever the formula raised, with a note naming the value.
- edited_upstream¶
The edited values this one was computed from, directly or further up.
- failure¶
What the formula raised when it last ran, or
Noneif it did not fail.
- format(unit=True)¶
Format the property at its declared precision.
- Parameters:
unit -- Include the unit.
- Returns:
The property as text, such as
"25.056 ± 0.053 mm²". For another precision, use a format specifier:f"{steel.area:.2f}".
- is_computed¶
Whether a formula gives the value.
- is_edited¶
Whether the value is edited — typed over its formula, or a computed table cell whose record is missing.
- is_outdated¶
Whether the value is outdated — an input changed since it was computed.
- readings¶
The readings, or
Nonefor a value not measured several times.The list is bound to the property:
append,removeor an item assigned changes the property, as assigning a whole list does. Readings are refused on a value a formula computes.
- state¶
Where the value stands, in one word.
One of
"entered"(typed in, no formula),"absent"(no formula, and nothing typed in),"current","outdated"(an input changed since it was computed),"waiting"(an input it reads was emptied since: the number is the one computed before),"never_computed","edited"(a value typed over its formula) or"failed"(its formula raised): the words a filter'sstatetakes.
- stats¶
The statistics of the readings, as a
Summary, orNonewithout readings.
- symbol¶
The property's symbol — the one this sample's file writes, else the one the project declares in
.samplekitrcunder[property.NAME], elseNone. Read only: a symbol is the project's, declared there, never set by a model or a script.
- to_text(style=None)¶
The property as a style writes it: its units, its symbols, its form of a property —
\SI{12.5 \pm 0.05}{\gram}in a style declaringproperty = '\SI{{value} \pm {uncertainty}}{{unit}}'.- Parameters:
style -- A style's name:
"plain", one SampleKit gives —"latex","markdown","html"— or one.samplekitrcdeclares. Without it,[render] style's, asstr()gives.- Returns:
The text,
n/awhere the value does not apply, and the style'smissingwhere there is none.- Raises:
ValueError -- No style has that name.
Example
>>> steel.area.to_text("latex") '$25.056 \\pm 0.053$ mm²'
- u¶
The uncertainty — the same as
uncertainty, spelt as a field path spells it (area.u).
- uncertainty¶
The absolute standard uncertainty, in the value's unit, or
None.
- unit¶
The unit, as the file writes it —
"g","degC"— orNone.
- v¶
The value — the same as
value, spelt as a field path spells it (area.v).
- value¶
The value — a number, text, a boolean, a date,
samplekit.NA, orNonewhen there is none.Assigning a value to a computed property overrides its formula: the property reads edited until
compute(force=True)gives it back to the formula. Assigning a list gives the property readings. A property with a unit takes numbers only, and raisesValueErrorotherwise.
- samplekit.NA¶
A value that does not apply to a sample —
yield_strength: n/ain its file.There is one,
samplekit.NA. It is false in a test and prints asn/a; a property set to it is saved asn/a, and a formula reading it givesNAtoo, without running.Example
>>> steel.yield_strength.value = sk.NA
- class samplekit.NotApplicable¶
A value that does not apply to a sample —
yield_strength: n/ain its file.There is one,
samplekit.NA. It is false in a test and prints asn/a; a property set to it is saved asn/a, and a formula reading it givesNAtoo, without running.Example
>>> steel.yield_strength.value = sk.NA
- class samplekit.BoundList(iterable=(), /)¶
A list bound to a sample: its changes are the sample's.
A sample's tags, a list attribute and a property's readings are read as one.
append,remove, an item assigned and every other change is checked and made in the sample too, and a refused item leaves both unchanged.list(...)or.copy()is a plain copy, bound to nothing, and so is a list read before the attribute was assigned again.Example
>>> steel.tags.append("reference")
- append(item)¶
Append object to the end of the list.
- extend(items)¶
Extend list by appending elements from the iterable.
- insert(index, item)¶
Insert object before index.
- pop(index=-1)¶
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
- remove(item)¶
Remove first occurrence of value.
Raises ValueError if the value is not present.
- clear()¶
Remove all items from list.
- sort(*, key=None, reverse=False)¶
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
- reverse()¶
Reverse IN PLACE.
- copy()¶
Return a shallow copy of the list.
Tables¶
A table of a sample holds rows of measurements, by column. Each column of a
new Table is declared with Property, as a property is: its unit, the
statistics of its cells' readings, or the formula that computes its cells;
its symbol, like any symbol, is the project's. ComputedColumns fills several
columns with one formula. ColumnView and RowView read a table by column
and by row.
- class samplekit.Table(columns, *positional, index=None, title=None, rows=None, computed=None)¶
A table of a sample: named columns, and rows identified by their index.
The index is the column — or the columns — whose values identify a row: a day, a temperature, a inspector. A cell is read by its index value, never by its position:
table.at(0.2, "force").A column is declared with
Property: its unit, the statistics of its cells' readings, or the formula that computes each cell, given the row (compute,compute_value,compute_uncertainty), or the whole column at once (compute_column). A formula filling several columns at once is aComputedColumns, given incomputed.- Parameters:
columns -- A dict of
Propertyby name, in the order they are shown.index -- The name of the index column, or a list of names; always named.
title -- A title for the table.
rows -- The first rows: each a dict of cells by column name.
computed -- The
ComputedColumnsof the table, each filling several columns.
- Raises:
TypeError -- A column is not a
Property, or is given a value; the index is not named.ValueError -- The index names no column, a row does not fit the columns, or a column is filled by two formulas.
Example
>>> inspection = sk.Table( ... {"inspector": sk.Property(), "score": sk.Property()}, ... index="inspector", ... rows=[{"inspector": "Ana", "score": 41}], ... ) >>> inspection.at("Ana", "score").value 41
- add(**cells)¶
Add a row at the end.
- Parameters:
**cells -- The row's cells by column name: a value, a list of readings, or a
Property. The index columns are required.- Raises:
KeyError -- A column the table does not have.
ValueError -- A row with that index exists already.
- at(index, column)¶
The cell of a row, by the row's index value.
- Parameters:
index -- The row's index value; a tuple for an index of several columns.
column -- The column's name.
- Returns:
The cell, as a
Property.- Raises:
KeyError -- No row has that index, or the column is unknown; the message names the nearest.
Example
>>> steel.curve.at(0.2, "force").value 9.516
- column_names¶
The names of the columns, in the order they were declared.
- data_columns¶
The names of the columns that are not the index.
- extend(rows)¶
Add several rows at the end.
- Parameters:
rows -- An iterable of dicts, each a row's cells by column name.
- Raises:
KeyError -- A column the table does not have.
ValueError -- A row with that index exists already.
- index¶
The name of the index column, or a list of names for an index of several columns.
- index_unit¶
The unit of the index column, or a list of units for an index of several columns.
- index_values¶
The index value of each row, in row order; a tuple each for an index of several columns.
- title¶
The table's title, or
None.
- to_csv()¶
The table as rows of CSV, as
samplekit FILE view TABLE --csvprints it: its index first, each column a value and its uncertainty headed with the unit, at the precision its columns declare.- Returns:
The text.
- Raises:
ValueError -- The table belongs to no sample yet.
Example
>>> text = steel.curve.to_csv()
- to_text(style=None)¶
The table as
samplekit viewunfolds it: its columns headed with their units, its index first, each cell in a style's forms — those of its sample's project, or of the project the current folder is in for a table of no sample.- Parameters:
style -- A style's name:
"plain", one SampleKit gives, or one.samplekitrcdeclares. Without it,[render] style's.- Returns:
The text.
- Raises:
ValueError -- No style has that name.
Example
>>> print(steel.curve.to_text())
- uncertainties(column)¶
The uncertainties of a column, in row order.
- Parameters:
column -- The column's name.
- Returns:
A list of uncertainties,
Nonewhere a cell has none.- Raises:
KeyError -- The column is unknown; the message lists the columns.
- update(index, **cells)¶
Change cells of one row.
Values computed from those cells become outdated. A computed cell changed here is edited: kept by
compute()untilcompute(force=True).- Parameters:
index -- The row's index value; a tuple for an index of several columns.
**cells -- The new cells, by column name.
- Raises:
KeyError -- No row has that index, or a column is unknown; the message names the nearest.
- values(column)¶
The values of a column, in row order.
- Parameters:
column -- The column's name.
- Returns:
A list of values,
Nonewhere a cell has none.- Raises:
KeyError -- The column is unknown; the message lists the columns.
Example
>>> steel.curve.values("force")[:3] [0.0, 1.281, 2.585]
- class samplekit.ComputedColumns(columns, *, compute=None, compute_column=None, depends_on=None)¶
Several columns of a table filled by one formula: given each row, or the columns it reads whole.
A column filled alone declares its formula on its
Property; this is for one computation that gives several columns at once, a fit's two parameters.- Parameters:
columns -- The columns it fills: a name, or a list of names.
compute -- A function given each row, a
RowView, and returning a dict: one cell for each column it fills, a number or(value, uncertainty).compute_column -- A function given the columns it reads, by name, and returning a dict: one list of cells for each column it fills, one cell per row.
depends_on -- What the formula reads:
"row.force"for a cell of the same row,"curve.force"for a whole column,"area"for a property of the sample;[]for nothing.
- Raises:
ValueError -- Neither formula is given, or both, or
depends_onis not.TypeError -- A formula is not callable.
Example
>>> bounds = sk.ComputedColumns( ... ["low", "high"], compute=lambda row: {"low": 1.0, "high": 2.0}, ... depends_on=[], ... )
- class samplekit.ColumnView¶
One column of a table, as a
compute_columnformula receives it, and astable.column_namereads it.Iterating gives each cell as a
Property, in row order, and an item is the cell of a row, by its index value:column[3].- uncertainties¶
The uncertainty of each cell, in row order;
Nonewhere a cell has none.
- values¶
The value of each cell, in row order;
Nonewhere a cell has none.
- class samplekit.RowView¶
One row of a table, as a column's formula receives it.
A cell is read by its column's name, as an attribute or an item:
row.forceorrow["force"], each aProperty.- items()¶
Each column name with its cell.
- keys()¶
The names of the row's columns.
- position¶
The row's position in the table, from 0.
Statistics¶
stats names the statistics a model can choose for readings: which one is
the value, which one the uncertainty. Summary is the statistics of a set of
values: a property's readings, or a field over a list of samples.
- class samplekit.stats¶
The statistics a model can declare for readings.
Six give a value —
mean,median,minimum,maximum,first_quartile,third_quartile— and three give an uncertainty —standard_error,sample_stdev,population_stdev.Example
>>> width = sk.Property(unit="mm", value=sk.stats.mean, ... uncertainty=sk.stats.standard_error)
- class samplekit.Statistic¶
A statistic of a property's readings, which a model declares to give the value or the uncertainty.
The statistics are in
samplekit.stats.Example
>>> sk.Property(value=sk.stats.median, uncertainty=sk.stats.standard_error) Property(value=None)
- name¶
Its name, as
Summaryspells it —"median".
- class samplekit.Summary¶
The statistics of a set of values: readings, or a field over a list.
Given by
Property.statsandSampleList.stats.- considered¶
How many samples the value applies to, those holding no number included and those saying not applicable left out: the denominator of
count, as--summarywrites3/4.Nonefor readings.
- count¶
How many values were summarised.
- first_quartile¶
The first quartile.
- maximum¶
The largest value.
- mean¶
The mean — weighted by 1/u² where every value has an uncertainty above zero, the arithmetic mean otherwise.
weightedsays which.
- median¶
The median.
- minimum¶
The smallest value.
- not_applicable¶
How many samples say the value is not applicable, counted apart — neither summarised nor missing.
- population_stdev¶
The population standard deviation, dividing by n.
- sample_stdev¶
The sample standard deviation, dividing by n − 1;
Nonefor one value.
- standard_error¶
The standard error of the mean — 1/√Σw beside a weighted mean, the sample standard deviation over √n beside an arithmetic one;
Nonefor one value unweighted.
- third_quartile¶
The third quartile.
- to_text(style=None)¶
The summary as
--summarywrites a row of it: the count, the mean, the deviations, its standard errorsem, the median and the extremes.- Parameters:
style -- Accepted for every
to_text; a summary's numbers are written alike in every style.- Returns:
The text.
- weighted¶
Whether
meanis weighted by 1/u², as the command line's summary heads itmean (1/u²).
Figures¶
plot draws a figure declared in .samplekitrc, or one given by its axes.
figure marks a model's method as a figure of its own.
- samplekit.plot(target, figure=None, *, x=None, y=None, group=None, kind=None, title=None, x_label=None, y_label=None, style=None, x_limits=None, y_limits=None, x_scale=None, y_scale=None, aspect=None, legend=None, figsize=None, output=None, overwrite=False, project_style=True)¶
Draw a figure of a sample or a list of samples, with matplotlib.
The figure is a model's figure, one declared in
.samplekitrc, or axes given here:xandy, drawn as a declared figure would be. It opens in a window, or is written tooutput. The project's[matplotlib]settings apply to every figure.- Parameters:
target -- A sample, a
SampleList, or an iterable of samples.figure -- The name of a model's figure or of a declared one.
x -- The field on the x axis, for a figure not declared.
y -- The field on the y axis, for a figure not declared.
group -- A field, or several, whose values split the samples into series, each in its own colour.
kind --
"scatter"(the default),"line","step","bar"or"box".title -- The title;
""draws none.x_label -- The x axis label, instead of the field's symbol and unit.
y_label -- The y axis label, instead of the field's symbol and unit.
style -- The declared style whose symbols and units label the axes;
[render] figure_styleby default.x_limits -- The x axis bounds,
(low, high);Noneor"auto"leaves one free.y_limits -- The y axis bounds,
(low, high);Noneor"auto"leaves one free.x_scale --
"linear","log"or"symlog".y_scale --
"linear","log"or"symlog".aspect --
"equal"or"auto".legend -- Where the legend goes:
"best","outside","none"or one of matplotlib's places.figsize -- The figure's width and height, in centimetres.
output -- The file to write, in the format its extension names:
.png,.pdf,.svg…{name}in it writes one file per sample, for a figure of one sample. A folder it names that does not exist is made.overwrite -- Replace an existing file.
project_style -- Apply the project's
[matplotlib]settings.
- Returns:
The matplotlib figures drawn.
- Raises:
TypeError -- Neither
figurenorxandyis given, or both are, or axes options are given to a model's figure.KeyError -- An unknown figure or field; the message names the nearest.
ValueError -- No sample to draw, or an output format matplotlib cannot write.
FileExistsError --
outputexists andoverwriteis false.RuntimeError -- No
outputis given and there is no display.
Example
>>> figures = sk.plot(specimens, "curves", output="paper/curves.pdf") >>> figures = sk.plot(specimens, x="yield_strength", y="tensile_strength", ... group="material", output="strengths.png")
- samplekit.figure(method=None, *, subplots=None, figsize=None, matplotlib=None)¶
Mark a method of a model as a figure.
The method draws into the matplotlib axes it receives, and returns nothing;
samplekit.plotandsamplekit plotopen it in a window or write it to a file. A method draws one sample; placed above@classmethod, it draws a list of them.- Parameters:
method -- The method, when used without arguments:
@sk.figure.subplots --
(rows, columns): the method receives the array of axesplt.subplotsmakes, instead of one.figsize -- The figure's width and height, in centimetres.
matplotlib -- matplotlib's settings for this figure alone, by their names, over the project's
[matplotlib]:{"lines.marker": "None"}.
- Returns:
The method, marked.
- Raises:
ValueError --
subplotsis not two positive integers.
Example
>>> class Specimen(sk.Sample): ... @sk.figure ... def stress_strain(self, ax): ... ax.plot(self.curve.values("strain"), ... self.curve.values("stress"))
Scripts¶
script marks a model's method as a script, which samplekit … run NAME
and p in the TUI run on each sample selected, or on the selection: see
Run a script of the model.
- samplekit.script(method)¶
Mark a method of a model as a script.
samplekit run NAMEruns it, andrin the workbench: a method acts on one sample, each selected in turn; placed above@classmethod, it receives the selection. Its keyword parameters are the command's options,--set offset=0.002, read as their annotation or their default says; its docstring is its description. What it changes in the samples is shown, and written once the change is accepted; what it returns is shown.- Parameters:
method -- The method.
- Returns:
The method, marked.
- Raises:
TypeError -- The method is a static method, or takes
*argsor**kwargs.
Example
>>> class Specimen(sk.Sample): ... @sk.script ... def classify(self, limit: float = 20.0): ... "Class the specimen's ductility by its elongation at break." ... self.ductility = "high" if self.elongation.value >= limit else "low"
The project¶
What a project declares in its .samplekitrc, as a script reads it: its
model, its queries, profiles, exports and figures, its units and properties.
project, on a sample or a list of samples, gives it.
- class samplekit.Project¶
A project: what its
.samplekitrcdeclares, read-only.Read from a sample or a list —
steel.project,specimens.project. Outside any project every collection of entries is empty.Example
>>> list(specimens.project.queries) ['ductile']
- collection¶
Which files are samples,
[collection], as aCollection.
- exports¶
The exports,
[export.*], by name, each anExport.
- figures¶
The figures,
[figure.*], by name, each aFigureDeclaration.
- matplotlib¶
The matplotlib settings every figure is drawn with,
[matplotlib]— a dict by matplotlib's own dotted names.
- model¶
The model,
[model], orNonewhen the project declares none.
- profiles¶
The profiles,
[profile.*], by name, each aProfile.
- properties¶
The declared properties,
[property.*], by name, each aPropertyDeclaration.
- queries¶
The saved queries,
[query.*], by name, each aQuery.
- render¶
How tables and figures are rendered,
[render], as aRender.
- root¶
The folder holding
.samplekitrc, orNoneoutside a project.
- units¶
The declared units,
[unit.*], by spelling, each aUnit.
- class samplekit.Model¶
The project's model,
[model]: the Python file and class its samples are read with.- class_name¶
The class in that file, or
Nonewhen the file declares only one.
- path¶
The model's Python file.
- class samplekit.Collection¶
Which files of the project are samples,
[collection].- exclude¶
The globs of files that are not samples.
- files¶
Where a sample's own files are looked for,
[collection] files— the folders searched by the sample's name, and the patterns naming it, as written.
- include¶
The globs a sample's file must match.
- recursive¶
Whether subfolders are searched.
- class samplekit.Query¶
A saved query,
[query.*]: a filter under a name.- directory¶
The folder the query searches by default, or
Nonefor the project's.
- filter¶
The filter expression, as
-ftakes it.
- name¶
The query's name.
- class samplekit.Profile¶
A profile,
[profile.*]: the columns of a table, and the order of its rows.- columns¶
The columns, each a
ColumnSpec, in order.
- name¶
The profile's name.
- sort¶
The sort keys, in order of precedence; a leading
-sorts descending.
- class samplekit.ColumnSpec¶
One column of a profile: its field, its headings and its precision.
- field¶
The field the column shows.
- header¶
The heading of the column in an exported file, or
None.
- label¶
The heading of the column in a terminal table, or
Nonefor the field.
- precision¶
The column's precision —
".3f", or a pair for the value and the uncertainty — orNone.
- template¶
The text each cell is written as, such as
"{value:.3f}", orNone.
- class samplekit.Export¶
An export,
[export.*]: a profile written to a file in a format, or a figure drawn to a file.- figure¶
The name of the figure it draws, or
Nonefor a table's export.
- filename¶
Whether the export adds a column with each sample's file name.
- format¶
The data format —
"csv","tsv","json"— orNonefor a document its style writes, or a figure.
- name¶
The export's name.
- output¶
The file it writes.
- path¶
Whether the export adds a column with each sample's path.
- profile¶
The name of the profile it writes, or
Nonefor a figure's export.
- query¶
The saved query that selects its samples, or
None.
- class samplekit.FigureDeclaration¶
A figure declared in
.samplekitrc,[figure.*]: what it draws, and how its axes are set.- aspect¶
"equal"or"auto", orNone.
- figsize¶
The figure's width and height in centimetres, or
None.
- group¶
The field, or comma-separated fields, whose values split the samples into series;
Nonefor one series.
- kind¶
"scatter","line","step","bar"or"box".
- legend¶
Where the legend goes —
"best","outside","none"or one of matplotlib's places — orNone.
- matplotlib¶
Its own matplotlib settings, over the project's
[matplotlib], by matplotlib's dotted names.
- name¶
The figure's name.
- query¶
The saved query that selects its samples, or
None.
- style¶
The style whose symbols and units label the axes, or
None.
- title¶
The title, or
None.
- x¶
The field on the x axis.
- x_label¶
The x axis label, or
Nonefor the field's symbol and unit.
- x_limits¶
The x axis bounds,
Nonefor a free one;Nonewhen not declared.
- x_scale¶
"linear","log"or"symlog", orNone.
- y¶
The field on the y axis.
- y_label¶
The y axis label, or
Nonefor the field's symbol and unit.
- y_limits¶
The y axis bounds,
Nonefor a free one;Nonewhen not declared.
- y_scale¶
"linear","log"or"symlog", orNone.
- class samplekit.Render¶
How the project renders tables and figures,
[render].- figure_style¶
The style figures label their axes in when they name none, or
None.
- precision¶
The precision of every number without its own, or
None.
- style¶
The style tables are rendered in, or
None.
- table¶
How a table is drawn —
"plain"or"boxed"— orNone.
- class samplekit.Unit¶
A unit declared in
.samplekitrc,[unit.*]: how it is written in each style.- spelling¶
The unit as the files write it —
"degC".
- variants¶
The unit in each style, by style name —
{"plain": "°C"}.
- class samplekit.PropertyDeclaration¶
A property declared in
.samplekitrc,[property.*]: its unit, symbol and precision, for every sample of the project.- precision¶
The precision —
".3f", or a pair for the value and the uncertainty — orNone.
- symbol¶
The symbol, or
None.
- symbol_variants¶
The symbol in each style, by style name:
{"figure": "$\\sigma$"}.
- unit¶
The unit, or
None.
- class samplekit.Names¶
The entries a project declares, read-only, by name.
An entry is read as an attribute or an item —
project.queries.ductileorproject.queries["ductile"]— and iterating gives the names. An unknown name raisesAttributeErrororKeyErrornaming the nearest.