API Reference#
Python module that enables the import and handling of VSM-data acquired on a Quantum Design PPMS measurement system. Extrinsic magnetic properties can be calculated from M(H) hysteresis loops and exported to JSON- or CSV-files. Automatic plotting with matplotlib is also available.
- class magmeas.Sweep(description: str = '', **kwargs: mammos_entity.Entity | mammos_units.Quantity | numpy.typing.ArrayLike)[source]#
Bases:
EntityCollectionClass for importing, storing and using of magnetometric data aswell as derived parameters.
- read_custom(reader_func, *reader_args, **reader_kwargs)[source]#
Use a custom reader function and assign its output to self. This is intended to expand the file reading functionality of magmeas with custom functions for currently unsupported file types. It could however also be used to group several initialisation steps together, as all outputs of the custom reader function will be assigned to self without any checks. This doesn’t only have to be measurement data like the ExternalMagneticField but could also be sample information, already calculated properties or anything else.
The custom reader function `reader_func`is expected to return a single dictionary or mammos_entity.EntityCollection object. Its contents will be assigned to self without checks. It is strongly encouraged to only include mammos_entity.Entity objects in those output containers, since only those can later be used for magmeas-internal calculations. Please keep in mind, that some already present contents of self might be overwritten if the same keys are used.
Also returns self, so the following works:
some_data = magmeas.Sweep().read_custom(some_func, ‘path/to/file.DAT’)
- Parameters:
reader_func (FUNCTION) – The custom reader function which will return a dictionary or a mammos_entity.EntityCollection object with Entities that will be assigned to self.
reader_args (optional) – Arguments which will be passed to reader_func. This could for example be the path to a file which is supposed to be read.
reader_kwargs (optional) – Keyword arguments which will be passed to reader_func.
- read_PPMS(filepath)[source]#
Read VSM-data from a Quantum Design .DAT file generated with Quantum Designs PPMS, DynaCool or VersaLab devices and assign it to self. Also returns self, so the following works:
some_data = magmeas.Sweep().read_PPMS(‘path/to/file.DAT’)
- Parameters:
filepath (STR | PATH) – Path to Quantum Design .DAT file that data is supposed to be imported from
- Returns:
Returns self, see above.
- Return type:
SWEEP-like
- get_entity_key(ontology_label)[source]#
Check, whether collection contains entities of the given label and return their respective keys. If no entities of this label can be found, then None is returned.
- Parameters:
ontology_label (STR) – Ontology label of the entities for which the keys are supposed to be returned.
- Returns:
None if entities with the given ontology label could not be found, the key of the entity that had the specified label if only one was found or a list of all keys for which the respective entity has the specified ontology label.
- Return type:
STR | LIST[STR] | NONE
- calc_M(**kwargs)[source]#
Calculate Magnetization and MagneticPolarization and assign them to self with the respective keys ‘M’ and ‘J’. For this, self must contain one (and only one) Entity which has the ontology_label ‘MagneticMoment’ and one of the following:
an Entity with the ontology_label ‘Volume’
an Entity with the ontology_label ‘Mass’ AND one with ‘Density’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Volume’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the keys ‘M’ and ‘J’.
The following equations are used:
\[\begin{split}M &= \frac{\mu}{V}\\ J &= \mu _0 \cdot M\\ V &= m \cdot \rho\\ V &= l_1 \cdot l_2 \cdot l_3\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of M and J if they are relevant.
- Return type:
None
- corr_demag(**kwargs)[source]#
Correct the ExternalMagneticField for the demagnetising field created by the samples own Magnetization. This yields the InternalMagneticField, which will be assigned to self with the key ‘H’. For this, self must contain one (and only one) Entity which has the ontology_label ‘ExternalMagneticField’, another one with ‘Magnetization’ and one of the following:
an Entity with the ontology_label ‘DemagnetizingFactor’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid. The FIRST value in this Entity is assumed to be parallel to the direction of the ExternalMagneticField. The function mammos_analysis.demag.rectangular_cuboid will be used to calculate the DemagnetizingFactor of this rectangular cuboid. Doing so manually and only passing the relevant value as its own Entity with the ontology_label ‘DemagnetizingFactor’ like above is recommended.
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Length’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘H’.
The following equations are used:
\[H_{int} = H_{ext} - D \cdot M\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of H if they are relevant.
- Return type:
None
- calc_B(**kwargs)[source]#
Calculate MagneticFluxDensity and assign it to self with the key ‘B’. For this, self must contain one (and only one) Entity which has the ontology_label ‘InternalMagneticField’ and one of the following:
an Entity with the ontology_label ‘Magnetization’
an Entity with the ontology_label ‘MagneticPolarisation’
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Magnetization’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘B’. The following equations will be used:
\[\begin{split}B &= \mu _0 \cdot (H_{int} + M)\\ B &= \mu _0 \cdot H_{int} + J\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of B if they are relevant.
- Return type:
None
- plot(*args, filepath=None, bounds=None, fig_ax=None, segments=None, segments_kwargs=None, **kwargs)[source]#
Plot arguments and save figure if a filepath is given.
- Parameters:
args (STR | ENTITY | QUANTITY | ARRAY) – This determines the values to be plotted. Can only be comprised of one or two values. In the case of a string, it is first attempted to use it as a key for the values in self. If the string is not a key in self, then it is assumed to be an ontology_label and the entitity in self with the fitting ontology_label will be used. If more than one entities have a fitting ontology_label, this method fails. In the case of an Entity, a Quantity or an array, they are attempted to be plotted directly.
filepath (STR | PATH, optional) – Filepath for saving the figure. Default is None, in that case no file is saved and the generated figure as well as all axes objects are returned.
bounds (NONE | TUPLE(NONE | INT), optional) – Indices (start, end) at which the data to be plotted will be cut off. Use None to plot until the respective start or end. Default is None.
fig_ax (TUPLE(matplotlib.figure.Figure, matplotlib.axes.Axes), optional) – Tuple of figure and axes the data should be plotted to. If None is given they will be generated dynamically. Default is None.
segments (NONE | TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data to be plotted will be cut off. See the method self.segments for more information. Note that valid input here are only the indices FOR the output from the segments method and NOT the indices of the actual measurement points. Use None to plot until the respective start or end. Will be overwritten by bounds. If only None and no tuple is given, this will be ignored. Default is None.
segments_kwargs (NONE | DICT, optional) – Dictionary of keyword arguments that will be unpacked in the segments method of self, if self has one. See the respective method for more details. Defailt is None.
kwargs – Keyword arguments to change the appearance of plots. See documentation of matplotlib.pyplot.plot for more information.
- Returns:
Return figure and axes object if filepath is not specified.
- Return type:
None | (matplotlib.Figure, matplotlib.Axes)
- property description: str#
Additional description of the entity collection.
The description is a string containing any information relevant to the entity collection. This can include, e.g., whether it is a set of experimental or simulation quantities or outline the overall workflow.
- classmethod from_dataframe(dataframe: pandas.DataFrame, metadata: dict[str, dict], description: str = '') mammos_entity.EntityCollection#
Create EntityCollection from dataframe and metadata.
The EntityCollection is created by combining metadata with data from the dataframe matching key/column names. The available metadata determines whether an element becomes an
Entity, amammos_units.Quantityor a numpy array.All column names in the
dataframemust also exist as keys inmetadataand vice versa.In addition
metadatacan have a keydescriptioncontaining a description for the collection.- Parameters:
dataframe – A dataframe containing the values for the individual entities.
metadata – A dictionary with the structure similar to the one defined in
metadata(). The keysunitanddescriptionfor anEntityare however optional. If not present, default units from the ontology and an empty description are used.description – Description of the entity collection.
- metadata() dict[str, dict[str, str]]#
Get entity metadata as dictionary.
This method creates a dictionary containing metadata for all entities in the collection. Keys are names of the (entities) attributes of the collection, values are dictionaries with:
keys
ontology_label,unitanddescriptionif the attribute is an entitykey
unitif the attribute is a quantityan empty dictionary otherwise
Examples
>>> import mammos_entity as me >>> import mammos_units as u >>> col = me.EntityCollection("The description", Tc=me.Tc(), x=1 * u.m, a=0) >>> col.metadata() {'Tc': {'ontology_label': 'CurieTemperature', 'unit': 'K', 'description': ''}, 'x': {'unit': 'm'}, 'a': {}}
Changed in version 0.14.0: The collection description has been removed from the metadata to allow the name
descriptionas key for an entity-like.
- to_csv(filename: str | PathLike) None#
Write collection to CSV file.
CSV files contain data in normal CSV format and additional metadata lines at the top of the file. Some of the lines are commented with
#. This structure is fixed and additional comment lines or inline comments in the data table are not allowed.The lines are, in order:
(commented) the file version in the form
mammos csv v<VERSION>(matching regex vd+)(commented, optional) a description of the file, appearing delimited by dashed lines
(optional, only for entities) the preferred ontology label
(optional, only for entities) a description string
(optional, only for entities) the ontology IRI
(optional, for entities and quantities) units
the short labels used to refer to individual columns when working with the data, e.g. in a
pandas.DataFrame(omitting spaces in this string is advisable; ideally this string is the short ontology label)all remaining lines contain data.
Elements in a line are separated by a comma without any surrounding whitespace. A trailing comma is not permitted. Line continuation is OS dependent (rn on Windows, n on Unix).
In columns without ontology the lines containing labels, IRIs, and description are empty.
Similarly, columns without units (with or without ontology entry) have empty units line.
For any column, the description line can be empty. Only entities can store descriptions, i.e., if the ontology-related lines are empty, the description string will not be read.
Added in version v2: The optional description of the file.
Added in version v3: Additional description metadata row containing a description for each column.
Changed in version v3: Ontology labels, entity descriptions, IRIs, and units are no longer commented.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the entities are not tabular. CSV files can only be written for collections in which all entities are either scalar or one-dimenisional with the same length.
ValueError – If elements of the collection are of type
EntityCollection(nested collections are not supported in CSV) or if the collection is empty.
Examples
Here is an example with five columns:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology label
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... ) >>> collection.to_csv("example.csv")
The new file has the following content:
>>> print(Path("example.csv").read_text()) # mammos csv v3 #---------------------------------------- # Test data #---------------------------------------- ,SpontaneousMagnetization,,DemagnetizingFactor, ,Magnetization at 0 Kelvin,,, ,https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25,,https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e, ,kA / m,s2,, index,Ms,alpha,DemagnetizingFactor,comment 0,100.0,1.2,1.0,Comment in the first row 1,100.0,3.4,0.5,Comment in the second row 2,100.0,5.6,0.5,Comment in the third row
Finally, remove the file.
>>> Path("example.csv").unlink()
- to_dataframe(include_units: bool = False) pandas.DataFrame#
Convert values to dataframe.
- Parameters:
include_units – If true, include units in the dataframe column names.
- to_hdf5(base: File | Group | str | PathLike, name: str | None = None) Group | None#
Write a collection to an HDF5 group.
The HDF5 structure is:
The collection is stored as an HDF5 group.
The collection description is written to the group’s
descriptionattribute.Each element of the collection becomes a child of the group: -
Entityobjects are stored as HDF5 datasetswith attributes
ontology_label,ontology_iri,unit,description(seemammos_entity.Entity.to_hdf5()).Quantityobjects are stored as datasets with aunitattribute.Plain values are stored as datasets without mammos-specific attributes.
Nested
EntityCollectionobjects become nested HDF5 groups (recursive structure).
The outermost group has an additional attribute
mammos_entity_version.
- Parameters:
base – If it is an open HDF5 file or a group in an HDF5 file, data will be added to it as new group. If it is a str or PathLike a new HDF5 file with the given name will be created. If a file with that name exists already, it will be overwritten without notice.
name – Name for the newly created group. If an element with that name exists already in base the function will fail. If
nameisNoneentities of the collection will be added directly tobaseand the collection description will be added tobaseattributes.
- Returns:
If
baseis an openFileorGroupthe newly created group. If base is a file name nothing is returned (because the file created internally will be closed before the function returns).
See also
mammos_entity.Entity.to_hdf5()mammos_entity.from_hdf5()
- to_yaml(filename: str | PathLike) None#
Write collection to YAML file.
MaMMoS YAML files have the following format:
one commented line at the top of the file containing the mammos format version in the form
# mammos yaml v<version-number>.a mapping with three top-level keys
metadata,descriptionanddatametadatais currently unused and should be emptythe
descriptionkey contains a (multi-line) string with arbitrary content describing the top-level collectiondatacontains one key per element in the collection. Each entry is either an entity-like entry or a nested collection node.
Collection nodes are recursive and have two keys
descriptionanddata:description: a (multi-line) string with arbitrary contentdata: mapping from entry names to entity-like entries or nested collection nodes
Entity-like entries have the following keys:
For
Entity:ontology_label: label in the ontologydescription: description stringontology_iri: IRI of the entityunit: unit of the entity (""for dimensionless)value: value of the data
For
Quantity:unit: unit of the quantityvalue: value of the data
For any other value:
value: value of the data
Added in version v2: The
descriptionkey for each object.Changed in version v2:
The version of the file is now stored in the first commented line, previously it was stored in
metadata:description.The top-level collection description is stored under
description(next tometadataanddata). Previously it was stored inmetadata:description.Non-entity entries no longer store null-valued ontology keys.
Nested collections are supported recursively.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the top-level collection is empty.
Examples
Here is an example with six entries:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology labelan element Tc with only a single value
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... Tc=me.Tc(300, "K"), ... ) >>> collection.to_yaml("example.yaml")
The new file has the following content:
>>> print(Path("example.yaml").read_text()) # mammos yaml v2 metadata: null description: Test data data: index: value: [0, 1, 2] Ms: ontology_label: SpontaneousMagnetization description: Magnetization at 0 Kelvin ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: [100.0, 100.0, 100.0] alpha: unit: s2 value: [1.2, 3.4, 5.6] DemagnetizingFactor: ontology_label: DemagnetizingFactor description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e unit: '' value: [1.0, 0.5, 0.5] comment: value: [Comment in the first row, Comment in the second row, Comment in the third row] Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 300.0
>>> Path("example.yaml").unlink()
Here is a second example with one outer and one inner collection:
>>> properties = me.EntityCollection( ... description="material properties", ... Ms=me.Ms(1.3e3, "kA/m"), ... Tc=me.Tc(1043, "K"), ... ) >>> measurement = me.EntityCollection( ... description="measurement with device X", ... sample=properties, ... T=me.T(300, "K", description="Measurement conditions"), ... H=me.H([0, 50, 100], "kA/m"), ... M=me.M([100, 300, 500], "kA/m"), ... ) >>> measurement.to_yaml("nested_example.yaml") >>> print(Path("nested_example.yaml").read_text()) # mammos yaml v2 metadata: null description: measurement with device X data: sample: description: material properties data: Ms: ontology_label: SpontaneousMagnetization description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: 1300.0 Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 1043.0 T: ontology_label: ThermodynamicTemperature description: Measurement conditions ontology_iri: https://w3id.org/emmo#EMMO_affe07e4_e9bc_4852_86c6_69e26182a17f unit: K value: 300.0 H: ontology_label: ExternalMagneticField description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_da08f0d3-fe19-58bc-8fb6-ecc8992d5eb3 unit: kA / m value: [0.0, 50.0, 100.0] M: ontology_label: Magnetization description: '' ontology_iri: https://w3id.org/emmo#EMMO_b23e7251_a488_4732_8268_027ad76d7e37 unit: kA / m value: [100.0, 300.0, 500.0]
>>> Path("nested_example.yaml").unlink()
- class magmeas.MH_major(description: str = '', **kwargs: mammos_entity.Entity | mammos_units.Quantity | numpy.typing.ArrayLike)[source]#
Bases:
SweepClass for importing, storing and using of magnetometric data from major hysteresis loop M(H) measurements aswell as derived properties.
- calc_properties(demag_only=False, **kwargs)[source]#
Calculate extrinsic magnetic properties from the demagnetisation curve
- Parameters:
demag_only (BOOL, optional) – Whether the dataset in self only contains the demagnetisation curve and no initial magnetisation. This affects the number of expected segmentation points in the dataset (see self.segments). Default is False.
kwargs (optional) – Keyword arguments used for the segmentation. See MH_major.segments for more details
- Return type:
None
- calc_Hk(**kwargs)[source]#
Calculate kneefield of demagnetization curve. The knee field strength is the internal magnetic field at which the magnetization in the demagnetization curve is reduced to 90 % of the remanence.
- Parameters:
kwargs (optional) – Keyword arguments used for the segmentation. See MH_major.segments for more details
- Returns:
Hk – Knee field strength as mammos_entity.Entity
- Return type:
ENTITY
- calc_SF()[source]#
Calculate squareness of demagnetization curve.
\[S = \frac{H_K}{H_C}\]- Parameters:
None
- Returns:
S – Squareness (dimensionless)
- Return type:
FLOAT
- estimate_saturation(threshold=None)[source]#
Calculate an estimation of the saturation magnetisation, return it and simultaneously assign it to the self. A possible high field susceptibility can optionally be corrected for.
- Parameters:
threshold (NONE | FLOAT, optional) – If a float instead of None is given, the saturation value will be corrected for a high field susceptibility by substracting any inclination at magnetisation values above the maximum field times the threshold factor. The saturation magnetisation is then the y-intersection from extrapolating M over 1/H to 0. Default value is None.
- Returns:
Ms – Saturation magnetisation.
- Return type:
ENTITY
- segments(edge_frac=0.05, prominence=1000000.0, **kwargs)[source]#
Find indices of segmentation points which can be used to seperate each measurement segment from each other. The segments are seperated by a changing sign of M (root) or a changing sign of dH/dt (peak). The segmentation points are chosen to be the index right after the root and right at the peak. Segmentation points with even indices (including 0) are peaks while segmentation points with uneven indices are roots.
- Parameters:
edge_frac (FLOAT, optional) – Percentage of measurement to be treated as edge. Default is 0.05, which means that segmentation points closer than 5 % of the total measurement width to the edges will be discarded.
prominence (FLOAT, optional) – The prominence which is used to find all peaks in H_ext(t). See the documentation of scipy.signal.find_peaks for more details. The default is 1e6.
kwargs (optional) – Additional keyword arguments that can be used for peak finding. See scipy.signal.find_peaks for more details
- Returns:
s – Array of segmentation points that can be used to segmentise the measurement.
- Return type:
ARRAY[INT]
- calc_B(**kwargs)#
Calculate MagneticFluxDensity and assign it to self with the key ‘B’. For this, self must contain one (and only one) Entity which has the ontology_label ‘InternalMagneticField’ and one of the following:
an Entity with the ontology_label ‘Magnetization’
an Entity with the ontology_label ‘MagneticPolarisation’
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Magnetization’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘B’. The following equations will be used:
\[\begin{split}B &= \mu _0 \cdot (H_{int} + M)\\ B &= \mu _0 \cdot H_{int} + J\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of B if they are relevant.
- Return type:
None
- calc_M(**kwargs)#
Calculate Magnetization and MagneticPolarization and assign them to self with the respective keys ‘M’ and ‘J’. For this, self must contain one (and only one) Entity which has the ontology_label ‘MagneticMoment’ and one of the following:
an Entity with the ontology_label ‘Volume’
an Entity with the ontology_label ‘Mass’ AND one with ‘Density’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Volume’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the keys ‘M’ and ‘J’.
The following equations are used:
\[\begin{split}M &= \frac{\mu}{V}\\ J &= \mu _0 \cdot M\\ V &= m \cdot \rho\\ V &= l_1 \cdot l_2 \cdot l_3\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of M and J if they are relevant.
- Return type:
None
- corr_demag(**kwargs)#
Correct the ExternalMagneticField for the demagnetising field created by the samples own Magnetization. This yields the InternalMagneticField, which will be assigned to self with the key ‘H’. For this, self must contain one (and only one) Entity which has the ontology_label ‘ExternalMagneticField’, another one with ‘Magnetization’ and one of the following:
an Entity with the ontology_label ‘DemagnetizingFactor’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid. The FIRST value in this Entity is assumed to be parallel to the direction of the ExternalMagneticField. The function mammos_analysis.demag.rectangular_cuboid will be used to calculate the DemagnetizingFactor of this rectangular cuboid. Doing so manually and only passing the relevant value as its own Entity with the ontology_label ‘DemagnetizingFactor’ like above is recommended.
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Length’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘H’.
The following equations are used:
\[H_{int} = H_{ext} - D \cdot M\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of H if they are relevant.
- Return type:
None
- property description: str#
Additional description of the entity collection.
The description is a string containing any information relevant to the entity collection. This can include, e.g., whether it is a set of experimental or simulation quantities or outline the overall workflow.
- classmethod from_dataframe(dataframe: pandas.DataFrame, metadata: dict[str, dict], description: str = '') mammos_entity.EntityCollection#
Create EntityCollection from dataframe and metadata.
The EntityCollection is created by combining metadata with data from the dataframe matching key/column names. The available metadata determines whether an element becomes an
Entity, amammos_units.Quantityor a numpy array.All column names in the
dataframemust also exist as keys inmetadataand vice versa.In addition
metadatacan have a keydescriptioncontaining a description for the collection.- Parameters:
dataframe – A dataframe containing the values for the individual entities.
metadata – A dictionary with the structure similar to the one defined in
metadata(). The keysunitanddescriptionfor anEntityare however optional. If not present, default units from the ontology and an empty description are used.description – Description of the entity collection.
- get_entity_key(ontology_label)#
Check, whether collection contains entities of the given label and return their respective keys. If no entities of this label can be found, then None is returned.
- Parameters:
ontology_label (STR) – Ontology label of the entities for which the keys are supposed to be returned.
- Returns:
None if entities with the given ontology label could not be found, the key of the entity that had the specified label if only one was found or a list of all keys for which the respective entity has the specified ontology label.
- Return type:
STR | LIST[STR] | NONE
- metadata() dict[str, dict[str, str]]#
Get entity metadata as dictionary.
This method creates a dictionary containing metadata for all entities in the collection. Keys are names of the (entities) attributes of the collection, values are dictionaries with:
keys
ontology_label,unitanddescriptionif the attribute is an entitykey
unitif the attribute is a quantityan empty dictionary otherwise
Examples
>>> import mammos_entity as me >>> import mammos_units as u >>> col = me.EntityCollection("The description", Tc=me.Tc(), x=1 * u.m, a=0) >>> col.metadata() {'Tc': {'ontology_label': 'CurieTemperature', 'unit': 'K', 'description': ''}, 'x': {'unit': 'm'}, 'a': {}}
Changed in version 0.14.0: The collection description has been removed from the metadata to allow the name
descriptionas key for an entity-like.
- plot(*args, filepath=None, bounds=None, fig_ax=None, segments=None, segments_kwargs=None, **kwargs)#
Plot arguments and save figure if a filepath is given.
- Parameters:
args (STR | ENTITY | QUANTITY | ARRAY) – This determines the values to be plotted. Can only be comprised of one or two values. In the case of a string, it is first attempted to use it as a key for the values in self. If the string is not a key in self, then it is assumed to be an ontology_label and the entitity in self with the fitting ontology_label will be used. If more than one entities have a fitting ontology_label, this method fails. In the case of an Entity, a Quantity or an array, they are attempted to be plotted directly.
filepath (STR | PATH, optional) – Filepath for saving the figure. Default is None, in that case no file is saved and the generated figure as well as all axes objects are returned.
bounds (NONE | TUPLE(NONE | INT), optional) – Indices (start, end) at which the data to be plotted will be cut off. Use None to plot until the respective start or end. Default is None.
fig_ax (TUPLE(matplotlib.figure.Figure, matplotlib.axes.Axes), optional) – Tuple of figure and axes the data should be plotted to. If None is given they will be generated dynamically. Default is None.
segments (NONE | TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data to be plotted will be cut off. See the method self.segments for more information. Note that valid input here are only the indices FOR the output from the segments method and NOT the indices of the actual measurement points. Use None to plot until the respective start or end. Will be overwritten by bounds. If only None and no tuple is given, this will be ignored. Default is None.
segments_kwargs (NONE | DICT, optional) – Dictionary of keyword arguments that will be unpacked in the segments method of self, if self has one. See the respective method for more details. Defailt is None.
kwargs – Keyword arguments to change the appearance of plots. See documentation of matplotlib.pyplot.plot for more information.
- Returns:
Return figure and axes object if filepath is not specified.
- Return type:
None | (matplotlib.Figure, matplotlib.Axes)
- read_PPMS(filepath)#
Read VSM-data from a Quantum Design .DAT file generated with Quantum Designs PPMS, DynaCool or VersaLab devices and assign it to self. Also returns self, so the following works:
some_data = magmeas.Sweep().read_PPMS(‘path/to/file.DAT’)
- Parameters:
filepath (STR | PATH) – Path to Quantum Design .DAT file that data is supposed to be imported from
- Returns:
Returns self, see above.
- Return type:
SWEEP-like
- read_custom(reader_func, *reader_args, **reader_kwargs)#
Use a custom reader function and assign its output to self. This is intended to expand the file reading functionality of magmeas with custom functions for currently unsupported file types. It could however also be used to group several initialisation steps together, as all outputs of the custom reader function will be assigned to self without any checks. This doesn’t only have to be measurement data like the ExternalMagneticField but could also be sample information, already calculated properties or anything else.
The custom reader function `reader_func`is expected to return a single dictionary or mammos_entity.EntityCollection object. Its contents will be assigned to self without checks. It is strongly encouraged to only include mammos_entity.Entity objects in those output containers, since only those can later be used for magmeas-internal calculations. Please keep in mind, that some already present contents of self might be overwritten if the same keys are used.
Also returns self, so the following works:
some_data = magmeas.Sweep().read_custom(some_func, ‘path/to/file.DAT’)
- Parameters:
reader_func (FUNCTION) – The custom reader function which will return a dictionary or a mammos_entity.EntityCollection object with Entities that will be assigned to self.
reader_args (optional) – Arguments which will be passed to reader_func. This could for example be the path to a file which is supposed to be read.
reader_kwargs (optional) – Keyword arguments which will be passed to reader_func.
- to_csv(filename: str | PathLike) None#
Write collection to CSV file.
CSV files contain data in normal CSV format and additional metadata lines at the top of the file. Some of the lines are commented with
#. This structure is fixed and additional comment lines or inline comments in the data table are not allowed.The lines are, in order:
(commented) the file version in the form
mammos csv v<VERSION>(matching regex vd+)(commented, optional) a description of the file, appearing delimited by dashed lines
(optional, only for entities) the preferred ontology label
(optional, only for entities) a description string
(optional, only for entities) the ontology IRI
(optional, for entities and quantities) units
the short labels used to refer to individual columns when working with the data, e.g. in a
pandas.DataFrame(omitting spaces in this string is advisable; ideally this string is the short ontology label)all remaining lines contain data.
Elements in a line are separated by a comma without any surrounding whitespace. A trailing comma is not permitted. Line continuation is OS dependent (rn on Windows, n on Unix).
In columns without ontology the lines containing labels, IRIs, and description are empty.
Similarly, columns without units (with or without ontology entry) have empty units line.
For any column, the description line can be empty. Only entities can store descriptions, i.e., if the ontology-related lines are empty, the description string will not be read.
Added in version v2: The optional description of the file.
Added in version v3: Additional description metadata row containing a description for each column.
Changed in version v3: Ontology labels, entity descriptions, IRIs, and units are no longer commented.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the entities are not tabular. CSV files can only be written for collections in which all entities are either scalar or one-dimenisional with the same length.
ValueError – If elements of the collection are of type
EntityCollection(nested collections are not supported in CSV) or if the collection is empty.
Examples
Here is an example with five columns:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology label
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... ) >>> collection.to_csv("example.csv")
The new file has the following content:
>>> print(Path("example.csv").read_text()) # mammos csv v3 #---------------------------------------- # Test data #---------------------------------------- ,SpontaneousMagnetization,,DemagnetizingFactor, ,Magnetization at 0 Kelvin,,, ,https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25,,https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e, ,kA / m,s2,, index,Ms,alpha,DemagnetizingFactor,comment 0,100.0,1.2,1.0,Comment in the first row 1,100.0,3.4,0.5,Comment in the second row 2,100.0,5.6,0.5,Comment in the third row
Finally, remove the file.
>>> Path("example.csv").unlink()
- to_dataframe(include_units: bool = False) pandas.DataFrame#
Convert values to dataframe.
- Parameters:
include_units – If true, include units in the dataframe column names.
- to_hdf5(base: File | Group | str | PathLike, name: str | None = None) Group | None#
Write a collection to an HDF5 group.
The HDF5 structure is:
The collection is stored as an HDF5 group.
The collection description is written to the group’s
descriptionattribute.Each element of the collection becomes a child of the group: -
Entityobjects are stored as HDF5 datasetswith attributes
ontology_label,ontology_iri,unit,description(seemammos_entity.Entity.to_hdf5()).Quantityobjects are stored as datasets with aunitattribute.Plain values are stored as datasets without mammos-specific attributes.
Nested
EntityCollectionobjects become nested HDF5 groups (recursive structure).
The outermost group has an additional attribute
mammos_entity_version.
- Parameters:
base – If it is an open HDF5 file or a group in an HDF5 file, data will be added to it as new group. If it is a str or PathLike a new HDF5 file with the given name will be created. If a file with that name exists already, it will be overwritten without notice.
name – Name for the newly created group. If an element with that name exists already in base the function will fail. If
nameisNoneentities of the collection will be added directly tobaseand the collection description will be added tobaseattributes.
- Returns:
If
baseis an openFileorGroupthe newly created group. If base is a file name nothing is returned (because the file created internally will be closed before the function returns).
See also
mammos_entity.Entity.to_hdf5()mammos_entity.from_hdf5()
- to_yaml(filename: str | PathLike) None#
Write collection to YAML file.
MaMMoS YAML files have the following format:
one commented line at the top of the file containing the mammos format version in the form
# mammos yaml v<version-number>.a mapping with three top-level keys
metadata,descriptionanddatametadatais currently unused and should be emptythe
descriptionkey contains a (multi-line) string with arbitrary content describing the top-level collectiondatacontains one key per element in the collection. Each entry is either an entity-like entry or a nested collection node.
Collection nodes are recursive and have two keys
descriptionanddata:description: a (multi-line) string with arbitrary contentdata: mapping from entry names to entity-like entries or nested collection nodes
Entity-like entries have the following keys:
For
Entity:ontology_label: label in the ontologydescription: description stringontology_iri: IRI of the entityunit: unit of the entity (""for dimensionless)value: value of the data
For
Quantity:unit: unit of the quantityvalue: value of the data
For any other value:
value: value of the data
Added in version v2: The
descriptionkey for each object.Changed in version v2:
The version of the file is now stored in the first commented line, previously it was stored in
metadata:description.The top-level collection description is stored under
description(next tometadataanddata). Previously it was stored inmetadata:description.Non-entity entries no longer store null-valued ontology keys.
Nested collections are supported recursively.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the top-level collection is empty.
Examples
Here is an example with six entries:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology labelan element Tc with only a single value
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... Tc=me.Tc(300, "K"), ... ) >>> collection.to_yaml("example.yaml")
The new file has the following content:
>>> print(Path("example.yaml").read_text()) # mammos yaml v2 metadata: null description: Test data data: index: value: [0, 1, 2] Ms: ontology_label: SpontaneousMagnetization description: Magnetization at 0 Kelvin ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: [100.0, 100.0, 100.0] alpha: unit: s2 value: [1.2, 3.4, 5.6] DemagnetizingFactor: ontology_label: DemagnetizingFactor description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e unit: '' value: [1.0, 0.5, 0.5] comment: value: [Comment in the first row, Comment in the second row, Comment in the third row] Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 300.0
>>> Path("example.yaml").unlink()
Here is a second example with one outer and one inner collection:
>>> properties = me.EntityCollection( ... description="material properties", ... Ms=me.Ms(1.3e3, "kA/m"), ... Tc=me.Tc(1043, "K"), ... ) >>> measurement = me.EntityCollection( ... description="measurement with device X", ... sample=properties, ... T=me.T(300, "K", description="Measurement conditions"), ... H=me.H([0, 50, 100], "kA/m"), ... M=me.M([100, 300, 500], "kA/m"), ... ) >>> measurement.to_yaml("nested_example.yaml") >>> print(Path("nested_example.yaml").read_text()) # mammos yaml v2 metadata: null description: measurement with device X data: sample: description: material properties data: Ms: ontology_label: SpontaneousMagnetization description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: 1300.0 Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 1043.0 T: ontology_label: ThermodynamicTemperature description: Measurement conditions ontology_iri: https://w3id.org/emmo#EMMO_affe07e4_e9bc_4852_86c6_69e26182a17f unit: K value: 300.0 H: ontology_label: ExternalMagneticField description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_da08f0d3-fe19-58bc-8fb6-ecc8992d5eb3 unit: kA / m value: [0.0, 50.0, 100.0] M: ontology_label: Magnetization description: '' ontology_iri: https://w3id.org/emmo#EMMO_b23e7251_a488_4732_8268_027ad76d7e37 unit: kA / m value: [100.0, 300.0, 500.0]
>>> Path("nested_example.yaml").unlink()
- class magmeas.MH_recoil(description: str = '', **kwargs: mammos_entity.Entity | mammos_units.Quantity | numpy.typing.ArrayLike)[source]#
Bases:
SweepClass for importing, storing and using of magnetometric data from recoil loop M(H) measurements. Recoil loop measurements are assumed to be measurements where the sample is first saturated at some positive field. After this, a number of recoil loops are performed, where the magnetic field is reduced to some negative value (which often includes fields that do not fully demagnetise the sample) and is then increased to an external field of 0 or to a positive external field which increases the internal field to 0.
- segments(edge_frac=0.01, prominence=5000.0, **kwargs)[source]#
Get indices of segmentation points. Segmentation point 0 occurs at H = H_max. All uneven segmentation points are the start of a recoil loop (only section with positive change in H) while all subsequent even segmentation points are the respective ends of each recoil loop.
- Parameters:
edge_frac (FLOAT, optional) – Percentage of measurement to be treated as edge. Default is 0.05, which means that segmentation points closer than 5 % of the total measurement width to the edges will be discarded.
prominence (FLOAT, optional) – The prominence which is used to find all peaks in H_ext(t). See the documentation of scipy.signal.find_peaks for more details. The default is 5e3.
kwargs (optional) – Additional keyword arguments that can be used for peak finding. See scipy.signal.find_peaks for more details
- Returns:
segments – Segmentation points used to extract each recoil loop.
- Return type:
ARRAY
- recoil_susceptibility(prominence=5000.0, take_mean=True)[source]#
Calculate recoil susceptibility from recoil loop measurement as slope of a linear regression of each recoil loop.
- Parameters:
prominence (FLOAT, optional) – Prominence used to find segmentation points, see MH_recoil.segments The default is 5e3.
take_mean (BOOL, optional) – Wether to take the mean of all recoil susceptibilities instead of returning an individual one for each loop. Default is True.
- Returns:
recoil_susceptibility – Recoil susceptibility calculated from recoil loop measurement.
- Return type:
FLOAT | ARRAY
- external_comp_field(demag_fields=None, prominence=5000.0)[source]#
Return external compensation fields, that will lead to an endpoint close to an internal magnetic field of zero for each recoil loop. This only makes sense to be calculated from recoil loop measurements, where the endpoint for each recoil loop was an external magnetic field of 0, which will lead to the respective internal magnetic field being non-zero. The external compensation fields can then be used in a new measurement which will then enable a recoil loop measurement corrected for demagnetisation.n External compensation field is calculated from the internal recoil fields (at the end of each recoil loop) and the recoil susceptibility according to:
\[H^e_{comp} = \frac{- H^i_{recoil}}{1 - D * \chi_{recoil}}\]- Parameters:
demag_fields (NONE | QUANTITY | ARRAY, optional) – If None, then the external compensation fields will be calculated for each recoil loop of the given MH_recoil object. Otherwise an array of external demagnetising fields can be given, which will be the start of each recoil loop for which the external compensation field is calculated. Must be given as a Quantity, otherwise its unit is assumed to be A/m. Default is None.
prominence (FLOAT, optional) – Prominence used to find segmentation points, see MH_recoil.segments The default is 5e3.
- Returns:
external_compensation_field – External compensation fields, that would lead to an internal field close to zero at the end of each recoil loop.
- Return type:
ARRAY
- calc_B(**kwargs)#
Calculate MagneticFluxDensity and assign it to self with the key ‘B’. For this, self must contain one (and only one) Entity which has the ontology_label ‘InternalMagneticField’ and one of the following:
an Entity with the ontology_label ‘Magnetization’
an Entity with the ontology_label ‘MagneticPolarisation’
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Magnetization’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘B’. The following equations will be used:
\[\begin{split}B &= \mu _0 \cdot (H_{int} + M)\\ B &= \mu _0 \cdot H_{int} + J\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of B if they are relevant.
- Return type:
None
- calc_M(**kwargs)#
Calculate Magnetization and MagneticPolarization and assign them to self with the respective keys ‘M’ and ‘J’. For this, self must contain one (and only one) Entity which has the ontology_label ‘MagneticMoment’ and one of the following:
an Entity with the ontology_label ‘Volume’
an Entity with the ontology_label ‘Mass’ AND one with ‘Density’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Volume’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the keys ‘M’ and ‘J’.
The following equations are used:
\[\begin{split}M &= \frac{\mu}{V}\\ J &= \mu _0 \cdot M\\ V &= m \cdot \rho\\ V &= l_1 \cdot l_2 \cdot l_3\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of M and J if they are relevant.
- Return type:
None
- corr_demag(**kwargs)#
Correct the ExternalMagneticField for the demagnetising field created by the samples own Magnetization. This yields the InternalMagneticField, which will be assigned to self with the key ‘H’. For this, self must contain one (and only one) Entity which has the ontology_label ‘ExternalMagneticField’, another one with ‘Magnetization’ and one of the following:
an Entity with the ontology_label ‘DemagnetizingFactor’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid. The FIRST value in this Entity is assumed to be parallel to the direction of the ExternalMagneticField. The function mammos_analysis.demag.rectangular_cuboid will be used to calculate the DemagnetizingFactor of this rectangular cuboid. Doing so manually and only passing the relevant value as its own Entity with the ontology_label ‘DemagnetizingFactor’ like above is recommended.
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Length’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘H’.
The following equations are used:
\[H_{int} = H_{ext} - D \cdot M\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of H if they are relevant.
- Return type:
None
- property description: str#
Additional description of the entity collection.
The description is a string containing any information relevant to the entity collection. This can include, e.g., whether it is a set of experimental or simulation quantities or outline the overall workflow.
- classmethod from_dataframe(dataframe: pandas.DataFrame, metadata: dict[str, dict], description: str = '') mammos_entity.EntityCollection#
Create EntityCollection from dataframe and metadata.
The EntityCollection is created by combining metadata with data from the dataframe matching key/column names. The available metadata determines whether an element becomes an
Entity, amammos_units.Quantityor a numpy array.All column names in the
dataframemust also exist as keys inmetadataand vice versa.In addition
metadatacan have a keydescriptioncontaining a description for the collection.- Parameters:
dataframe – A dataframe containing the values for the individual entities.
metadata – A dictionary with the structure similar to the one defined in
metadata(). The keysunitanddescriptionfor anEntityare however optional. If not present, default units from the ontology and an empty description are used.description – Description of the entity collection.
- get_entity_key(ontology_label)#
Check, whether collection contains entities of the given label and return their respective keys. If no entities of this label can be found, then None is returned.
- Parameters:
ontology_label (STR) – Ontology label of the entities for which the keys are supposed to be returned.
- Returns:
None if entities with the given ontology label could not be found, the key of the entity that had the specified label if only one was found or a list of all keys for which the respective entity has the specified ontology label.
- Return type:
STR | LIST[STR] | NONE
- metadata() dict[str, dict[str, str]]#
Get entity metadata as dictionary.
This method creates a dictionary containing metadata for all entities in the collection. Keys are names of the (entities) attributes of the collection, values are dictionaries with:
keys
ontology_label,unitanddescriptionif the attribute is an entitykey
unitif the attribute is a quantityan empty dictionary otherwise
Examples
>>> import mammos_entity as me >>> import mammos_units as u >>> col = me.EntityCollection("The description", Tc=me.Tc(), x=1 * u.m, a=0) >>> col.metadata() {'Tc': {'ontology_label': 'CurieTemperature', 'unit': 'K', 'description': ''}, 'x': {'unit': 'm'}, 'a': {}}
Changed in version 0.14.0: The collection description has been removed from the metadata to allow the name
descriptionas key for an entity-like.
- plot(*args, filepath=None, bounds=None, fig_ax=None, segments=None, segments_kwargs=None, **kwargs)#
Plot arguments and save figure if a filepath is given.
- Parameters:
args (STR | ENTITY | QUANTITY | ARRAY) – This determines the values to be plotted. Can only be comprised of one or two values. In the case of a string, it is first attempted to use it as a key for the values in self. If the string is not a key in self, then it is assumed to be an ontology_label and the entitity in self with the fitting ontology_label will be used. If more than one entities have a fitting ontology_label, this method fails. In the case of an Entity, a Quantity or an array, they are attempted to be plotted directly.
filepath (STR | PATH, optional) – Filepath for saving the figure. Default is None, in that case no file is saved and the generated figure as well as all axes objects are returned.
bounds (NONE | TUPLE(NONE | INT), optional) – Indices (start, end) at which the data to be plotted will be cut off. Use None to plot until the respective start or end. Default is None.
fig_ax (TUPLE(matplotlib.figure.Figure, matplotlib.axes.Axes), optional) – Tuple of figure and axes the data should be plotted to. If None is given they will be generated dynamically. Default is None.
segments (NONE | TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data to be plotted will be cut off. See the method self.segments for more information. Note that valid input here are only the indices FOR the output from the segments method and NOT the indices of the actual measurement points. Use None to plot until the respective start or end. Will be overwritten by bounds. If only None and no tuple is given, this will be ignored. Default is None.
segments_kwargs (NONE | DICT, optional) – Dictionary of keyword arguments that will be unpacked in the segments method of self, if self has one. See the respective method for more details. Defailt is None.
kwargs – Keyword arguments to change the appearance of plots. See documentation of matplotlib.pyplot.plot for more information.
- Returns:
Return figure and axes object if filepath is not specified.
- Return type:
None | (matplotlib.Figure, matplotlib.Axes)
- read_PPMS(filepath)#
Read VSM-data from a Quantum Design .DAT file generated with Quantum Designs PPMS, DynaCool or VersaLab devices and assign it to self. Also returns self, so the following works:
some_data = magmeas.Sweep().read_PPMS(‘path/to/file.DAT’)
- Parameters:
filepath (STR | PATH) – Path to Quantum Design .DAT file that data is supposed to be imported from
- Returns:
Returns self, see above.
- Return type:
SWEEP-like
- read_custom(reader_func, *reader_args, **reader_kwargs)#
Use a custom reader function and assign its output to self. This is intended to expand the file reading functionality of magmeas with custom functions for currently unsupported file types. It could however also be used to group several initialisation steps together, as all outputs of the custom reader function will be assigned to self without any checks. This doesn’t only have to be measurement data like the ExternalMagneticField but could also be sample information, already calculated properties or anything else.
The custom reader function `reader_func`is expected to return a single dictionary or mammos_entity.EntityCollection object. Its contents will be assigned to self without checks. It is strongly encouraged to only include mammos_entity.Entity objects in those output containers, since only those can later be used for magmeas-internal calculations. Please keep in mind, that some already present contents of self might be overwritten if the same keys are used.
Also returns self, so the following works:
some_data = magmeas.Sweep().read_custom(some_func, ‘path/to/file.DAT’)
- Parameters:
reader_func (FUNCTION) – The custom reader function which will return a dictionary or a mammos_entity.EntityCollection object with Entities that will be assigned to self.
reader_args (optional) – Arguments which will be passed to reader_func. This could for example be the path to a file which is supposed to be read.
reader_kwargs (optional) – Keyword arguments which will be passed to reader_func.
- to_csv(filename: str | PathLike) None#
Write collection to CSV file.
CSV files contain data in normal CSV format and additional metadata lines at the top of the file. Some of the lines are commented with
#. This structure is fixed and additional comment lines or inline comments in the data table are not allowed.The lines are, in order:
(commented) the file version in the form
mammos csv v<VERSION>(matching regex vd+)(commented, optional) a description of the file, appearing delimited by dashed lines
(optional, only for entities) the preferred ontology label
(optional, only for entities) a description string
(optional, only for entities) the ontology IRI
(optional, for entities and quantities) units
the short labels used to refer to individual columns when working with the data, e.g. in a
pandas.DataFrame(omitting spaces in this string is advisable; ideally this string is the short ontology label)all remaining lines contain data.
Elements in a line are separated by a comma without any surrounding whitespace. A trailing comma is not permitted. Line continuation is OS dependent (rn on Windows, n on Unix).
In columns without ontology the lines containing labels, IRIs, and description are empty.
Similarly, columns without units (with or without ontology entry) have empty units line.
For any column, the description line can be empty. Only entities can store descriptions, i.e., if the ontology-related lines are empty, the description string will not be read.
Added in version v2: The optional description of the file.
Added in version v3: Additional description metadata row containing a description for each column.
Changed in version v3: Ontology labels, entity descriptions, IRIs, and units are no longer commented.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the entities are not tabular. CSV files can only be written for collections in which all entities are either scalar or one-dimenisional with the same length.
ValueError – If elements of the collection are of type
EntityCollection(nested collections are not supported in CSV) or if the collection is empty.
Examples
Here is an example with five columns:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology label
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... ) >>> collection.to_csv("example.csv")
The new file has the following content:
>>> print(Path("example.csv").read_text()) # mammos csv v3 #---------------------------------------- # Test data #---------------------------------------- ,SpontaneousMagnetization,,DemagnetizingFactor, ,Magnetization at 0 Kelvin,,, ,https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25,,https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e, ,kA / m,s2,, index,Ms,alpha,DemagnetizingFactor,comment 0,100.0,1.2,1.0,Comment in the first row 1,100.0,3.4,0.5,Comment in the second row 2,100.0,5.6,0.5,Comment in the third row
Finally, remove the file.
>>> Path("example.csv").unlink()
- to_dataframe(include_units: bool = False) pandas.DataFrame#
Convert values to dataframe.
- Parameters:
include_units – If true, include units in the dataframe column names.
- to_hdf5(base: File | Group | str | PathLike, name: str | None = None) Group | None#
Write a collection to an HDF5 group.
The HDF5 structure is:
The collection is stored as an HDF5 group.
The collection description is written to the group’s
descriptionattribute.Each element of the collection becomes a child of the group: -
Entityobjects are stored as HDF5 datasetswith attributes
ontology_label,ontology_iri,unit,description(seemammos_entity.Entity.to_hdf5()).Quantityobjects are stored as datasets with aunitattribute.Plain values are stored as datasets without mammos-specific attributes.
Nested
EntityCollectionobjects become nested HDF5 groups (recursive structure).
The outermost group has an additional attribute
mammos_entity_version.
- Parameters:
base – If it is an open HDF5 file or a group in an HDF5 file, data will be added to it as new group. If it is a str or PathLike a new HDF5 file with the given name will be created. If a file with that name exists already, it will be overwritten without notice.
name – Name for the newly created group. If an element with that name exists already in base the function will fail. If
nameisNoneentities of the collection will be added directly tobaseand the collection description will be added tobaseattributes.
- Returns:
If
baseis an openFileorGroupthe newly created group. If base is a file name nothing is returned (because the file created internally will be closed before the function returns).
See also
mammos_entity.Entity.to_hdf5()mammos_entity.from_hdf5()
- to_yaml(filename: str | PathLike) None#
Write collection to YAML file.
MaMMoS YAML files have the following format:
one commented line at the top of the file containing the mammos format version in the form
# mammos yaml v<version-number>.a mapping with three top-level keys
metadata,descriptionanddatametadatais currently unused and should be emptythe
descriptionkey contains a (multi-line) string with arbitrary content describing the top-level collectiondatacontains one key per element in the collection. Each entry is either an entity-like entry or a nested collection node.
Collection nodes are recursive and have two keys
descriptionanddata:description: a (multi-line) string with arbitrary contentdata: mapping from entry names to entity-like entries or nested collection nodes
Entity-like entries have the following keys:
For
Entity:ontology_label: label in the ontologydescription: description stringontology_iri: IRI of the entityunit: unit of the entity (""for dimensionless)value: value of the data
For
Quantity:unit: unit of the quantityvalue: value of the data
For any other value:
value: value of the data
Added in version v2: The
descriptionkey for each object.Changed in version v2:
The version of the file is now stored in the first commented line, previously it was stored in
metadata:description.The top-level collection description is stored under
description(next tometadataanddata). Previously it was stored inmetadata:description.Non-entity entries no longer store null-valued ontology keys.
Nested collections are supported recursively.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the top-level collection is empty.
Examples
Here is an example with six entries:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology labelan element Tc with only a single value
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... Tc=me.Tc(300, "K"), ... ) >>> collection.to_yaml("example.yaml")
The new file has the following content:
>>> print(Path("example.yaml").read_text()) # mammos yaml v2 metadata: null description: Test data data: index: value: [0, 1, 2] Ms: ontology_label: SpontaneousMagnetization description: Magnetization at 0 Kelvin ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: [100.0, 100.0, 100.0] alpha: unit: s2 value: [1.2, 3.4, 5.6] DemagnetizingFactor: ontology_label: DemagnetizingFactor description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e unit: '' value: [1.0, 0.5, 0.5] comment: value: [Comment in the first row, Comment in the second row, Comment in the third row] Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 300.0
>>> Path("example.yaml").unlink()
Here is a second example with one outer and one inner collection:
>>> properties = me.EntityCollection( ... description="material properties", ... Ms=me.Ms(1.3e3, "kA/m"), ... Tc=me.Tc(1043, "K"), ... ) >>> measurement = me.EntityCollection( ... description="measurement with device X", ... sample=properties, ... T=me.T(300, "K", description="Measurement conditions"), ... H=me.H([0, 50, 100], "kA/m"), ... M=me.M([100, 300, 500], "kA/m"), ... ) >>> measurement.to_yaml("nested_example.yaml") >>> print(Path("nested_example.yaml").read_text()) # mammos yaml v2 metadata: null description: measurement with device X data: sample: description: material properties data: Ms: ontology_label: SpontaneousMagnetization description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: 1300.0 Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 1043.0 T: ontology_label: ThermodynamicTemperature description: Measurement conditions ontology_iri: https://w3id.org/emmo#EMMO_affe07e4_e9bc_4852_86c6_69e26182a17f unit: K value: 300.0 H: ontology_label: ExternalMagneticField description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_da08f0d3-fe19-58bc-8fb6-ecc8992d5eb3 unit: kA / m value: [0.0, 50.0, 100.0] M: ontology_label: Magnetization description: '' ontology_iri: https://w3id.org/emmo#EMMO_b23e7251_a488_4732_8268_027ad76d7e37 unit: kA / m value: [100.0, 300.0, 500.0]
>>> Path("nested_example.yaml").unlink()
- class magmeas.FORC(datfile, read_method='auto')[source]#
Bases:
SweepClass for analysing magnetometric data of FORC measurements.
- segments(prominence=5000.0)[source]#
Get indices of segmentation points. Segmentation point 0 occurs at H = H_max. All uneven segmentation points are the start of a FORC (only section with positive change in H) while all subsequent even segmentation points are the respective ends of each FORC.
- Parameters:
prominence (FLOAT, optional) – The prominence which is used to find all peaks in H_ext(t). See the documentation of scipy.signal.find_peaks for more details. The default is 5e3.
- Returns:
segments – Segmentation points used to extract each recoil loop.
- Return type:
ARRAY
- forc_grid(demag_correction=False, prominence=5000.0)[source]#
Extract grid of magnetic fields, reversal fields and magnetisations from the FORC-measurement.
- Parameters:
demag_correction (BOOL, optional) – Whether to correct the magnetic field for Demagnetisation. The default is True.
prominence (FLOAT, optional) – Prominence used to find segmentation points, see FORC.segments The default is 5e3.
- Returns:
h_grid (QUANTITY) – Magnetic field at each grid point of the FORC-measurement. If demag_correction was True, this is the internal magnetic field. Otherwise it’s the external magnetic field.
h_r_grid (QUANTITY) – Magnetic reversal field of each FORC. Has the same shape as h_grid. If demag_correction was True, this is the internal magnetic field. Otherwise it’s the external magnetic field.
m_grid (QUANTITY) – Magnetisation at each grid point of the FORC-measurement.
- forc_dist(SF, demag_correction=True, prominence=5000.0)[source]#
Calculate the transformed coordinates H_c and H_i as well as the FORC distribution. Takes a grid of (2*SF+1)**2 measurement points from the grid of M(H_r, H) points and fits a quadratic function. The FORC distribution is then the mixed partial derivative of this fitted polynomial.
- Parameters:
SF (INT) – Smoothing factor to be used in the calculation of the FORC distribution. The number of points contributing to a point in the FORC distribution is a square grid with a side length of (2*SF+1) measurement points.
demag_correction (BOOL, optional) – Whether to correct the magnetic field for Demagnetisation. The default is True.
prominence (FLOAT, optional) – Prominence used to find segmentation points, see FORC.segments The default is 5e3.
- Returns:
H_c (QUANTITY) – Local coercive field H_c = (H_r - H) / 2 defined for H > 0
H_i (QUANTITY) – Local interaction field H_i = (H_r + H) / 2
rho (ARRAY) – FORC distribution at each point of the FORC measurement grid.
- calc_B(**kwargs)#
Calculate MagneticFluxDensity and assign it to self with the key ‘B’. For this, self must contain one (and only one) Entity which has the ontology_label ‘InternalMagneticField’ and one of the following:
an Entity with the ontology_label ‘Magnetization’
an Entity with the ontology_label ‘MagneticPolarisation’
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Magnetization’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘B’. The following equations will be used:
\[\begin{split}B &= \mu _0 \cdot (H_{int} + M)\\ B &= \mu _0 \cdot H_{int} + J\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of B if they are relevant.
- Return type:
None
- calc_M(**kwargs)#
Calculate Magnetization and MagneticPolarization and assign them to self with the respective keys ‘M’ and ‘J’. For this, self must contain one (and only one) Entity which has the ontology_label ‘MagneticMoment’ and one of the following:
an Entity with the ontology_label ‘Volume’
an Entity with the ontology_label ‘Mass’ AND one with ‘Density’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Volume’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the keys ‘M’ and ‘J’.
The following equations are used:
\[\begin{split}M &= \frac{\mu}{V}\\ J &= \mu _0 \cdot M\\ V &= m \cdot \rho\\ V &= l_1 \cdot l_2 \cdot l_3\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of M and J if they are relevant.
- Return type:
None
- corr_demag(**kwargs)#
Correct the ExternalMagneticField for the demagnetising field created by the samples own Magnetization. This yields the InternalMagneticField, which will be assigned to self with the key ‘H’. For this, self must contain one (and only one) Entity which has the ontology_label ‘ExternalMagneticField’, another one with ‘Magnetization’ and one of the following:
an Entity with the ontology_label ‘DemagnetizingFactor’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid. The FIRST value in this Entity is assumed to be parallel to the direction of the ExternalMagneticField. The function mammos_analysis.demag.rectangular_cuboid will be used to calculate the DemagnetizingFactor of this rectangular cuboid. Doing so manually and only passing the relevant value as its own Entity with the ontology_label ‘DemagnetizingFactor’ like above is recommended.
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Length’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘H’.
The following equations are used:
\[H_{int} = H_{ext} - D \cdot M\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of H if they are relevant.
- Return type:
None
- property description: str#
Additional description of the entity collection.
The description is a string containing any information relevant to the entity collection. This can include, e.g., whether it is a set of experimental or simulation quantities or outline the overall workflow.
- classmethod from_dataframe(dataframe: pandas.DataFrame, metadata: dict[str, dict], description: str = '') mammos_entity.EntityCollection#
Create EntityCollection from dataframe and metadata.
The EntityCollection is created by combining metadata with data from the dataframe matching key/column names. The available metadata determines whether an element becomes an
Entity, amammos_units.Quantityor a numpy array.All column names in the
dataframemust also exist as keys inmetadataand vice versa.In addition
metadatacan have a keydescriptioncontaining a description for the collection.- Parameters:
dataframe – A dataframe containing the values for the individual entities.
metadata – A dictionary with the structure similar to the one defined in
metadata(). The keysunitanddescriptionfor anEntityare however optional. If not present, default units from the ontology and an empty description are used.description – Description of the entity collection.
- get_entity_key(ontology_label)#
Check, whether collection contains entities of the given label and return their respective keys. If no entities of this label can be found, then None is returned.
- Parameters:
ontology_label (STR) – Ontology label of the entities for which the keys are supposed to be returned.
- Returns:
None if entities with the given ontology label could not be found, the key of the entity that had the specified label if only one was found or a list of all keys for which the respective entity has the specified ontology label.
- Return type:
STR | LIST[STR] | NONE
- metadata() dict[str, dict[str, str]]#
Get entity metadata as dictionary.
This method creates a dictionary containing metadata for all entities in the collection. Keys are names of the (entities) attributes of the collection, values are dictionaries with:
keys
ontology_label,unitanddescriptionif the attribute is an entitykey
unitif the attribute is a quantityan empty dictionary otherwise
Examples
>>> import mammos_entity as me >>> import mammos_units as u >>> col = me.EntityCollection("The description", Tc=me.Tc(), x=1 * u.m, a=0) >>> col.metadata() {'Tc': {'ontology_label': 'CurieTemperature', 'unit': 'K', 'description': ''}, 'x': {'unit': 'm'}, 'a': {}}
Changed in version 0.14.0: The collection description has been removed from the metadata to allow the name
descriptionas key for an entity-like.
- plot(*args, filepath=None, bounds=None, fig_ax=None, segments=None, segments_kwargs=None, **kwargs)#
Plot arguments and save figure if a filepath is given.
- Parameters:
args (STR | ENTITY | QUANTITY | ARRAY) – This determines the values to be plotted. Can only be comprised of one or two values. In the case of a string, it is first attempted to use it as a key for the values in self. If the string is not a key in self, then it is assumed to be an ontology_label and the entitity in self with the fitting ontology_label will be used. If more than one entities have a fitting ontology_label, this method fails. In the case of an Entity, a Quantity or an array, they are attempted to be plotted directly.
filepath (STR | PATH, optional) – Filepath for saving the figure. Default is None, in that case no file is saved and the generated figure as well as all axes objects are returned.
bounds (NONE | TUPLE(NONE | INT), optional) – Indices (start, end) at which the data to be plotted will be cut off. Use None to plot until the respective start or end. Default is None.
fig_ax (TUPLE(matplotlib.figure.Figure, matplotlib.axes.Axes), optional) – Tuple of figure and axes the data should be plotted to. If None is given they will be generated dynamically. Default is None.
segments (NONE | TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data to be plotted will be cut off. See the method self.segments for more information. Note that valid input here are only the indices FOR the output from the segments method and NOT the indices of the actual measurement points. Use None to plot until the respective start or end. Will be overwritten by bounds. If only None and no tuple is given, this will be ignored. Default is None.
segments_kwargs (NONE | DICT, optional) – Dictionary of keyword arguments that will be unpacked in the segments method of self, if self has one. See the respective method for more details. Defailt is None.
kwargs – Keyword arguments to change the appearance of plots. See documentation of matplotlib.pyplot.plot for more information.
- Returns:
Return figure and axes object if filepath is not specified.
- Return type:
None | (matplotlib.Figure, matplotlib.Axes)
- read_PPMS(filepath)#
Read VSM-data from a Quantum Design .DAT file generated with Quantum Designs PPMS, DynaCool or VersaLab devices and assign it to self. Also returns self, so the following works:
some_data = magmeas.Sweep().read_PPMS(‘path/to/file.DAT’)
- Parameters:
filepath (STR | PATH) – Path to Quantum Design .DAT file that data is supposed to be imported from
- Returns:
Returns self, see above.
- Return type:
SWEEP-like
- read_custom(reader_func, *reader_args, **reader_kwargs)#
Use a custom reader function and assign its output to self. This is intended to expand the file reading functionality of magmeas with custom functions for currently unsupported file types. It could however also be used to group several initialisation steps together, as all outputs of the custom reader function will be assigned to self without any checks. This doesn’t only have to be measurement data like the ExternalMagneticField but could also be sample information, already calculated properties or anything else.
The custom reader function `reader_func`is expected to return a single dictionary or mammos_entity.EntityCollection object. Its contents will be assigned to self without checks. It is strongly encouraged to only include mammos_entity.Entity objects in those output containers, since only those can later be used for magmeas-internal calculations. Please keep in mind, that some already present contents of self might be overwritten if the same keys are used.
Also returns self, so the following works:
some_data = magmeas.Sweep().read_custom(some_func, ‘path/to/file.DAT’)
- Parameters:
reader_func (FUNCTION) – The custom reader function which will return a dictionary or a mammos_entity.EntityCollection object with Entities that will be assigned to self.
reader_args (optional) – Arguments which will be passed to reader_func. This could for example be the path to a file which is supposed to be read.
reader_kwargs (optional) – Keyword arguments which will be passed to reader_func.
- to_csv(filename: str | PathLike) None#
Write collection to CSV file.
CSV files contain data in normal CSV format and additional metadata lines at the top of the file. Some of the lines are commented with
#. This structure is fixed and additional comment lines or inline comments in the data table are not allowed.The lines are, in order:
(commented) the file version in the form
mammos csv v<VERSION>(matching regex vd+)(commented, optional) a description of the file, appearing delimited by dashed lines
(optional, only for entities) the preferred ontology label
(optional, only for entities) a description string
(optional, only for entities) the ontology IRI
(optional, for entities and quantities) units
the short labels used to refer to individual columns when working with the data, e.g. in a
pandas.DataFrame(omitting spaces in this string is advisable; ideally this string is the short ontology label)all remaining lines contain data.
Elements in a line are separated by a comma without any surrounding whitespace. A trailing comma is not permitted. Line continuation is OS dependent (rn on Windows, n on Unix).
In columns without ontology the lines containing labels, IRIs, and description are empty.
Similarly, columns without units (with or without ontology entry) have empty units line.
For any column, the description line can be empty. Only entities can store descriptions, i.e., if the ontology-related lines are empty, the description string will not be read.
Added in version v2: The optional description of the file.
Added in version v3: Additional description metadata row containing a description for each column.
Changed in version v3: Ontology labels, entity descriptions, IRIs, and units are no longer commented.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the entities are not tabular. CSV files can only be written for collections in which all entities are either scalar or one-dimenisional with the same length.
ValueError – If elements of the collection are of type
EntityCollection(nested collections are not supported in CSV) or if the collection is empty.
Examples
Here is an example with five columns:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology label
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... ) >>> collection.to_csv("example.csv")
The new file has the following content:
>>> print(Path("example.csv").read_text()) # mammos csv v3 #---------------------------------------- # Test data #---------------------------------------- ,SpontaneousMagnetization,,DemagnetizingFactor, ,Magnetization at 0 Kelvin,,, ,https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25,,https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e, ,kA / m,s2,, index,Ms,alpha,DemagnetizingFactor,comment 0,100.0,1.2,1.0,Comment in the first row 1,100.0,3.4,0.5,Comment in the second row 2,100.0,5.6,0.5,Comment in the third row
Finally, remove the file.
>>> Path("example.csv").unlink()
- to_dataframe(include_units: bool = False) pandas.DataFrame#
Convert values to dataframe.
- Parameters:
include_units – If true, include units in the dataframe column names.
- to_hdf5(base: File | Group | str | PathLike, name: str | None = None) Group | None#
Write a collection to an HDF5 group.
The HDF5 structure is:
The collection is stored as an HDF5 group.
The collection description is written to the group’s
descriptionattribute.Each element of the collection becomes a child of the group: -
Entityobjects are stored as HDF5 datasetswith attributes
ontology_label,ontology_iri,unit,description(seemammos_entity.Entity.to_hdf5()).Quantityobjects are stored as datasets with aunitattribute.Plain values are stored as datasets without mammos-specific attributes.
Nested
EntityCollectionobjects become nested HDF5 groups (recursive structure).
The outermost group has an additional attribute
mammos_entity_version.
- Parameters:
base – If it is an open HDF5 file or a group in an HDF5 file, data will be added to it as new group. If it is a str or PathLike a new HDF5 file with the given name will be created. If a file with that name exists already, it will be overwritten without notice.
name – Name for the newly created group. If an element with that name exists already in base the function will fail. If
nameisNoneentities of the collection will be added directly tobaseand the collection description will be added tobaseattributes.
- Returns:
If
baseis an openFileorGroupthe newly created group. If base is a file name nothing is returned (because the file created internally will be closed before the function returns).
See also
mammos_entity.Entity.to_hdf5()mammos_entity.from_hdf5()
- to_yaml(filename: str | PathLike) None#
Write collection to YAML file.
MaMMoS YAML files have the following format:
one commented line at the top of the file containing the mammos format version in the form
# mammos yaml v<version-number>.a mapping with three top-level keys
metadata,descriptionanddatametadatais currently unused and should be emptythe
descriptionkey contains a (multi-line) string with arbitrary content describing the top-level collectiondatacontains one key per element in the collection. Each entry is either an entity-like entry or a nested collection node.
Collection nodes are recursive and have two keys
descriptionanddata:description: a (multi-line) string with arbitrary contentdata: mapping from entry names to entity-like entries or nested collection nodes
Entity-like entries have the following keys:
For
Entity:ontology_label: label in the ontologydescription: description stringontology_iri: IRI of the entityunit: unit of the entity (""for dimensionless)value: value of the data
For
Quantity:unit: unit of the quantityvalue: value of the data
For any other value:
value: value of the data
Added in version v2: The
descriptionkey for each object.Changed in version v2:
The version of the file is now stored in the first commented line, previously it was stored in
metadata:description.The top-level collection description is stored under
description(next tometadataanddata). Previously it was stored inmetadata:description.Non-entity entries no longer store null-valued ontology keys.
Nested collections are supported recursively.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the top-level collection is empty.
Examples
Here is an example with six entries:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology labelan element Tc with only a single value
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... Tc=me.Tc(300, "K"), ... ) >>> collection.to_yaml("example.yaml")
The new file has the following content:
>>> print(Path("example.yaml").read_text()) # mammos yaml v2 metadata: null description: Test data data: index: value: [0, 1, 2] Ms: ontology_label: SpontaneousMagnetization description: Magnetization at 0 Kelvin ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: [100.0, 100.0, 100.0] alpha: unit: s2 value: [1.2, 3.4, 5.6] DemagnetizingFactor: ontology_label: DemagnetizingFactor description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e unit: '' value: [1.0, 0.5, 0.5] comment: value: [Comment in the first row, Comment in the second row, Comment in the third row] Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 300.0
>>> Path("example.yaml").unlink()
Here is a second example with one outer and one inner collection:
>>> properties = me.EntityCollection( ... description="material properties", ... Ms=me.Ms(1.3e3, "kA/m"), ... Tc=me.Tc(1043, "K"), ... ) >>> measurement = me.EntityCollection( ... description="measurement with device X", ... sample=properties, ... T=me.T(300, "K", description="Measurement conditions"), ... H=me.H([0, 50, 100], "kA/m"), ... M=me.M([100, 300, 500], "kA/m"), ... ) >>> measurement.to_yaml("nested_example.yaml") >>> print(Path("nested_example.yaml").read_text()) # mammos yaml v2 metadata: null description: measurement with device X data: sample: description: material properties data: Ms: ontology_label: SpontaneousMagnetization description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: 1300.0 Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 1043.0 T: ontology_label: ThermodynamicTemperature description: Measurement conditions ontology_iri: https://w3id.org/emmo#EMMO_affe07e4_e9bc_4852_86c6_69e26182a17f unit: K value: 300.0 H: ontology_label: ExternalMagneticField description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_da08f0d3-fe19-58bc-8fb6-ecc8992d5eb3 unit: kA / m value: [0.0, 50.0, 100.0] M: ontology_label: Magnetization description: '' ontology_iri: https://w3id.org/emmo#EMMO_b23e7251_a488_4732_8268_027ad76d7e37 unit: kA / m value: [100.0, 300.0, 500.0]
>>> Path("nested_example.yaml").unlink()
- class magmeas.MT(description: str = '', **kwargs: mammos_entity.Entity | mammos_units.Quantity | numpy.typing.ArrayLike)[source]#
Bases:
SweepClass for importing, storing and using of magnetometric data from M(T)-measurement aswell as derived properties.
- calc_Tc(segments=None, kernel_width=40, edge_frac=0.05, prominence=0.2, **kwargs)[source]#
Calculate Curie-temperature from M(T) measurement. The results should always be checked for feasability and ideally compared with a plot of M(T) and dM/dT(T) to confirm. Curie-temperatures are assumed to occur at turning points of the M(T) curve.
- Parameters:
segments (TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data used for the calculation will be cut off. This usually yields better results than using the whole dataset. Experience has shown that the return curve is often more useful, but this should be checked for each dataset. Default is None.
kernel_width (INT, optional) – Kernel width to be used for smoothing of derivative. Default is 40.
edge_frac (FLOAT, optional) – Fraction of measurement range to be masked at the edges, since those regions are usually very noisy. This is combined with the segments argument with the edges being cut off after the segments have been selected. Default is 0.05.
prominence (FLOAT) – Prominence to be used in the peak finding step. See documentation of scipy.signal.find_peaks for more information. Default is 0.2.
kwargs – Keyword arguments to be used for improved peak finding. See documentation of scipy.signal.find_peaks for more information.
- Returns:
Tc – Curie-Temperature as mammos_entity.Entity
- Return type:
ENTITY
- segments(edge_frac=0.05, prominence=5, **kwargs)[source]#
Find indices of segmentation points which can be used to seperate each measurement segment from each other. The segments are seperated by a changing sign of dT/dt.
- Parameters:
edge_frac (FLOAT, optional) – Fraction of measurement to be treated as edge. Default is 0.05, which means that segmentation points closer than 5 % of the total measurement width to the edges will be discarded. Default is 0.05.
prominence (INT | FLOAT, optional) – Prominence of peaks in T(t) or -T(t) which will be used to define segemntation points. Default is 5.
kwargs (optional) – Optional keyword arguments that will be passed to the peak finding function. See scipy.signal.find_peaks for more information.
- Returns:
s – Array of segmentation points that can be used to segmentise the measurement.
- Return type:
ARRAY[INT]
- dMdT(T, M, kernel_width, edge_frac)[source]#
Return first derivative of magnetisation over temperature. Includes smoothing and masking functionality.
- Parameters:
T (ARRAY | QUANTITY) – Thermodynamic temperature.
M (ARRAY | QUANTITY) – Magnetisation or magnetic polarisation.
kernel_width (INT) – Width of kernel to be used for smoothing. Should be even value.
edge_frac (FLOAT) – Fraction of the array to be masked off at the edges.
- Returns:
dMdT – First derivative of magnetisation over temperature.
- Return type:
QUANTITY
- calc_B(**kwargs)#
Calculate MagneticFluxDensity and assign it to self with the key ‘B’. For this, self must contain one (and only one) Entity which has the ontology_label ‘InternalMagneticField’ and one of the following:
an Entity with the ontology_label ‘Magnetization’
an Entity with the ontology_label ‘MagneticPolarisation’
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Magnetization’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘B’. The following equations will be used:
\[\begin{split}B &= \mu _0 \cdot (H_{int} + M)\\ B &= \mu _0 \cdot H_{int} + J\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of B if they are relevant.
- Return type:
None
- calc_M(**kwargs)#
Calculate Magnetization and MagneticPolarization and assign them to self with the respective keys ‘M’ and ‘J’. For this, self must contain one (and only one) Entity which has the ontology_label ‘MagneticMoment’ and one of the following:
an Entity with the ontology_label ‘Volume’
an Entity with the ontology_label ‘Mass’ AND one with ‘Density’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Volume’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the keys ‘M’ and ‘J’.
The following equations are used:
\[\begin{split}M &= \frac{\mu}{V}\\ J &= \mu _0 \cdot M\\ V &= m \cdot \rho\\ V &= l_1 \cdot l_2 \cdot l_3\end{split}\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of M and J if they are relevant.
- Return type:
None
- corr_demag(**kwargs)#
Correct the ExternalMagneticField for the demagnetising field created by the samples own Magnetization. This yields the InternalMagneticField, which will be assigned to self with the key ‘H’. For this, self must contain one (and only one) Entity which has the ontology_label ‘ExternalMagneticField’, another one with ‘Magnetization’ and one of the following:
an Entity with the ontology_label ‘DemagnetizingFactor’
an Entity with the ontology_label ‘Length’, containing three values (and only three!) which are assumed to be the side lenghts of a rectangular cuboid. The FIRST value in this Entity is assumed to be parallel to the direction of the ExternalMagneticField. The function mammos_analysis.demag.rectangular_cuboid will be used to calculate the DemagnetizingFactor of this rectangular cuboid. Doing so manually and only passing the relevant value as its own Entity with the ontology_label ‘DemagnetizingFactor’ like above is recommended.
If more than one variant would be possible, only one will be chosen. The choice will fall on the option higher in the list above. If the thus chosen option is satisfied by more than one Entity contained in self, the calculation will be canceled as the ambiguity cannot be fixed automatically (e.g. two Entities have the ontology_label ‘Length’). Optionally, the needed Entities from the list above can be given as keyword arguments of this function to provide them for this calculation. They will then be assigned to self and the same logic as before is followed. Assignments to self will happen whether the given Entities are used in the calculation or not. Already assigned Entities will be overwritten if the same key is used, which also applies to entities with the key ‘H’.
The following equations are used:
\[H_{int} = H_{ext} - D \cdot M\]- Parameters:
kwargs (ENTITY, optional) – Keyword arguments that will be assigned to self and possibly contribute to the calculation of H if they are relevant.
- Return type:
None
- property description: str#
Additional description of the entity collection.
The description is a string containing any information relevant to the entity collection. This can include, e.g., whether it is a set of experimental or simulation quantities or outline the overall workflow.
- classmethod from_dataframe(dataframe: pandas.DataFrame, metadata: dict[str, dict], description: str = '') mammos_entity.EntityCollection#
Create EntityCollection from dataframe and metadata.
The EntityCollection is created by combining metadata with data from the dataframe matching key/column names. The available metadata determines whether an element becomes an
Entity, amammos_units.Quantityor a numpy array.All column names in the
dataframemust also exist as keys inmetadataand vice versa.In addition
metadatacan have a keydescriptioncontaining a description for the collection.- Parameters:
dataframe – A dataframe containing the values for the individual entities.
metadata – A dictionary with the structure similar to the one defined in
metadata(). The keysunitanddescriptionfor anEntityare however optional. If not present, default units from the ontology and an empty description are used.description – Description of the entity collection.
- get_entity_key(ontology_label)#
Check, whether collection contains entities of the given label and return their respective keys. If no entities of this label can be found, then None is returned.
- Parameters:
ontology_label (STR) – Ontology label of the entities for which the keys are supposed to be returned.
- Returns:
None if entities with the given ontology label could not be found, the key of the entity that had the specified label if only one was found or a list of all keys for which the respective entity has the specified ontology label.
- Return type:
STR | LIST[STR] | NONE
- metadata() dict[str, dict[str, str]]#
Get entity metadata as dictionary.
This method creates a dictionary containing metadata for all entities in the collection. Keys are names of the (entities) attributes of the collection, values are dictionaries with:
keys
ontology_label,unitanddescriptionif the attribute is an entitykey
unitif the attribute is a quantityan empty dictionary otherwise
Examples
>>> import mammos_entity as me >>> import mammos_units as u >>> col = me.EntityCollection("The description", Tc=me.Tc(), x=1 * u.m, a=0) >>> col.metadata() {'Tc': {'ontology_label': 'CurieTemperature', 'unit': 'K', 'description': ''}, 'x': {'unit': 'm'}, 'a': {}}
Changed in version 0.14.0: The collection description has been removed from the metadata to allow the name
descriptionas key for an entity-like.
- plot(*args, filepath=None, bounds=None, fig_ax=None, segments=None, segments_kwargs=None, **kwargs)#
Plot arguments and save figure if a filepath is given.
- Parameters:
args (STR | ENTITY | QUANTITY | ARRAY) – This determines the values to be plotted. Can only be comprised of one or two values. In the case of a string, it is first attempted to use it as a key for the values in self. If the string is not a key in self, then it is assumed to be an ontology_label and the entitity in self with the fitting ontology_label will be used. If more than one entities have a fitting ontology_label, this method fails. In the case of an Entity, a Quantity or an array, they are attempted to be plotted directly.
filepath (STR | PATH, optional) – Filepath for saving the figure. Default is None, in that case no file is saved and the generated figure as well as all axes objects are returned.
bounds (NONE | TUPLE(NONE | INT), optional) – Indices (start, end) at which the data to be plotted will be cut off. Use None to plot until the respective start or end. Default is None.
fig_ax (TUPLE(matplotlib.figure.Figure, matplotlib.axes.Axes), optional) – Tuple of figure and axes the data should be plotted to. If None is given they will be generated dynamically. Default is None.
segments (NONE | TUPLE(NONE | INT), optional) – Segmentation points (start, end) at which the data to be plotted will be cut off. See the method self.segments for more information. Note that valid input here are only the indices FOR the output from the segments method and NOT the indices of the actual measurement points. Use None to plot until the respective start or end. Will be overwritten by bounds. If only None and no tuple is given, this will be ignored. Default is None.
segments_kwargs (NONE | DICT, optional) – Dictionary of keyword arguments that will be unpacked in the segments method of self, if self has one. See the respective method for more details. Defailt is None.
kwargs – Keyword arguments to change the appearance of plots. See documentation of matplotlib.pyplot.plot for more information.
- Returns:
Return figure and axes object if filepath is not specified.
- Return type:
None | (matplotlib.Figure, matplotlib.Axes)
- read_PPMS(filepath)#
Read VSM-data from a Quantum Design .DAT file generated with Quantum Designs PPMS, DynaCool or VersaLab devices and assign it to self. Also returns self, so the following works:
some_data = magmeas.Sweep().read_PPMS(‘path/to/file.DAT’)
- Parameters:
filepath (STR | PATH) – Path to Quantum Design .DAT file that data is supposed to be imported from
- Returns:
Returns self, see above.
- Return type:
SWEEP-like
- read_custom(reader_func, *reader_args, **reader_kwargs)#
Use a custom reader function and assign its output to self. This is intended to expand the file reading functionality of magmeas with custom functions for currently unsupported file types. It could however also be used to group several initialisation steps together, as all outputs of the custom reader function will be assigned to self without any checks. This doesn’t only have to be measurement data like the ExternalMagneticField but could also be sample information, already calculated properties or anything else.
The custom reader function `reader_func`is expected to return a single dictionary or mammos_entity.EntityCollection object. Its contents will be assigned to self without checks. It is strongly encouraged to only include mammos_entity.Entity objects in those output containers, since only those can later be used for magmeas-internal calculations. Please keep in mind, that some already present contents of self might be overwritten if the same keys are used.
Also returns self, so the following works:
some_data = magmeas.Sweep().read_custom(some_func, ‘path/to/file.DAT’)
- Parameters:
reader_func (FUNCTION) – The custom reader function which will return a dictionary or a mammos_entity.EntityCollection object with Entities that will be assigned to self.
reader_args (optional) – Arguments which will be passed to reader_func. This could for example be the path to a file which is supposed to be read.
reader_kwargs (optional) – Keyword arguments which will be passed to reader_func.
- to_csv(filename: str | PathLike) None#
Write collection to CSV file.
CSV files contain data in normal CSV format and additional metadata lines at the top of the file. Some of the lines are commented with
#. This structure is fixed and additional comment lines or inline comments in the data table are not allowed.The lines are, in order:
(commented) the file version in the form
mammos csv v<VERSION>(matching regex vd+)(commented, optional) a description of the file, appearing delimited by dashed lines
(optional, only for entities) the preferred ontology label
(optional, only for entities) a description string
(optional, only for entities) the ontology IRI
(optional, for entities and quantities) units
the short labels used to refer to individual columns when working with the data, e.g. in a
pandas.DataFrame(omitting spaces in this string is advisable; ideally this string is the short ontology label)all remaining lines contain data.
Elements in a line are separated by a comma without any surrounding whitespace. A trailing comma is not permitted. Line continuation is OS dependent (rn on Windows, n on Unix).
In columns without ontology the lines containing labels, IRIs, and description are empty.
Similarly, columns without units (with or without ontology entry) have empty units line.
For any column, the description line can be empty. Only entities can store descriptions, i.e., if the ontology-related lines are empty, the description string will not be read.
Added in version v2: The optional description of the file.
Added in version v3: Additional description metadata row containing a description for each column.
Changed in version v3: Ontology labels, entity descriptions, IRIs, and units are no longer commented.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the entities are not tabular. CSV files can only be written for collections in which all entities are either scalar or one-dimenisional with the same length.
ValueError – If elements of the collection are of type
EntityCollection(nested collections are not supported in CSV) or if the collection is empty.
Examples
Here is an example with five columns:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology label
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... ) >>> collection.to_csv("example.csv")
The new file has the following content:
>>> print(Path("example.csv").read_text()) # mammos csv v3 #---------------------------------------- # Test data #---------------------------------------- ,SpontaneousMagnetization,,DemagnetizingFactor, ,Magnetization at 0 Kelvin,,, ,https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25,,https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e, ,kA / m,s2,, index,Ms,alpha,DemagnetizingFactor,comment 0,100.0,1.2,1.0,Comment in the first row 1,100.0,3.4,0.5,Comment in the second row 2,100.0,5.6,0.5,Comment in the third row
Finally, remove the file.
>>> Path("example.csv").unlink()
- to_dataframe(include_units: bool = False) pandas.DataFrame#
Convert values to dataframe.
- Parameters:
include_units – If true, include units in the dataframe column names.
- to_hdf5(base: File | Group | str | PathLike, name: str | None = None) Group | None#
Write a collection to an HDF5 group.
The HDF5 structure is:
The collection is stored as an HDF5 group.
The collection description is written to the group’s
descriptionattribute.Each element of the collection becomes a child of the group: -
Entityobjects are stored as HDF5 datasetswith attributes
ontology_label,ontology_iri,unit,description(seemammos_entity.Entity.to_hdf5()).Quantityobjects are stored as datasets with aunitattribute.Plain values are stored as datasets without mammos-specific attributes.
Nested
EntityCollectionobjects become nested HDF5 groups (recursive structure).
The outermost group has an additional attribute
mammos_entity_version.
- Parameters:
base – If it is an open HDF5 file or a group in an HDF5 file, data will be added to it as new group. If it is a str or PathLike a new HDF5 file with the given name will be created. If a file with that name exists already, it will be overwritten without notice.
name – Name for the newly created group. If an element with that name exists already in base the function will fail. If
nameisNoneentities of the collection will be added directly tobaseand the collection description will be added tobaseattributes.
- Returns:
If
baseis an openFileorGroupthe newly created group. If base is a file name nothing is returned (because the file created internally will be closed before the function returns).
See also
mammos_entity.Entity.to_hdf5()mammos_entity.from_hdf5()
- to_yaml(filename: str | PathLike) None#
Write collection to YAML file.
MaMMoS YAML files have the following format:
one commented line at the top of the file containing the mammos format version in the form
# mammos yaml v<version-number>.a mapping with three top-level keys
metadata,descriptionanddatametadatais currently unused and should be emptythe
descriptionkey contains a (multi-line) string with arbitrary content describing the top-level collectiondatacontains one key per element in the collection. Each entry is either an entity-like entry or a nested collection node.
Collection nodes are recursive and have two keys
descriptionanddata:description: a (multi-line) string with arbitrary contentdata: mapping from entry names to entity-like entries or nested collection nodes
Entity-like entries have the following keys:
For
Entity:ontology_label: label in the ontologydescription: description stringontology_iri: IRI of the entityunit: unit of the entity (""for dimensionless)value: value of the data
For
Quantity:unit: unit of the quantityvalue: value of the data
For any other value:
value: value of the data
Added in version v2: The
descriptionkey for each object.Changed in version v2:
The version of the file is now stored in the first commented line, previously it was stored in
metadata:description.The top-level collection description is stored under
description(next tometadataanddata). Previously it was stored inmetadata:description.Non-entity entries no longer store null-valued ontology keys.
Nested collections are supported recursively.
- Parameters:
filename – Name of the generated file. An existing file with the same name is overwritten without notice.
- Raises:
ValueError – If the top-level collection is empty.
Examples
Here is an example with six entries:
an index with no units or ontology label
the entity spontaneous magnetization with an entry in the ontology and a description
a made-up quantity alpha with a unit but no ontology label
demagnetizing factor with an ontology entry but no unit
a column
commentcontaining a string comment without units or ontology labelan element Tc with only a single value
The file has a description reading “Test data”.
>>> from pathlib import Path >>> import mammos_entity as me >>> import mammos_units as u >>> collection = me.EntityCollection( ... description="Test data", ... index=[0, 1, 2], ... Ms=me.Entity("SpontaneousMagnetization", [1e2, 1e2, 1e2], "kA/m", description="Magnetization at 0 Kelvin"), ... alpha=[1.2, 3.4, 5.6] * u.s**2, ... DemagnetizingFactor=me.Entity("DemagnetizingFactor", [1, 0.5, 0.5]), ... comment=[ ... "Comment in the first row", ... "Comment in the second row", ... "Comment in the third row", ... ], ... Tc=me.Tc(300, "K"), ... ) >>> collection.to_yaml("example.yaml")
The new file has the following content:
>>> print(Path("example.yaml").read_text()) # mammos yaml v2 metadata: null description: Test data data: index: value: [0, 1, 2] Ms: ontology_label: SpontaneousMagnetization description: Magnetization at 0 Kelvin ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: [100.0, 100.0, 100.0] alpha: unit: s2 value: [1.2, 3.4, 5.6] DemagnetizingFactor: ontology_label: DemagnetizingFactor description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_0f2b5cc9-d00a-5030-8448-99ba6b7dfd1e unit: '' value: [1.0, 0.5, 0.5] comment: value: [Comment in the first row, Comment in the second row, Comment in the third row] Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 300.0
>>> Path("example.yaml").unlink()
Here is a second example with one outer and one inner collection:
>>> properties = me.EntityCollection( ... description="material properties", ... Ms=me.Ms(1.3e3, "kA/m"), ... Tc=me.Tc(1043, "K"), ... ) >>> measurement = me.EntityCollection( ... description="measurement with device X", ... sample=properties, ... T=me.T(300, "K", description="Measurement conditions"), ... H=me.H([0, 50, 100], "kA/m"), ... M=me.M([100, 300, 500], "kA/m"), ... ) >>> measurement.to_yaml("nested_example.yaml") >>> print(Path("nested_example.yaml").read_text()) # mammos yaml v2 metadata: null description: measurement with device X data: sample: description: material properties data: Ms: ontology_label: SpontaneousMagnetization description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_032731f8-874d-5efb-9c9d-6dafaa17ef25 unit: kA / m value: 1300.0 Tc: ontology_label: CurieTemperature description: '' ontology_iri: https://w3id.org/emmo#EMMO_6b5af5a8_a2d8_4353_a1d6_54c9f778343d unit: K value: 1043.0 T: ontology_label: ThermodynamicTemperature description: Measurement conditions ontology_iri: https://w3id.org/emmo#EMMO_affe07e4_e9bc_4852_86c6_69e26182a17f unit: K value: 300.0 H: ontology_label: ExternalMagneticField description: '' ontology_iri: https://w3id.org/emmo/domain/magnetic-materials#EMMO_da08f0d3-fe19-58bc-8fb6-ecc8992d5eb3 unit: kA / m value: [0.0, 50.0, 100.0] M: ontology_label: Magnetization description: '' ontology_iri: https://w3id.org/emmo#EMMO_b23e7251_a488_4732_8268_027ad76d7e37 unit: kA / m value: [100.0, 300.0, 500.0]
>>> Path("nested_example.yaml").unlink()