calamari.measurement.Measurement#

class calamari.measurement.Measurement(path, data_format, measurement_type, file_role, title, header=dict(), data=DataFrame(), moment_base=None)#

Bases: object

A single parsed magnetometry measurement file.

path#

Source file path.

Type:

pathlib.Path

data_format#

Loader dialect that produced this object: the format_name of the registered loader that claimed the file, normally 'MPMS3'. Always a real dialect – calamari.io.load() raises UnsupportedFileError for a file no loader recognises rather than returning a partly-parsed object (IO-5), so downstream code never has to test for an “unknown” format. (measurement_type below is a separate question and can still be 'unknown': the dialect is known, but which kind of measurement it holds may not be.)

Type:

str

measurement_type#

One of 'DC', 'AC', 'VSM', or 'unknown'.

Type:

str

file_role#

One of 'summary', 'raw', 'diagnostic', 'log'.

Type:

str

title#

Descriptive run name from TITLE; it does not identify the measurement family.

Type:

str or None

header#

Parsed header metadata (sample name/mass/comment/date and any other INFO fields, plus raw_lines and the info sub-dict).

Type:

dict

data#

Raw data table from the [Data] section, numeric where possible, with column names taken verbatim from the file.

Type:

pandas.DataFrame

property temperature: Series | None#

Temperature column in Kelvin, or None if absent.

property field_oe: Series | None#

Applied field column in Oe, or None if absent.

Converts automatically if the file records field in Tesla (the instrument’s alternate unit selection) – the accessor’s declared unit is what you get, per DM-2.

property field_tesla: Series | None#

Applied field column converted to Tesla, or None if absent.

Uses the exact CGS-Gaussian factor OE_PER_TESLA (1 T = 1e4 Oe) from calamari.constants; unit conversions never hard-code the factor at the call site.

property moment_emu: Series | None#

DC moment column in emu, or None if absent.

Matches MPMS3 Moment / DC Moment Free Ctr bases. A file recorded in A m^2 (the instrument’s alternate moment unit) is converted to emu here, so the accessor’s name stays true whatever the operator selected.

Of MPMS3’s two DC-scan moments this reads the free-centre one (DC Moment Free Ctr), never DC Moment Fixed Ctr. The free-centre fit leaves both sample position and moment free, which is the right default for a well-centred sample with a decent signal; for a weak moment that fit is poorly conditioned and the AutoTracking-constrained fixed-centre value can be the more trustworthy number. Read data['DC Moment Fixed Ctr (emu)'] directly for that case, and data['DC Free Fit'] (0-1) to judge which to believe.

If more than one moment column carries data – a sequence that switched measurement mode partway, or alternated row by row – this raises AmbiguousColumnError rather than picking one. Choose with with_moment(); see moment_columns for what the file offers.

property moment_err_emu: Series | None#

Per-point standard error on moment_emu, in emu, or None.

The instrument measures this and writes it alongside every moment; it is the yerr calamari.fitting.fit is built around, and supplying it is the difference between reported uncertainties that are absolute and ones rescaled from the residual scatter (see the error convention in calamari.fitting.engine):

result = calamari.fit("linear", m.field_oe, m.moment_emu,
                      yerr=m.moment_err_emu)

Follows moment_emu: whichever moment column is in use names its own error column, so a with_moment() choice carries over and the two can never come from different measurements. Converted with the same unit factor as the moment, so the ratio is preserved.

None when the file records no error for the moment in use.

Warning

A zero error is not the same as no error, and is common: an instrument reporting scan-to-scan scatter writes 0 when only one scan was averaged, which covers most single-shot measurements. Passing an all-zero yerr to a least-squares fit gives every point infinite weight and the result will not be meaningful. Check (err > 0).any() before using it as a weight.

property chi_real_err: Series | None#

Recorded standard error on chi_real in emu/Oe, or None if absent.

Resolved from the error column paired with the populated susceptibility component and converted using its own unit suffix. A recorded zero error must not be treated as an exact observation when choosing fit weights.

property chi_imag_err: Series | None#

Per-point standard error on chi_imag, in emu/Oe, or None.

The out-of-phase counterpart of chi_real_err; see there.

property moment_columns: tuple[str, ...]#

Moment columns present in data and carrying values.

The candidates moment_emu chooses between, in priority order, named exactly as the file spells them. Empty when the file records no moment at all; length 1 for almost every file, since an instrument writes the column set for every application it has installed and the unused modes’ columns sit empty.

Length > 1 means the file holds more than one kind of moment measurement – see with_moment().

with_moment(column)#

Return a NEW Measurement whose moment_emu reads column.

For a file recording more than one kind of moment, this is how you say which you want – and, because it is a cheap derivation rather than a re-parse, how you get both from one load:

