calamari.measurement.Measurement#
- class calamari.measurement.Measurement(path, data_format, measurement_type, file_role, title, header=dict(), data=DataFrame(), moment_base=None)#
Bases:
objectA single parsed magnetometry measurement file.
- path#
Source file path.
- Type:
- data_format#
Loader dialect that produced this object: the
format_nameof the registered loader that claimed the file, normally'MPMS3'. Always a real dialect –calamari.io.load()raisesUnsupportedFileErrorfor 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_typebelow is a separate question and can still be'unknown': the dialect is known, but which kind of measurement it holds may not be.)- Type:
- title#
Descriptive run name from TITLE; it does not identify the measurement family.
- header#
Parsed header metadata (sample name/mass/comment/date and any other
INFOfields, plusraw_linesand theinfosub-dict).- Type:
- data#
Raw data table from the
[Data]section, numeric where possible, with column names taken verbatim from the file.- Type:
- 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) fromcalamari.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 Ctrbases. 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), neverDC 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. Readdata['DC Moment Fixed Ctr (emu)']directly for that case, anddata['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
AmbiguousColumnErrorrather than picking one. Choose withwith_moment(); seemoment_columnsfor 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
yerrcalamari.fitting.fitis 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 incalamari.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 awith_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
yerrto 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
dataand carrying values.The candidates
moment_emuchooses 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_emureadscolumn.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
Measurementobjects 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 frommoment_columnsor fromdata.columnsworks 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:
- Returns:
calamari.measurement.Measurement– A new object;selfis unchanged (DM-1). The choice survivesrestrict().- 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 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_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/molin 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 date_iso: str | None#
Recorded file creation date as ISO
YYYY-MM-DD.Parsed from the human-readable
M/D/YYYYtoken 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_isofor 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. Seerow_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 ofmeasurement_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
Measurementobjects sharing the parsed data, so either can be handed to plotting, fitting or transition detection – the same bargainwith_moment()offers, one level up. It is also how a combined VSM+DC file’smoment_emubecomes answerable: the ambiguity that accessor refuses to guess at is exactly the choice this makes explicit.- Parameters:
family (
str) –'VSM','DC'or'AC'.measurement_typeslists what this file offers.- Return type:
- Returns:
calamari.measurement.Measurement– A new object;selfis unchanged (DM-1). Itsmeasurement_typeis 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 thanself, 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
dataremains reachable from the original object.- Return type:
- 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_emunames its unit but not its provenance. This names the provenance – the counterpart ofcalamari.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 raisesAmbiguousColumnErrorexactly asmoment_emudoes – if it answered anyway, the two accessors could describe different measurements.- Type:
How the moment in
moment_emuwas measured
- max_repeats()#
Largest number of repeat measurements of one setpoint, or 1.
Read from the instrument’s own
Measurement Numbercolumn, which MPMS3 populates as1, 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__()andsummary(), andcalamari.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:
- 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
Nonerather than propagating: this method describes a file, including a problematic one.- Return type:
- 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 fromquality()n_flagged,max_continuity_scoreandn_status_departures(None when no point could be scored).
Notes
n_pointscounts 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_measurementsis 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 andscan_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, exceedsthreshold. 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. Defaultcalamari.quality.CONTINUITY_THRESHOLD(20), an empirical diagnostic default, not a calibrated false-alarm probability.- Returns:
- Raises:
ValueError – If
thresholdis 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. DefaultSCAN_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. DefaultSCAN_H_TOL_OE(10 Oe).
- Return type:
- 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 newMeasurementwith a shallow copy ofheaderand a re-indexed copy ofdata; the original object (and any other reference to it) is untouched.- Parameters:
t_range (
tuple[float,float] |None) – Inclusive(lo, hi)bounds (Kelvin) applied totemperature. RaisesValueErrorif given and this Measurement has no temperature column.h_range (
tuple[float,float] |None) – Inclusive(lo, hi)bounds (Oe) applied tofield_oe– NOTfield_tesla, matching the raw column’s native unit. RaisesValueErrorif given and this Measurement has no field column.mask (
object|None) – A boolean mask aligned positionally todata(i.e. its length must equallen(self.data)). Combined witht_range/h_rangeby logical AND when more than one filter is given.
- Return type:
- Returns:
calamari.measurement.Measurement– A new object whosedatacontains only the rows that pass every given filter, with a resetRangeIndex.headeris 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
temperaturefailst_range(so that row is excluded whenevert_rangeis given) but is untouched byh_rangeormask, and vice versa – this falls out naturally from pandas’ NaN-comparisons (NaN >= loandNaN <= hiare 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)dataDataFrame, not an error.