m = calamari.load(path)
vsm = m.with_moment("Moment")
dc  = m.with_moment("DC Moment Free Ctr")

Both are ordinary Measurement objects sharing the parsed data, so either can be handed to plotting, fitting or transition detection. It is also the way to reach MPMS3’s fixed-centre moment, which no accessor returns by default:

fixed = m.with_moment("DC Moment Fixed Ctr")
Parameters:

column (str) – Column name, with or without its unit suffix – "DC Moment Free Ctr" and "DC Moment Free Ctr (emu)" are both accepted, so a name copied from moment_columns or from data.columns works either way. The unit is still read from the file’s own suffix and converted as usual, so this selects which measurement, never what unit it is in.

Return type:

Measurement

Returns:

calamari.measurement.Measurement – A new object; self is unchanged (DM-1). The choice survives restrict().

Raises:

ValueError – If no column with that base name exists in data. Naming a column the file does not have is a caller error, and silently falling back to the default priority would hide it.

property chi_real: Series | None#

Recorded AC in-phase susceptibility chi’ in emu/Oe, or None if absent.

Reads MPMS3’s AC X’ column and converts its unit suffix. No moment/drive re-derivation is performed. The recorded error is exposed separately.

property chi_imag: Series | None#

Recorded AC out-of-phase susceptibility chi’’ in emu/Oe, or None.

property ac_frequency: Series | None#

Recorded AC drive frequency in Hz, or None if absent.

Reads AC Frequency. The bare Frequency column describes mechanical VSM oscillation and is deliberately excluded.

property ac_drive_oe: Series | None#

Achieved peak AC drive field in Oe, or None if absent.

Reads AC Drive, including modulation and nulling-coil contributions. A recorded Tesla unit is converted to Oe.

property sample_name: str | None#

Sample name/material from header INFO, or None.

property sample_mass_mg: float | None#

Operator-entered SAMPLE_MASS in milligrams, or None if unrecorded.

The header cannot corroborate the specimen mass. Sample.from_measurement records file/user provenance and lets an explicit caller mass take precedence.

property sample_molar_mass_g_per_mol: float | None#

Molar mass from the header (MPMS3 SAMPLE_MOLECULAR_WEIGHT).

Exposed so the value is not silently dropped, but deliberately not used by calamari.sample.Sample.from_measurement(), which is where the mass is adopted automatically. The two are not as symmetric as they look:

  • A sample mass is a property of this specimen. Only weighing it can tell you, so the header may be the only record there is – reading it fills a gap nothing else can.

  • A molar mass is a property of the compound: chemistry, computable from the formula, the same for every sample of the material. The caller always has an authoritative source, so preferring a number typed into an instrument wizard would be adopting a convenience copy over a better-known fact.

Opting in is one visible line:

Sample.from_measurement(
    m, molar_mass_g_per_mol=m.sample_molar_mass_g_per_mol
)

The g/mol in the name is inferred, not verified: “molecular weight” is numerically the molar mass in g/mol and there is no plausible alternative, but no real file carrying a populated value has been examined – the field is routinely left blank.

property comment: str | None#

Sample comment from header INFO, or None.

property date_iso: str | None#

Recorded file creation date as ISO YYYY-MM-DD.

Parsed from the human-readable M/D/YYYY token in the FILEOPENTIME line. Numeric timestamps are preserved without conversion; the empirically supported origin does not establish timezone handling.

property date_epoch: float | None#

Recorded numeric FILEOPENTIME token, or None.

Inspected native MPMS3 exports support seconds from 1899-12-30. Timezone and clock handling remain unspecified; no conversion is applied. Use date_iso for the recorded calendar date.

property row_families: Series#

Per-row measurement family, aligned to data.

Computed on access rather than stored, so it stays true through restrict(): a stored answer would go on describing the rows a subset no longer contains. See row_families() for the rule.

property measurement_types: tuple[str, ...]#

Which measurement families this file contains, in FAMILY_ORDER.

('VSM',) for an ordinary VSM run; ('VSM', 'AC') for a combined run that measured both at every setpoint. This is the structured form of measurement_type, and the one to branch on:

if 'AC' in m.measurement_types:
    ...

rather than m.measurement_type == 'AC', which is False for a file holding AC and something else.

Housekeeping rows contribute nothing: they are not a measurement family.

of_type(family)#

Return a NEW Measurement holding only one measurement family’s rows.

The way to read a combined run one measurement at a time:

m = calamari.load(path)          # measurement_type 'VSM+AC'
vsm = m.of_type("VSM")           # selected VSM moment
ac = m.of_type("AC")             # selected AC response

Both are ordinary Measurement objects sharing the parsed data, so either can be handed to plotting, fitting or transition detection – the same bargain with_moment() offers, one level up. It is also how a combined VSM+DC file’s moment_emu becomes answerable: the ambiguity that accessor refuses to guess at is exactly the choice this makes explicit.

Parameters:

family (str) – 'VSM', 'DC' or 'AC'. measurement_types lists what this file offers.

Return type:

Measurement

Returns:

calamari.measurement.Measurement – A new object; self is unchanged (DM-1). Its measurement_type is restamped to the single family, so it no longer claims to hold rows it does not. Asking for the only family a file has returns a full copy rather than self, so the result is always safe to treat as a derived object.

Raises:

MeasurementFamilyError – If this file holds no rows of that family. Naming a family the file does not have is a caller error, and returning an empty Measurement would hide it – an empty sweep looks like a sweep that measured nothing, not like a question that was wrong.

split_by_type()#

Every measurement family in the file, as its own Measurement.

Keyed in FAMILY_ORDER, so iteration order is stable across files:

for family, part in m.split_by_type().items():
    print(family, len(part.data))

A file with one family returns one entry – the honest answer, and it means a caller written for combined runs also works on ordinary ones with no special case. Housekeeping rows are in no bucket: they are not a measurement, and every row of data remains reachable from the original object.

Return type:

dict[str, Measurement]

property moment_method: str | None#

'VSM', 'DC', or None if the file records no moment.

Both a VSM measurement and a DC scan yield a moment in emu, and moment_emu names its unit but not its provenance. This names the provenance – the counterpart of calamari.sample.Sample.mass_source, and the answer to “how was the number I am plotting actually obtained?”.

'DC' means a DC scan (the instrument translating the sample through the pickup coils and fitting the response); 'VSM' means the sample vibrating at fixed position. They are different measurements of the same quantity, with different noise and different systematics.

The vocabulary is deliberately the same as measurement_types, so the two compose:

m.of_type(m.moment_method)

Follows with_moment(): whichever moment column is in use decides the answer. If more than one moment column carries data and no choice has been made, this raises AmbiguousColumnError exactly as moment_emu does – if it answered anyway, the two accessors could describe different measurements.

Type:

How the moment in moment_emu was measured

max_repeats()#

Largest number of repeat measurements of one setpoint, or 1.

Read from the instrument’s own Measurement Number column, which MPMS3 populates as 1, 2, 1, 2, ... when each setpoint was measured twice. A new repetition begins wherever the counter fails to increase.

Deliberately counter-only: it never falls back to guessing from setpoint tolerances. This is reported by __repr__() and summary(), and calamari.catalog.summarise() builds on the latter, so a tolerance-based detector would run over every file in a directory tree and announce phantom repeats wherever the tolerance happened not to suit. Detection that appears unbidden has to be the kind that cannot be wrong.

Returns 1 for a file with no such column, a constant one, or genuinely no repeats. Use calamari.repeats.repeat_groups() for the real answer, which groups on the setpoints when the counter cannot help.

Housekeeping rows are excluded before the counter is read (_measured()). A locate scan sitting between two measurements is not a repetition of either, and one carrying a counter value that continues the run’s sequence would otherwise extend a genuine pair into a phantom triple.

Return type:

int

summary()#

A one-glance description of this measurement, as a plain dict.

The “what am I holding?” answer: dialect, measurement type, sample, date, point count, temperature and field spans, AC frequencies and scan classification. Every value is derived from this object, so it costs no re-parse.

This is the per-file half of a catalog row – calamari.catalog.summarise() builds on it, adding only the path-derived fields it needs a root directory to compute, so the two cannot drift apart.

Accessors that would raise (an unrecognised unit, or a file holding more than one kind of moment) are reported as None rather than propagating: this method describes a file, including a problematic one.

Return type:

dict

Returns:

dict – Keys: data_format, measurement_type, file_role, sample_name, sample_mass_mg, date, n_points, n_measurements, T_min, T_max, H_min_Oe, H_max_Oe, H_min_T, H_max_T, ac_frequencies_Hz, scan_kind, max_repeats, comment, and from quality() n_flagged, max_continuity_score and n_status_departures (None when no point could be scored).

Notes

n_points counts rows, and keeps that meaning: a row the instrument wrote is a row, and silently redefining a published column would be the kind of changed-number-that-looks-the-same this library exists to avoid. n_measurements is the count excluding housekeeping rows (see _measurement_mask()); the two are equal for every file that has no such rows, which is most of them. The T/H spans and scan_kind, by contrast, describe the measurement and so exclude housekeeping rows – they were simply wrong before, not differently defined. The AC frequency list excludes them for the same reason (see _ac_frequency_summary()).

quality(*, threshold=None)#

Screen every measured point: which deserve a second look, and why.

Returns a QualityReport: one row per measured point, scored within its own measurement family (and AC frequency) in file order. A point is flagged when its value breaks the continuity of its neighbours – its departure from a straight line through them (fitted against the swept field or temperature), over how far they stray from that line themselves, exceeds threshold. A transition step or a cusp scores near 1, because its neighbours disagree too; an isolated glitch scores in the hundreds.

Beside the flag the report carries the evidence for reading it – the point’s uncertainty relative to its neighbours’, its within-point temperature and field spread, the instrument’s fit quality for the moment in use, status codes that depart from this file’s usual value, SQUID range changes. None of these is a gate, because on real files each fires on innocent points alone (see calamari.quality):

report = m.quality()
report                     # one line: how many flagged, max score
report.flagged             # the rows, with their evidence
m.data.loc[report.flagged.index]   # the raw rows themselves

Nothing is removed from the Measurement (DM-1); the report only describes.

Parameters:

threshold (float | None) – Continuity score above which a point is flagged. Default calamari.quality.CONTINUITY_THRESHOLD (20), an empirical diagnostic default, not a calibrated false-alarm probability.

Returns:

calamari.quality.QualityReport

Raises:

ValueError – If threshold is not positive.

classify_scan(t_tol_K=0.5, h_tol_Oe=10.0)#

Classify the sweep as a temperature scan, field scan, or other.

A quantity is considered “~constant” when its span (max - min) stays below the given tolerance, i.e. within instrument setpoint jitter. Only quantities with at least two non-null points are eligible to be judged “varying”.

Housekeeping rows are excluded first (_measured()). They are not measurements, and they sit wherever the transport happened to be: a real isothermal M(H) ending in a locate scan several kelvin away was classified 'mixed' on the strength of that one row.

Parameters:
  • t_tol_K (float) – Temperature span (K) above which temperature is treated as varying. Default SCAN_T_TOL_K (0.5 K), a generic choice tuned on MPMS3 data; raise it for noisier thermometry.

  • h_tol_Oe (float) – Field span (Oe) above which field is treated as varying. Default SCAN_H_TOL_OE (10 Oe).

Return type:

str

Returns:

str – 'T-scan' (T varies, H constant), 'H-scan' (H varies, T constant), 'mixed' (both vary), or 'static/other' (neither varies).

property scan_kind: str#

Sweep classification using the default tolerances.

Convenience wrapper over classify_scan(); see there for the thresholds and their rationale. One of 'T-scan', 'H-scan', 'mixed', 'static/other'.

restrict(*, t_range=None, h_range=None, mask=None)#

Return a NEW Measurement keeping only rows that pass every filter.

Generic row-restriction primitive: this is the library equivalent of a project-side “clip this file to the T<=30 K region before searching for transitions” wrapper (a restrict-shaped need shows up any time a caller wants a sub-window of one file without re-parsing it – e.g. dropping a featureless high-T tail before transition detection, isolating one field range, or applying an arbitrary hand-built boolean selection). Per the immutability convention (see module docstring / DM-1), this never mutates self: it returns a new Measurement with a shallow copy of header and a re-indexed copy of data; the original object (and any other reference to it) is untouched.

Parameters:
  • t_range (tuple[float, float] | None) – Inclusive (lo, hi) bounds (Kelvin) applied to temperature. Raises ValueError if given and this Measurement has no temperature column.

  • h_range (tuple[float, float] | None) – Inclusive (lo, hi) bounds (Oe) applied to field_oe – NOT field_tesla, matching the raw column’s native unit. Raises ValueError if given and this Measurement has no field column.

  • mask (object | None) – A boolean mask aligned positionally to data (i.e. its length must equal len(self.data)). Combined with t_range/h_range by logical AND when more than one filter is given.

Return type:

Measurement

Returns:

calamari.measurement.Measurement – A new object whose data contains only the rows that pass every given filter, with a reset RangeIndex. header is a shallow copy (dict(self.header)); all other fields (path, data_format, measurement_type, file_role, title) are shared as-is, since they describe the source file and are unaffected by row selection.

Notes

A row whose filter column is NaN is dropped only by the filter that reads that column: a NaN temperature fails t_range (so that row is excluded whenever t_range is given) but is untouched by h_range or mask, and vice versa – this falls out naturally from pandas’ NaN-comparisons (NaN >= lo and NaN <= hi are both False), no special-casing needed. Giving no filters at all (t_range=h_range=mask=None) returns a full copy. A filter combination that keeps no rows returns a Measurement with an empty (but correctly columned) data DataFrame, not an error.