Skip to content

User Reference

The simple namespace exposes the core functionality required for standard use.
This includes convenient access to all primary user-facing classes and functions, making it the recommended entry point for most workflows.

For more advanced, specialised, or lower-level functionality, you can import directly from the individual submodules:


The simple Namespace

add_weights

add_weights(modeldata, axis, weights=1, *, sum_weights=True, norm_weights=True, default_attrname=None, unit=None, default_value=0, mask=None, mask_na=True, axisname='w')

Add weights to the specified axis of each datapoint in the modeldata dictionary.

This function appends a new array of weights (under axisname) to each datapoint in modeldata. The weights can be a constant or a string referring to data to be individually retrieved from each model. Optionally, the weights can be summed, normalized, and masked for missing data.

The 'mask' and 'mask_na' arguments should be the same as those used to generate modeldata to ensure consistent results.

Parameters:

  • modeldata (dict) –

    The data dictionary returned from get_data. It should be a dict of models, each containing a list of datapoint dictionaries.

  • axis (str) –

    The axis in the datapoints that the weights correspond to (e.g., 'x', 'y').

  • weights ((int, float, str), default: 1 ) –

    The weights to add. Can be: - A scalar to apply uniformly, - A string key that will be used to retrieve data from each model individually.

  • sum_weights (bool, default: True ) –

    If True and weights is a string consisting of multiple keys, the values for the different keys are summed together and used for each datapoint for a given model. Default is True.

  • norm_weights (bool, default: True ) –

    If True, normalise weights along the specified axis. Default is True.

  • default_attrname (str or None, default: None ) –

    Attribute name to use when fetching weights if not included in labels. Optional.

  • unit (str or None, default: None ) –

    Unit to assign to the fetched weight values. Optional.

  • default_value (float, default: 0 ) –

    Default value to assign if weights are missing. Default is 0.

  • mask (str or None, default: None ) –

    Optional mask to apply to the data when computing or assigning weights.

  • mask_na (bool, default: True ) –

    If True, mask values will be replaced with NaNs. If False, masked values are omitted.

  • axisname (str, default: 'w' ) –

    The name under which the weight data will be stored in each datapoint. Default is 'w'.

Returns:

  • dict

    The modified modeldata, with weight arrays added to each datapoint.

Raises:

  • ValueError

    If the number of weight arrays does not match the number of datapoints and they cannot be broadcast.

Source code in simple/plotting.py
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
@utils.set_default_kwargs()
def add_weights(modeldata, axis, weights=1, *,
                sum_weights=True, norm_weights=True,
                default_attrname=None, unit=None, default_value=0,
                mask=None, mask_na=True, axisname='w'):
    """
    Add weights to the specified axis of each datapoint in the modeldata dictionary.

    This function appends a new array of weights (under `axisname`) to each datapoint
    in `modeldata`. The weights can be a constant or a string referring to data to be individually
    retrieved from each model. Optionally, the weights can be summed, normalized, and masked for missing data.

    The 'mask' and 'mask_na' arguments should be the same as those used to generate `modeldata` to ensure
    consistent results.

    Args:
        modeldata (dict): The data dictionary returned from `get_data`. It should be a
            dict of models, each containing a list of datapoint dictionaries.
        axis (str): The axis in the datapoints that the weights correspond to (e.g., 'x', 'y').
        weights (int, float, str): The weights to add. Can be:
            - A scalar to apply uniformly,
            - A string key that will be used to retrieve data from each model individually.
        sum_weights (bool): If True and `weights` is a string consisting of multiple keys, the values for the different
            keys are summed together and used for each datapoint for a given model. Default is True.
        norm_weights (bool): If True, normalise weights along the specified axis. Default is True.
        default_attrname (str or None): Attribute name to use when fetching weights if not included
            in labels. Optional.
        unit (str or None): Unit to assign to the fetched weight values. Optional.
        default_value (float): Default value to assign if weights are missing. Default is 0.
        mask (str or None): Optional mask to apply to the data when computing or assigning weights.
        mask_na (bool): If True, mask values will be replaced with NaNs. If False, masked values are omitted.
        axisname (str): The name under which the weight data will be stored in each datapoint. Default is 'w'.

    Returns:
        dict: The modified `modeldata`, with weight arrays added to each datapoint.

    Raises:
        ValueError: If the number of weight arrays does not match the number of datapoints
            and they cannot be broadcast.
    """

    # Remove any previous weights
    for model in modeldata:
        for dp in modeldata[model]:
            dp.pop(axisname, None)

    models = list(modeldata.keys())
    if type(weights) is str:
        modeldata_w, axis_labels_w = get_data(models, {'w': weights},
                                              mask=mask, mask_na=mask_na,
                                              default_attrname=default_attrname, unit=unit,
                                              default_value=default_value,
                                              attrname_in_label=True, model_in_label=False, axis_name_in_label=False,
                                              latex_labels=False)

        if sum_weights:
            for model, datapoints_w in modeldata_w.items():
                if len(datapoints_w) > 1:
                    labels = [dw.get('label', 'Missing label') for dw in datapoints_w]
                    logger.info(
                        f'{model}: Calculating weights by adding together: {axis_labels_w["w"]} <w: {", ".join(labels)}>')
                    modeldata_w[model] = [{axisname: functools.reduce(np.add, [dw['w'] for dw in datapoints_w])}]

    else:
        modeldata_w = {}
        for model in models:
            datapoints_xy = modeldata[model]
            if mask:
                m = model.get_mask(mask)
                if mask_na:
                    modeldata_w[model] = [{axisname: np.full(m.shape, weights, dtype=np.float64)}]
                    modeldata_w[model][0][axisname][np.logical_not(m)] = np.nan
                else:
                    modeldata_w[model] = [{axisname: np.full(np.count_nonzero(m), weights, dtype=np.float64)}]
            else:
                modeldata_w[model] = [{axisname: np.full_like(dp[axis], weights, dtype=np.float64)} for dp in datapoints_xy]

    for model, datapoints in modeldata.items():
        datapoints_w = modeldata_w[model]

        if len(datapoints_w) == 1 and len(datapoints) > 1:
            for datapoint in datapoints:
                datapoint[axisname] = datapoints_w[0][axisname].copy()
        elif len(datapoints_w) == len(datapoints):
            for i, datapoint in enumerate(datapoints):
                datapoint[axisname] = datapoints_w[i][axisname]
        else:
            raise ValueError(f'Size of weights data incompatible with size of {axis} data')

    if norm_weights:
        _norm_weights(modeldata, axisname)

    return modeldata

add_weights_ccsne

add_weights_ccsne(modeldata, axis, weights=1, kwargs=None)

Add weights to the specified axis of each CCSNe datapoint in the modeldata dictionary.

Before normalisation, if applied, the weight of each datapoint will be multiplied by the mass of each mass coordinate.

This function appends a new array of weights (under axisname) to each datapoint in modeldata. The weights can be a constant or a string referring to data to be indvidually retrieved from each model. Optionally, the weights can be summed, normalized, and masked for missing data.

The mask and mask_na arguments should be the same as those used to generate 'modeldata' to ensure conistent results.

Add weights to CCSNe datapoints by combining standard weighting with mass coordinate scaling.

This function extends add_weights by additionally multiplying the resulting weights by the mass associated with each mass coordinate in CCSNe models.

The initial weighting follows the same logic as add_weights, accepting either a scalar or a string referring to model attributes. The 'mask' and 'mask_na' arguments should match those used when creating modeldata to ensure consistency.

Parameters:

  • modeldata (dict) –

    The data dictionary as returned by get_data, structured as {model_name: list of datapoints}. Each datapoint is a dictionary.

  • axis (str) –

    The axis key to which the weights apply (e.g., 'x', 'y').

  • weights (int, float, or str, default: 1 ) –

    The weight specification. Can be: - A scalar to apply uniformly across all datapoints, - A string key to retrieve values from each model individually.

  • **kwargs

    Any valid keyword arguments for the add_weights function.

Returns:

  • dict

    The modified modeldata, with weight arrays added to each datapoint.

Source code in simple/ccsne.py
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
@utils.set_default_kwargs(inherits_=plotting.add_weights)
def add_weights_ccsne(modeldata, axis, weights = 1, kwargs=None):
    """
    Add weights to the specified axis of each CCSNe datapoint in the modeldata dictionary.

    Before normalisation, if applied, the weight of each datapoint will be multiplied by the
    mass of each mass coordinate.

    This function appends a new array of weights (under `axisname`) to each datapoint
    in `modeldata`. The weights can be a constant or a string referring to data to be indvidually
    retrieved from each model. Optionally, the weights can be summed,
    normalized, and masked for missing data.

    The `mask` and `mask_na` arguments should be the same as those used to generate 'modeldata' to ensure
    conistent results.

    Add weights to CCSNe datapoints by combining standard weighting with mass coordinate scaling.

    This function extends `add_weights` by additionally multiplying the resulting weights
    by the mass associated with each mass coordinate in CCSNe models.

    The initial weighting follows the same logic as `add_weights`, accepting either a scalar
    or a string referring to model attributes. The 'mask' and 'mask_na' arguments should
    match those used when creating `modeldata` to ensure consistency.

    Args:
        modeldata (dict): The data dictionary as returned by `get_data`, structured as
            {model_name: list of datapoints}. Each datapoint is a dictionary.
        axis (str): The axis key to which the weights apply (e.g., 'x', 'y').
        weights (int, float, or str): The weight specification. Can be:
            - A scalar to apply uniformly across all datapoints,
            - A string key to retrieve values from each model individually.
        **kwargs: Any valid keyword arguments for the `add_weights` function.

    Returns:
        dict: The modified `modeldata`, with weight arrays added to each datapoint.
    """

    mask = kwargs.get('mask', None)
    mask_na = kwargs.get('mask_na', True)
    axisname = kwargs.get('axisname', 'w')

    norm_weights = kwargs.pop('norm_weights', True) # Defaults to the value of add_weights
    kwargs['norm_weights'] = False
    modeldata = plotting.add_weights(modeldata, axis, weights, kwargs=kwargs)

    logger.info('Multiplying all weights by the mass coordinate mass')

    for model, datapoints in modeldata.items():
        masscoord_mass = model.masscoord_mass
        if mask:
            imask = model.get_mask(mask)

        for ki, datapoint in enumerate(datapoints):
            if mask and not mask_na:
                datapoint[axisname] = datapoint[axisname] * masscoord_mass[imask]
            else:
                datapoint[axisname] = datapoint[axisname] * masscoord_mass

    if norm_weights:
        plotting._norm_weights(modeldata, axisname)

    return modeldata

asarray

asarray(values, dtype=None, saving=False)

Convert data to a numpy array.

If data is a string or a sequence of strings and saving=False, either a single string or a tuple of string will be returned. If saving is True the values will be converted to an array with a byte dtype. This ensures values are compatible with the hdf5 library.

Arrays with a bytes dtype will automatically be converted to the str dtype. If saving is False then this values will be converted to either a string or a tuple of strings (see above).

Parameters:

  • values

    An values like object.

  • dtype

    The data type of the returned values.

  • saving

    Should be True is the data is to be saved in a hdf5 file.

Source code in simple/utils.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def asarray(values, dtype=None, saving=False):
    """
    Convert ``data`` to a numpy array.

    If ``data`` is a string or a sequence of strings and ``saving=False``, either a single string or a tuple
    of string will be returned. If ``saving`` is ``True`` the values will be converted to an array with a byte dtype.
    This ensures values are compatible with the hdf5 library.

    Arrays with a ``bytes`` dtype will automatically be converted to the ``str`` dtype. If ``saving`` is ``False`` then
    this values will be converted to either a string or a tuple of strings (see above).

    Args:
        values (): An values like object.
        dtype (): The data type of the returned values.
        saving (): Should be ``True`` is the data is to be saved in a hdf5 file.

    """
    values = np.asarray(values, dtype=dtype)

    if values.dtype.type is np.bytes_:
        values = values.astype(np.str_)

    if not saving and values.dtype.type is np.str_:
        values = values.tolist()
        if type(values) is list:
            values = tuple(values)

    if saving and values.dtype.type is np.str_:
        values = values.astype(np.bytes_)

    return values

aselement

aselement(string, without_suffix=False, allow_invalid=False)

Returns a Element representing an element symbol.

The returned element format is the capitalised element symbol followed by the suffix, if present. E.g. Pd-104* where * is the suffix.

The case of the element symbol is not considered.

Parameters:

  • string (str) –

    A string containing an element symbol.

  • without_suffix

    If True the suffix part of the string is ignored.

  • allow_invalid

    If False, and string cannot be parsed into an element string, an exception is raised. If True then string.strip() is returned instead.

Examples:

>>> ele = simple.asisotope("pd"); ele
"Pd"
Source code in simple/utils.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def aselement(string, without_suffix=False, allow_invalid=False):
    """
    Returns a [``Element``][simple.utils.Element] representing an element symbol.

    The returned element format is the capitalised element
    symbol followed by the suffix, if present. E.g. ``Pd-104*`` where
    ``*`` is the suffix.

    The case of the element symbol is not considered.

    Args:
        string (str): A string containing an element symbol.
        without_suffix (): If ``True`` the suffix part of the string is ignored.
        allow_invalid ():  If ``False``, and ``string`` cannot be parsed into an element string, an exception is
            raised. If ``True`` then ``string.strip()`` is returned instead.

    Examples:
        >>> ele = simple.asisotope("pd"); ele
        "Pd"


    """
    if type(string) is Element:
        if without_suffix:
            return string.without_suffix()
        else:
            return string
    elif isinstance(string, str):
        string = string.strip()
    else:
        raise TypeError(f'``string`` must a str not {type(string)}')

    try:
        return Element(string, without_suffix=without_suffix)
    except ValueError:
        if allow_invalid:
            return string
        else:
            raise

aselements

aselements(strings, without_suffix=False, allow_invalid=False)

Returns a tuple of Element strings where each string represents an element symbol.

Parameters:

  • strings

    Can either be a string with element symbol seperated by a , or a sequence of strings.

  • without_suffix

    If True the suffix part of each isotope string is ignored.

  • allow_invalid

    If False, and a string cannot be parsed into an isotope string, an exception is raised. If True then string.strip() is returned instead.

Examples:

>>> simple.asisotopes('ru, pd, cd')
('Ru', 'Pd', 'Cd')
>>> simple.asisotopes(['ru', 'pd', 'cd'])
('Ru', 'Pd', 'Cd')
Source code in simple/utils.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
def aselements(strings, without_suffix=False, allow_invalid=False):
    """
    Returns a tuple of [``Element``][simple.utils.Element] strings where each string represents an element symbol.

    Args:
        strings (): Can either be a string with element symbol seperated by a ``,`` or a sequence of strings.
        without_suffix (): If ``True`` the suffix part of each isotope string is ignored.
        allow_invalid ():  If ``False``, and a string cannot be parsed into an isotope string, an exception is
            raised. If ``True`` then ``string.strip()`` is returned instead.

    Examples:
        >>> simple.asisotopes('ru, pd, cd')
        ('Ru', 'Pd', 'Cd')

        >>> simple.asisotopes(['ru', 'pd', 'cd'])
        ('Ru', 'Pd', 'Cd')
    """
    if type(strings) is str:
        strings = [s for s in strings.split(',')]

    return tuple(aselement(string, without_suffix=without_suffix, allow_invalid=allow_invalid) for string in strings)

asisolist

asisolist(isolist, without_suffix=False, allow_invalid=False)

Return a dictionary consisting of an isotope key mapped to a tuple of isotopes that should make up the key isotope.

If isolist is list or tuple of keys then each key will be mapped only to itself.

Parameters:

  • isolist

    Either a dictionary mapping a single isotope to a list of isotopes or a sequence of isotopes that will be mapped to themselfs.

  • without_suffix

    If True the suffix part of each isotope string is ignored.

  • allow_invalid

    If True invalid isotopes string are allowed. If False they will instead raise an exception.

Source code in simple/utils.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
def asisolist(isolist, without_suffix=False, allow_invalid=False):
    """
    Return a dictionary consisting of an isotope key mapped to a tuple of isotopes that should make up the
    key isotope.

    If ``isolist`` is list or tuple of keys then each key will be mapped only to itself.

    Args:
        isolist (): Either a dictionary mapping a single isotope to a list of isotopes or a sequence of isotopes that
            will be mapped to themselfs.
        without_suffix (): If ``True`` the suffix part of each isotope string is ignored.
        allow_invalid (): If ``True`` invalid isotopes string are allowed. If ``False`` they will instead raise
            an exception.
    """
    if type(isolist) is not dict:
        isolist = asisotopes(isolist, without_suffix=without_suffix, allow_invalid=allow_invalid)
        return {iso: (iso,) for iso in isolist}
    else:
        return {asisotope(k, without_suffix=without_suffix, allow_invalid=allow_invalid):
                asisotopes(v, without_suffix=without_suffix, allow_invalid=allow_invalid)
                for k,v in isolist.items()}

asisotope

asisotope(string, without_suffix=False, allow_invalid=False)

Returns a Isotope representing an isotope.

The returned isotope format is the capitalised element symbol followed by a dash followed by the mass number followed by the suffix, if present. E.g. Pd-104* where * is the suffix.

The order of the element symbol and mass number in string is not important, but they must proceed the suffix. The element symbol and mass number may be seperated by -. The case of the element symbol is not considered.

Parameters:

  • string (str) –

    A string element symbol and a mass number.

  • without_suffix

    If True the suffix part of the isotope string is ignored.

  • allow_invalid

    If False, and string cannot be parsed into an isotope string, an exception is raised. If True then string.strip() is returned instead.

Examples:

>>> iso = simple.asisotope("104pd"); iso # pd104, 104-Pd etc are also valid
"Pd-104"
>>> iso.symbol, iso.mass
"Pd", "104"
Source code in simple/utils.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
def asisotope(string, without_suffix=False, allow_invalid=False):
    """
    Returns a [``Isotope``][simple.utils.Isotope] representing an isotope.

    The returned isotope format is the capitalised element
    symbol followed by a dash followed by the mass number followed by the suffix, if present. E.g. ``Pd-104*`` where
    ``*`` is the suffix.

    The order of the element symbol and mass number in ``string`` is not important, but they must proceed the suffix.
    The element symbol and mass number may be seperated by ``-``. The case of the element symbol is not
    considered.

    Args:
        string (str): A string element symbol and a mass number.
        without_suffix (): If ``True`` the suffix part of the isotope string is ignored.
        allow_invalid ():  If ``False``, and ``string`` cannot be parsed into an isotope string, an exception is
            raised. If ``True`` then ``string.strip()`` is returned instead.

    Examples:
        >>> iso = simple.asisotope("104pd"); iso # pd104, 104-Pd etc are also valid
        "Pd-104"
        >>> iso.symbol, iso.mass
        "Pd", "104"

    """
    if type(string) is Isotope:
        if without_suffix:
            return string.without_suffix()
        else:
            return string
    elif isinstance(string, str):
        string = string.strip()
    else:
        raise TypeError(f'``string`` must a str not {type(string)}')

    try:
        return Isotope(string, without_suffix=without_suffix)
    except ValueError:
        if allow_invalid:
            return string
        else:
            raise

asisotopes

asisotopes(strings, without_suffix=False, allow_invalid=False)

Returns a tuple of Isotope strings where each string represents an isotope.

Parameters:

  • strings

    Can either be a string with isotopes seperated by a , or a sequence of strings.

  • without_suffix

    If True the suffix part of each isotope string is ignored.

  • allow_invalid

    If False, and a string cannot be parsed into an isotope string, an exception is raised. If True then string.strip() is returned instead.

Examples:

>>> simple.asisotopes('104pd, pd105, 106-Pd')
('Pd-104', 'Pd-105, 106-Pd')
>>> simple.asisotopes(['104pd', 'pd105', '106-Pd'])
('Pd-104', 'Pd-105, 106-Pd')
Source code in simple/utils.py
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def asisotopes(strings, without_suffix=False, allow_invalid=False):
    """
    Returns a tuple of [``Isotope``][simple.utils.Isotope] strings where each string represents an isotope.

    Args:
        strings (): Can either be a string with isotopes seperated by a ``,`` or a sequence of strings.
        without_suffix (): If ``True`` the suffix part of each isotope string is ignored.
        allow_invalid ():  If ``False``, and a string cannot be parsed into an isotope string, an exception is
            raised. If ``True`` then ``string.strip()`` is returned instead.

    Examples:
        >>> simple.asisotopes('104pd, pd105, 106-Pd')
        ('Pd-104', 'Pd-105, 106-Pd')

        >>> simple.asisotopes(['104pd', 'pd105', '106-Pd'])
        ('Pd-104', 'Pd-105, 106-Pd')
    """
    if type(strings) is str:
        strings = [s for s in strings.split(',')]

    return tuple(asisotope(string, without_suffix=without_suffix, allow_invalid=allow_invalid) for string in strings)

askeyarray

askeyarray(values, keys, dtype=None)

Returns a numpy array where the columns can be accessed by the column key.

Parameters:

  • values

    An array consisting of 2 dimensions where first dimension is the row and the second dimension is the column.

  • keys

    The keys for each column in values. Must be the same length as the second dimension of values. of array.

  • dtype

    The values type of the returned array. All columns will have the same dtype.

Notes If values has less then 2 dimensions then it is assumed to represent a single row of values.

It is not possible to save this type of array in hdf5 files if they have more than a few hundred columns.

Examples:

>>> a = simple.askeyarray([[1,2,3],[4,5,6]], ['Pd-104','Pd-105','Pd-106']); a
array([(1, 2, 3), (4, 5, 6)],
      dtype=[('Pd-104', '<i8'), ('Pd-105', '<i8'), ('Pd-106', '<i8')])
>>> a['Pd-104']
array([1, 4])
Source code in simple/utils.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def askeyarray(values, keys, dtype=None):
    """
    Returns a numpy array where the columns can be accessed by the column key.

    Args:
        values (): An array consisting of 2 dimensions where first dimension is the row and the second
            dimension is the column.
        keys (): The keys for each column in ``values``. Must be the same length as the second dimension of ``values``.
            of ``array``.
        dtype (): The values type of the returned array. All columns will have the same dtype.

    **Notes**
    If ``values`` has less then 2 dimensions then it is assumed to represent a single row of values.

    It is not possible to save this type of array in hdf5 files if they have more than a few hundred columns.

    Examples:
        >>> a = simple.askeyarray([[1,2,3],[4,5,6]], ['Pd-104','Pd-105','Pd-106']); a
        array([(1, 2, 3), (4, 5, 6)],
              dtype=[('Pd-104', '<i8'), ('Pd-105', '<i8'), ('Pd-106', '<i8')])
        >>> a['Pd-104']
        array([1, 4])

    """
    if type(keys) is str:
        keys = [k.strip() for k in keys.split(',')]

    a = np.asarray(values, dtype=dtype)
    dtype = [(k, a.dtype) for k in keys]

    if a.ndim < 2:
        a = a.reshape((-1, a.size))
    elif a.ndim > 2:
        raise ValueError('``values`` cannot have more than 2 dimensions')

    if a.shape[1] != len(keys):
        raise ValueError(
            f'item (r:{a.shape[0]}, c:{a.shape[1]}) must have same number of columns as there are keys ({len(keys)})')

    return np.array([tuple(r) for r in a], dtype=dtype)

asratio

asratio(string, without_suffix=False, allow_invalid=False)

Returns a Ratio string representing the ratio of two isotopes.

The format of the returned string is the numerator followed by a / followed by the normiso. The numerator and normiso string be parsed by asisotope together with the given without_suffix and allow_invalid arguments passed to this function.

Parameters:

  • string (str) –

    A string contaning two strings seperated by a single /.

  • without_suffix (bool, default: False ) –

    If True the suffix part of the numerator and normiso string is ignored.

  • allow_invalid (bool, default: False ) –

    Whether the numerator and normiso has to be a valid isotope string.

If the returned string is an isotope string it will have the following attributes and methods.

Attributes:

  • numer (str) –

    The numerator string

  • denom (str) –

    The normiso string

Functions:

  • latex

    Returns a latex formatted version of the isotope.

  • without_suffix

    Returns a ratio string omitting the numerator and normiso suffix.

Source code in simple/utils.py
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
def asratio(string, without_suffix=False, allow_invalid=False):
    """
    Returns a [``Ratio``][simple.utils.Isotope] string representing the ratio of two isotopes.

    The format of the returned string is the numerator followed by
    a ``/`` followed by the normiso. The numerator and normiso string be parsed by ``asisotope`` together with
    the given ``without_suffix`` and ``allow_invalid`` arguments passed to this function.

    Args:
        string (str): A string contaning two strings seperated by a single ``/``.
        without_suffix (bool): If ``True`` the suffix part of the numerator and normiso string is ignored.
        allow_invalid (bool): Whether the numerator and normiso has to be a valid isotope string.

    If the returned string is an isotope string it will have the following attributes and methods.

    Attributes:
        numer (str): The numerator string
        denom (str): The normiso string

    Methods:
        latex(string): Returns a latex formatted version of the isotope.
        without_suffix(): Returns a ratio string omitting the numerator and normiso suffix.

    """
    if type(string) is Ratio:
        return string
    elif isinstance(string, str):
        string = string.strip()
    else:
        raise TypeError(f'``string`` must a str not {type(string)}')

    try:
        return Ratio(string, without_suffix=without_suffix)
    except ValueError:
        if allow_invalid:
            return string
        else:
            raise

asratios

asratios(strings, without_suffix=False, allow_invalid=False)

Returns a tuple of Ratio strings where each string represents the ratio of two isotopes.

Parameters:

  • strings

    Can either be a string with isotope ratios seperated by a , or a sequence of strings.

  • without_suffix

    If True the suffix part of each isotope string is ignored.

  • allow_invalid

    If False, and a string cannot be parsed into an isotope string, an exception is raised. If True then string.strip() is returned instead.

Source code in simple/utils.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def asratios(strings, without_suffix=False, allow_invalid=False):
    """
    Returns a tuple of [``Ratio``][simple.utils.Isotope] strings where each string represents the ratio of two isotopes.

    Args:
        strings (): Can either be a string with isotope ratios seperated by a ``,`` or a sequence of strings.
        without_suffix (): If ``True`` the suffix part of each isotope string is ignored.
        allow_invalid ():  If ``False``, and a string cannot be parsed into an isotope string, an exception is
            raised. If ``True`` then ``string.strip()`` is returned instead.
    """
    if type(strings) is str:
        strings = [s.strip() for s in strings.split(',')]

    return tuple(asratio(string, without_suffix=without_suffix, allow_invalid=allow_invalid) for string in strings)

create_legend

create_legend(ax, outside=False, outside_margin=0.01, kwargs=None)

Add a legend to a plot.

Parameters:

  • ax

    The working axes. Accepted values are any matplotlib Axes object or plt instance.

  • outside (bool, default: False ) –

    If True the legend will be drawn just outside the upper left corner of the plot. This will overwrite any loc and bbox_to_anchor arguments in kwargs.

  • outside_margin

    Margin between the plot and the legend. Relative to the width of the plot.

  • **kwargs

    Any valid argument for matplotlibs legend function.

Source code in simple/plotting.py
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
@utils.set_default_kwargs()
def create_legend(ax, outside = False, outside_margin=0.01, kwargs=None):
    """
    Add a legend to a plot.

    Args:
        ax (): The working axes. Accepted values are any matplotlib Axes object or plt instance.
        outside (bool): If ``True`` the legend will be drawn just outside the upper left corner of the plot. This will
            overwrite any ``loc`` and ``bbox_to_anchor`` arguments in ``kwargs``.
        outside_margin (): Margin between the plot and the legend. Relative to the width of the plot.
        **kwargs (): Any valid argument for matplotlibs
            [``legend``](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html) function.
    """
    ax = get_axes(ax)

    if outside:
        kwargs['loc'] = 'upper left'
        kwargs['bbox_to_anchor'] = (1+outside_margin, 1)

    kwargs.pop_many(create_legend)
    ax.legend(**kwargs)

create_rose_plot

create_rose_plot(ax=None, *, xscale=1, yscale=1, segment=None, rres=None)

Create a plot with a rose projection.

The rose ax is a subclass of matplotlibs polar axes.

Parameters:

  • ax

    A matplotlib axes object, or an object with a gca() method (e.g. plt). If the axes does not have a rose projection, it will be destroyed and replaced by a new [RoseAxes][(]simple.roseaxes.RoseAxes].

  • xscale

    The scale of the x axis.

  • yscale

    The scale of the y axis.

  • segment

    Which segment of the rose diagram to show. Options are N, E, S, W, NE, SE, SW, NW and None. If None the entire circle is shown.

  • rres

    The resolution of lines drawn along the radius r. The number of points in a line is calculated as

Returns:

  • RoseAxes

    The new rose ax.

Source code in simple/plotting.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
@set_default_kwargs(layout='constrained')
def create_rose_plot(ax=None, *, xscale=1, yscale=1,
                     segment=None, rres=None):
    """
    Create a plot with a [rose projection][simple.roseaxes.RoseAxes].

    The rose ax is a subclass of matplotlibs
    [polar axes](https://matplotlib.org/stable/api/projections/polar.html#matplotlib.projections.polar.PolarAxes).

    Args:
        ax (): A matplotlib axes object, or an object with a ``gca()`` method (e.g. ``plt``). If the
            axes does not have a rose projection, it will be destroyed and replaced by a new [RoseAxes][(]simple.roseaxes.RoseAxes].
        xscale (): The scale of the x axis.
        yscale (): The scale of the y axis.
        segment (): Which segment of the rose diagram to show. Options are ``N``, ``E``, ``S``, ``W``,
            ``NE``, ``SE``, ``SW``, ``NW`` and ``None``. If ``None`` the entire circle is shown.
        rres (): The resolution of lines drawn along the radius ``r``. The number of points in a line is calculated as
        ``r*rres+1`` (Min. 2).

    Returns:
        RoseAxes : The new rose ax.
    """
    if ax is None:
        fig, ax = plt.subplots(subplot_kw={'projection': 'rose'}, layout='constrained')
    else:
        ax = get_axes(ax)
        if ax.name != 'rose':
            logger.warning(f'Wrong Axes projection for rose plot. Deleting axes and creating a new one.')
            subplot_dict = getattr(ax, '_SIMPLE_subplot_dict', None)
            subplot_dict_key = getattr(ax, '_SIMPLE_subplot_dict_key', None)
            fig = ax.get_figure()
            rows, cols, start, stop = ax.get_subplotspec().get_geometry()

            ax.remove()
            ax = fig.add_subplot(rows, cols, start + 1, projection='rose')
            if subplot_dict is not None:
                subplot_dict[subplot_dict_key] = ax
                ax._SIMPLE_subplot_dict = subplot_dict
                ax._SIMPLE_subplot_dict_key = subplot_dict_key

    ax.set_xyscale(xscale, yscale)

    if segment:
        ax.set_xysegment(segment)

    if rres:
        ax.set_rres(rres)

    return ax

create_subplots

create_subplots(mosaic, update_fig=True, kwargs=None)

Create a series of subplots.

See matplotlib's documentation for a more thorough description of the mosaic argument and other possible arguments.

Parameters:

  • mosaic

    A visual layout of how you want your subplots to be arranged. This can either be a nested list of strings or a single string with each subplot represented by a single character, where ; represent a new row.

  • update_fig

    If True (default), the figure will be updated using any kwargs prefixed with fig_.

  • kwargs

    Keyword arguments to go with the mosaic argument. Kwargs prefixed with fig_ will be used with [update_figure][simple.plot.update_figure] to update the figure.

Returns:

  • dict

    A dictionary containing the subplots.

Source code in simple/plotting.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
@add_shortcut('AB', mosaic='AB', fig_size=(12, 5.5))
@add_shortcut('AB_CD', mosaic='AB;CD', fig_size=(12, 11))
@set_default_kwargs(layout='constrained')
def create_subplots(mosaic, update_fig=True, kwargs=None):
    """
    Create a series of subplots.

    See [matplotlib's documentation](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot_mosaic.html#matplotlib.pyplot.subplot_mosaic)
    for a more thorough description of the *mosaic* argument and other possible arguments.

    Args:
        mosaic (): A visual layout of how you want your subplots to be arranged. This can either
            be a nested list of strings or a single string with each subplot represented by a single character, where
            `;` represent a new row.
        update_fig (): If ``True`` (default), the figure will be updated using any *kwargs* prefixed with ``fig_``.
        kwargs (): Keyword arguments to go with the ``mosaic`` argument. Kwargs prefixed with ``fig_`` will be used with
            [`update_figure`][simple.plot.update_figure] to update the figure.

    Returns:
        dict: A dictionary containing the subplots.
    """
    fig_kwargs = kwargs.pop_many(prefix='fig', remove_prefix=False)

    fig, subplots = plt.subplot_mosaic(mosaic, **kwargs)

    update_figure(fig, fig_kwargs, update_fig=update_fig)

    for key, sp in subplots.items():
        sp._SIMPLE_subplot_dict = subplots
        sp._SIMPLE_subplot_dict_name = key

    fig._SIMPLE_subplots = subplots
    return subplots

get_data

get_data(models, axis_names, *, where=None, latex_labels=True, key=None, default_attrname=None, unit=None, default_value=np.nan, key_in_label=None, numer_in_label=None, denom_in_label=None, model_in_label=None, unit_in_label=None, attrname_in_label=None, axis_name_in_label=None, label=True, prefix_label=None, suffix_label=None, mask=None, mask_na=True, kwargs=None)

Get one or more datasets from a group of models together with suitable labels.

Each data point is a dictionary that contains a value for each of the axis given in axis_names plus a label describing the data point. The value for each axis is determined by the key argument. This argument has two possible components; the name of the attribute and the index, or key, to be applied this, or the default_attrname, attribute.

The name of the attribute must start with a . followed by the path to the attribute relative to the Model object using successive . for nested attributes, e.g. .intnorm.eRi.

The index, or key, part of the key can either be an integer, a slice or a sequence of keys seperated by ,. The keys will be parsed into either Isotope, Ratio, or Element strings. If a key is given it is assumed that the attribute contains an isotope key array. Therefore, Element strings will be replaced with all the isotopes of that element present in the attribute (Across all models) and Ratio strings will return the numerator value divided by the denominator value.

If the attribute name is given in key then the index, or key, part must be enclosed in square brackets, e.g. .intnorm.eRi[105Pd]. If the default_attrname should be used then key should only contain the index, or key.

By the default the label for each data point only contains the information is not shared with all other data points. Information that is shared between all data points is instead included in the axis labels.

Parameters:

  • models

    A collection of models to plot. A subselection of these models can be made using the where argument.

  • axis_names
  • where (str, default: None ) –

    If given will be used to create a subselection of models. Any kwargs prefixed with where_ will be supplied as keyword arguments. See [ModelCollection.where][(]simple.models.ModelCollection.where] for more details.

  • latex_labels (bool, default: True ) –

    Whether to use the latex formatting in the labels, when available.

  • key ((str, int, slice), default: None ) –

    This can either be a valid index to the default_attrname array or the path, with or without a valid index, of a different attribute. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • default_attrname

    The name of the default attribute to use if xkey and ykey are indexes. By default, the default key array is used. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • unit

    The desired unit for the xkey and ykey. Different units for xkey and ykey can be specified by supplying a (<xkey_unit>, <ykey_unit>) sequence. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • default_value

    The value given to invalid indexes of arrays. Must have a shape compatible with the size of the indexed array. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • key_in_label (bool, default: None ) –

    Whether to include the key index in the label. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • numer_in_label (bool, default: None ) –

    Whether to include the numerator of a key index in the label. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • denom_in_label (bool, default: None ) –

    Whether to include the denominator of a key index in the label. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • model_in_label (bool, default: None ) –

    Whether to include the model name in the label. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • unit_in_label (bool, default: None ) –

    Whether to include the unit in the label. Accepts either single universal value or a list of values, one for each axis (See below for details).

  • attrname_in_label (bool, default: None ) –

    Whether to include the attribute name in the label. By default the name is only included if it is different from the default_attrname. Accepts a single universal value or a list of values, one for each axis (See below for details).

  • axis_name_in_label (bool, default: None ) –

    Whether to include the axis name in the label. Accepts either single universal value or a value for each axis (See below for details).

  • label ((str, bool, None), default: True ) –

    The label for individual datapoints. Accepts either a single universal value or a list of values, one per data point (See below for details).

  • prefix_label

    Text to be added to the beginning of each data point label. Accepts either a single universal value or a list of values, one per data point (See below for details).

  • suffix_label

    Text to be added at the end of each data point label. Accepts either a single universal value or a list of values, one per data point (See below for details).

  • mask ((str, int, slice), default: None ) –

    Can be used to apply a mask to the data which is plotted. See the get_mask function of the Model object. Accepts either a single universal value or a list of values, one per model (See below for details).

  • mask_na (bool, default: True ) –

    If True masked values will be replaced by np.nan values. Only works if all arrays in a dataset have a float based datatype. Accepts either a single universal value or a list of values, one per model (See below for details).

  • **kwargs
One per axis arguments

These arguments allow you to set a different value for each axis in axis_names. This can be either a single value used for all the axis or a sequence of values, one per axis.

It is also possible to define the value for a specific axis by including a keyword argument consiting of the axis name followed directly by the argument name. The value specified this way will take presidence over the value given by the argument itself. For example xkey=102Pd will set the key argument for the x axis to 102Pd.

One per data point arguments

These arguments allow you to set a different value for each data point. The number of data points is equal to the number of models multiplied by the number of datasets generated. This can be either a single value used for all the axis or a sequence of values, one per data point.

One per model arguments

These arguments allow you to set a different value for each model in models. This can be either a single value used for all the axis or a sequence of values, one per model.

Returns:

  • Tuple[dict, dict]: Two dictionaries containing:

    • A dictionary with the data points for each model, mapped to the model name

    • A dictionary containing labels for each axis, mapped to the axis name.

Examples:

Here is an example of how the return data can be used.

model_datapoints, axis_labels = simple.get_data(models, 'x, y', xkey=..., ykey=...)

# Set the axis labels
plt.set_xlabel(axis_labels['x'])
plt.set_ylabel(axis_labels['y'])

# Iterate though the data and plot it
for model_name, datapoints in model_datapoints.items():
    for dp in datapoints:
        plt.plot(dp['x'], dp['y'], label=dp['label'])
Source code in simple/plotting.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
@utils.set_default_kwargs()
def get_data(models, axis_names, *, where=None, latex_labels = True,
             key=None, default_attrname=None, unit=None, default_value = np.nan,
             key_in_label=None, numer_in_label=None, denom_in_label=None,
             model_in_label=None, unit_in_label=None, attrname_in_label=None, axis_name_in_label=None,
             label = True, prefix_label = None, suffix_label = None,
             mask = None, mask_na = True,
             kwargs = None):
    """
    Get one or more datasets from a group of models together with suitable labels.

    Each data point is a dictionary that contains a value for each of the axis given in *axis_names* plus a label
    describing the data point. The value for each axis is determined by the *key* argument. This argument has two
    possible components; the name of the attribute and the index, or key, to be applied this, or the
    *default_attrname*, attribute.

    The name of the attribute must start with a ``.`` followed by the path to the attribute relative to the Model
    object using successive ``.`` for nested attributes, e.g. ``.intnorm.eRi``.

    The index, or key, part of the *key* can either be an integer, a slice or a sequence of keys seperated by ``,``.
    The keys will be parsed into either [Isotope][simple.utils.Isotope], [Ratio][simple.utils.Ratio], or
    [Element][simple.utils.Element] strings. If a key is given it is assumed that the attribute contains an isotope
    key array. Therefore, Element strings will be replaced with all the isotopes of that element
    present in the attribute (Across all models) and Ratio strings will return the numerator value divided by the
    denominator value.

    If the attribute name is given in *key* then the index, or key, part must be enclosed in square brackets, e.g.
    ``.intnorm.eRi[105Pd]``. If the *default_attrname* should be used then *key* should only contain the index, or key.

    By the default the label for each data point only contains the information is not shared with all other data points.
    Information that is shared between all data points is instead included in the axis labels.

    Args:
        models (): A collection of models to plot. A subselection of these models can be made using the *where*
            argument.
        axis_names ():
        where (str): If given will be used to create a subselection of *models*. Any *kwargs* prefixed
            with ``where_`` will be supplied as keyword arguments. See
             [``ModelCollection.where``][(]simple.models.ModelCollection.where] for more details.
        latex_labels (bool): Whether to use the latex formatting in the labels, when available.
        key (str, int, slice): This can either be a valid index to the *default_attrname* array or the path, with
            or without a valid index, of a different attribute. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        default_attrname (): The name of the default attribute to use if *xkey* and *ykey* are indexes. By default,
            the default key array is used. Accepts either single universal value or a list of values, one for each
            axis (See below for details).
        unit (): The desired unit for the *xkey* and *ykey*. Different units for *xkey* and *ykey* can be specified
            by supplying a ``(<xkey_unit>, <ykey_unit>)`` sequence. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        default_value (): The value given to invalid indexes of arrays. Must have a shape compatible with the size
            of the indexed array. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        key_in_label (bool): Whether to include the key index in the label. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        numer_in_label (bool): Whether to include the numerator of a key index in the label. Accepts either single
            universal value or a list of values, one for each axis (See below for details).
        denom_in_label (bool): Whether to include the denominator of a key index in the label. Accepts either single
            universal value or a list of values, one for each axis (See below for details).
        model_in_label (bool): Whether to include the model name in the label. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        unit_in_label (bool): Whether to include the unit in the label. Accepts either single universal value
            or a list of values, one for each axis (See below for details).
        attrname_in_label (bool): Whether to include the attribute name in the label. By default
            the name is only included if it is different from the *default_attrname*. Accepts a single universal
            value or a list of values, one for each axis (See below for details).
        axis_name_in_label (bool): Whether to include the axis name in the label. Accepts either single universal value
            or a value for each axis (See below for details).
        label (str, bool, None): The label for individual datapoints. Accepts either a single universal value or
            a list of values, one per data point (See below for details).
        prefix_label (): Text to be added to the beginning of each data point label. Accepts either a single universal
            value or a list of values, one per data point (See below for details).
        suffix_label (): Text to be added at the end of each data point label. Accepts either a single universal
            value or a list of values, one per data point (See below for details).
        mask (str, int, slice): Can be used to apply a mask to the data which is plotted. See the
            ``get_mask`` function of the Model object. Accepts either a single universal
            value or a list of values, one per model (See below for details).
        mask_na (bool): If ``True`` masked values will be replaced by ``np.nan`` values. Only works if all arrays
            in a dataset have a float based datatype. Accepts either a single universal
            value or a list of values, one per model (See below for details).
        **kwargs:

    One per axis arguments:
        These arguments allow you to set a different value for each axis in *axis_names*. This can be
        either a single value used for all the axis or a sequence of values, one per axis.

        It is also possible to define the value for a specific axis by  including a keyword argument consiting
        of the axis name followed directly by the argument name. The value specified this way will take presidence over
        the value given by the argument itself. For example ``xkey=102Pd`` will set the *key* argument for
        the *x* axis to ``102Pd``.


    One per data point arguments:
        These arguments allow you to set a different value for each data point. The number of data points is
        equal to the number of models multiplied by the number of datasets generated. This can be
        either a single value used for all the axis or a sequence of values, one per data point.


    One per model arguments:
        These arguments allow you to set a different value for each model in *models*. This can be
        either a single value used for all the axis or a sequence of values, one per model.


    Returns:
        Tuple[dict, dict]: Two dictionaries containing:

            - A dictionary with the data points for each model, mapped to the model name

            - A dictionary containing labels for each axis, mapped to the axis name.

    Examples:
        Here is an example of how the return data can be used.
        ```
        model_datapoints, axis_labels = simple.get_data(models, 'x, y', xkey=..., ykey=...)

        # Set the axis labels
        plt.set_xlabel(axis_labels['x'])
        plt.set_ylabel(axis_labels['y'])

        # Iterate though the data and plot it
        for model_name, datapoints in model_datapoints.items():
            for dp in datapoints:
                plt.plot(dp['x'], dp['y'], label=dp['label'])
        ```

    """

    where_kwargs = kwargs.pop_many(prefix='where')
    models = get_models(models, where=where, where_kwargs=where_kwargs)

    if type(axis_names) is dict:
        axis_name_args = list(axis_names.keys())
        axis_key_args = list(axis_names.values())
    elif type(axis_names) is str:
        if ',' in axis_names:
            axis_name_args = list(n.strip() for n in axis_names.split(','))
        else:
            axis_name_args = list(n.strip() for n in axis_names.split())
        axis_key_args = None
    else:
        raise TypeError('``axis_name`` must be a string or a dict')

    lenargs = len(axis_name_args)
    lenmodels = len(models)

    def one_per_n(n, n_name, arg_name, arg_value):
        if isinstance(arg_value, str) or not isinstance(arg_value, Sequence):
            return [arg_value for i in range(n)]
        elif len(arg_value) == n:
            if type(arg_value) is list:
                return arg_value
            else:
                return list(arg_value)
        else:
            raise ValueError(f'Length of ``{arg_name}`` ({len(arg_value)}) must be equal to number of {n_name} ({n})')

    def one_per_arg(name, value):
        args = one_per_n(lenargs, 'axis', name, value)

        for i, axis in enumerate(axis_name_args):
            if (k:=f'{axis}{name}') in kwargs:
                args[i] = kwargs.pop(k)
            if (k:=f'{axis}{name}') in kwargs:
                args[i] = kwargs.pop(k)

        return args


    def parse_key_string(key, data_arrays):
        try:
            return utils.asisotopes(key), 'iso'
        except:
            pass

        try:
            return utils.asratios(key), 'rat'
        except:
            pass

        try:
            elements =  utils.aselements(key)
        except:
            raise ValueError(f'Unable to parse "{key}" into a sequence of valid Element, Isotope or Ratio string.')
        else:
            # Because the key list should be the same for all models we need to go through them all here
            # incase some have more or less isotopes in the specified data array
            all_isotopes = ()
            for element in elements:
                element_isotopes = []
                for data in data_arrays:
                    if not isinstance(data, (np.ndarray)) or data.dtype.fields is None:
                        raise ValueError(f'Data array "{attrname}" of model {model.name} is not a key array. '
                                         f'Cannot extract isotope keys.')

                    for iso in utils.get_isotopes_of_element(data.dtype.fields, element):
                        if iso not in element_isotopes:
                            element_isotopes.append(iso)
                all_isotopes += tuple(sorted(element_isotopes, key=lambda iso: float(iso.mass)))
            return all_isotopes, 'iso'

    def get_data_label(keylabels, keys, key_in_label, numer_in_label, denom_in_label):
        labels = []
        for key in keys:
            if type(key) is utils.Isotope:
                if key_in_label:
                    label = keylabels.get(key, f"!{key}")
                else:
                    label = ''
            elif key_in_label:
                if numer_in_label and denom_in_label:
                    label = f'{keylabels.get(key.numer, f"!{key.numer}")}/{keylabels.get(key.denom, f"!{key.denom}")} '
                elif numer_in_label:
                    label = keylabels.get(key.numer, f"!{key.numer}")
                elif denom_in_label:
                    label = keylabels.get(key.denom, f"!{key.denom}")
                else:
                    label = ''
            else:
                label = ''
            labels.append(label)
        return labels

    def get_data_index(data_array, index, mi, ai):
        try:
            return data_array[index]
        except ValueError as error:
            if isinstance(index, str):
                logger.warning(f'{models[mi]}.{attrname_a[ai]}: Missing field "{index}" replaced by the default value ({default_value})')
                return np.full(len(data_array), default_value_args[ai])
            else:
                raise error

    if axis_key_args is None:
        axis_key_args = one_per_arg('key', key)

    default_attrname_args = one_per_arg('default_attrname', default_attrname)
    desired_unit_args = one_per_arg('unit', unit)
    default_value_args = one_per_arg('default_value', default_value)
    key_in_label_args = one_per_arg('key_in_label', key_in_label)
    numer_in_label_args = one_per_arg('numer_in_label', numer_in_label)
    denom_in_label_args = one_per_arg('denom_in_label', denom_in_label)
    model_in_label_args = one_per_arg('model_in_label', model_in_label)
    unit_in_label_args = one_per_arg('unit_in_label', unit_in_label)
    attrname_in_label_args = one_per_arg('attrname_in_label', attrname_in_label)
    axis_name_in_label_args = one_per_arg('axis_name_in_label', axis_name_in_label)

    mask_args = one_per_n(lenmodels, 'models', 'mask', mask)
    mask_na_args = one_per_n(lenmodels, 'models', 'mask_na', mask_na)

    # _a -   [arg1, arg2, ...]
    # _am -  [(arg1_model1, arg1_model2, ...), (arg2_model1, arg2_model2, ...)]
    # _amk - [({arg1_model1_key1, arg1_model1_key2, ...}, {arg1_model2_key1, arg1_model2_key2, ...}), ...]
    attrname_a, keys_ak, keytype_a = [], [], []
    data_arrays_am, data_units_am = [], []
    data_label_am, data_keylabels_am = [], []
    for ai, arg in enumerate(axis_key_args):
        if type(arg) is not str:
            attrname = utils.parse_attrname(default_attrname_args[ai])
            key = arg
        else:
            if arg.startswith('.'):
                m = re.match(r'^([A-Za-z0-9_.]+)(?:\[(.*?)\])?$', arg)
                if m:
                    attrname = utils.parse_attrname(m.group(1))
                    key = m.group(2)
                    if attrname_in_label_args[ai] is None:
                        attrname_in_label_args[ai] = True
                else:
                    raise ValueError(f'Invalid arg: {key}')
            else:
                attrname = utils.parse_attrname(default_attrname_args[ai])
                key = arg

        if attrname_in_label_args[ai] is None and attrname is None:
            attrname_in_label_args[ai] = True

        attrname_a.append(attrname)

        # Here we get all the data arrays
        # For this we only need the attrname
        data_arrays_am.append([])
        data_units_am.append([])
        data_label_am.append([])
        data_keylabels_am.append([])
        for model in models:
            data, data_unit = model.get_array(attrname, desired_unit_args[ai])
            data_arrays_am[-1].append(data)
            data_units_am[-1].append(data_unit)

            attr_label, key_labels = model.get_array_labels(attrname, latex=latex_labels)
            data_label_am[-1].append(attr_label)
            data_keylabels_am[-1].append(key_labels)


        # Parse the key
        # Is the key is an element symbol it will extract all isotopes of that element from the data
        # Hence why we need to get the data arrays before this step
        if type(key) is str:
            # Check if key is an integer index or slice
            m = re.match(r'^\s*(-?\d+)\s*$|^\s*(-?\d*)\s*:\s*(-?\d*)\s*(?::\s*(-?\d*))?\s*$', key)
            if m:
                if m.group(1):
                    key = int(m.group(1))
                else:  # Slice
                    key = slice(int(m.group(2)) if m.group(2) is not None else None,
                                int(m.group(3)) if m.group(3) is not None else None,
                                int(m.group(4)) if m.group(4) is not None else None)
                key = (key,)
                keytype = 'index'

            else:
                key, keytype = parse_key_string(key, data_arrays_am[-1])
        elif type(key) is int or type(key) is slice:
            key = (key,)
            keytype = 'index'
        elif key is None:
            key = (key, )
            keytype = 'none'
        else:
            key, keytype = parse_key_string(key, data_arrays_am[-1])

        keys_ak.append(key)
        keytype_a.append(keytype)

    # Make sure the size of the keys is the same for all args
    size = {len(k) for k in keys_ak}
    size.discard(1)
    if len(size) > 1:
        raise ValueError(f'Length of indexes for not compatible {[len(k) for k in attrname_a]}')
    elif len(size) == 1:
        lenkeys = size.pop()
    else:
        lenkeys = 1

    for ai in range(lenargs):
        if len(keys_ak[ai]) != lenkeys:
            # current size can only be 1. Repeat until it is the correct length
            keys_ak[ai] = [keys_ak[ai][0] for i in range(lenkeys)]

    axis_label_args = [kwargs.pop(f'{name}label', True) for name in axis_name_args]
    axis_prefix_label_args = [kwargs.pop(f'{name}prefix_label', '') for name in axis_name_args]
    axis_suffix_label_args = [kwargs.pop(f'{name}suffix_label', '') for name in axis_name_args]
    label_args = one_per_n(lenmodels * lenkeys, 'datapoints', 'label', label)
    prefix_label_args = one_per_n(lenmodels * lenkeys, 'datapoints', 'prefix_label', prefix_label)
    suffix_label_args = one_per_n(lenmodels * lenkeys, 'datapoints', 'suffix_label', suffix_label)

    result_data = {}
    result_axis_label = {}
    data_labels_amk = []

    # Get the arg label which can be used as an axis label
    # Get the data point label for each arg. These are all combined later
    # Model name is not added. It will be added once the individual arg labels have been joined
    for ai in range(lenargs):
        keys = keys_ak[ai]
        keytype = keytype_a[ai]

        # Find common keys that can go into the arg label
        if keytype == 'iso':
            unique_keylabels = set()
            for mi, keylabels in enumerate(data_keylabels_am[ai]):
                if keylabels is None:
                    raise ValueError(f"Data array '{attrname_a[ai]}' of model '{models[mi].name}' is not a key array.")
                unique_keylabels = {*unique_keylabels, *(keylabels.get(k, None) for k in keys)}

            unique_keylabels.discard(None)
            if len(unique_keylabels) == 1: # Same label for all data points
                arg_label = unique_keylabels.pop()
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = False
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = False
            else:
                arg_label = f"<{axis_name_args[ai]}>"
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = True
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = True

        elif keytype == 'rat':
            unique_n_keylabels = {}
            unique_d_keylabels = {}
            for keylabels in data_keylabels_am[ai]:
                if keylabels is None:
                    raise ValueError(f"Data array '{attrname[ai]}' of model '{models[ai].name}' is not a key array.")

                unique_n_keylabels = {*unique_n_keylabels, *(keylabels.get(k.numer, None) for k in keys)}
                unique_d_keylabels = {*unique_d_keylabels, *(keylabels.get(k.denom, None) for k in keys)}

            unique_n_keylabels.discard(None)
            unique_d_keylabels.discard(None)

            if key_in_label_args[ai] is not None:
                if numer_in_label_args[ai] is None:
                    numer_in_label_args[ai] = key_in_label_args[ai]
                if denom_in_label_args[ai] is None:
                    denom_in_label_args[ai] = key_in_label_args[ai]

            if len(unique_n_keylabels) == 1 and len(unique_d_keylabels) == 1:
                arg_label = f"{unique_n_keylabels.pop()} / {unique_d_keylabels.pop()}"
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = False
                if numer_in_label_args[ai] is None:
                    numer_in_label_args[ai] = False
                if denom_in_label_args[ai] is None:
                    denom_in_label_args[ai] = False
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = False
            elif len(unique_n_keylabels) == 1:
                arg_label = f'{unique_n_keylabels.pop()} / <{axis_name_args[ai]}>'
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = True
                if numer_in_label_args[ai] is None:
                    numer_in_label_args[ai] = False
                if denom_in_label_args[ai] is None:
                    denom_in_label_args[ai] = True
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = True
            elif len(unique_d_keylabels) == 1:
                arg_label = f"<{axis_name_args[ai]}> / {unique_d_keylabels.pop()}"
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = True
                if numer_in_label_args[ai] is None:
                    numer_in_label_args[ai] = True
                if denom_in_label_args[ai] is None:
                    denom_in_label_args[ai] = False
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = True
            else:
                arg_label = f"<{axis_name_args[ai]}>"
                if key_in_label_args[ai] is None:
                    key_in_label_args[ai] = True
                if numer_in_label_args[ai] is None:
                    numer_in_label_args[ai] = True
                if denom_in_label_args[ai] is None:
                    denom_in_label_args[ai] = True
                if axis_name_in_label_args[ai] is None:
                    axis_name_in_label_args[ai] = True

        else:
            arg_label = ''

            # Neither are possible so just set to False
            key_in_label_args[ai] = False
            axis_name_in_label_args[ai] = False

        # Create labels for each key
        data_labels_amk.append([])
        if keytype == 'iso' or keytype == 'rat':
            for keylabels in data_keylabels_am[ai]:
                data_labels_amk[-1].append(get_data_label(keylabels, keys,
                                                          key_in_label_args[ai], numer_in_label_args[ai], denom_in_label_args[ai]))
                if attrname_in_label_args[ai] is None:
                    attrname_in_label_args[ai] = False

        else:
            # No keys so just creates an empty label
            data_labels_amk[-1].extend([['' for i in range(lenkeys)] for j in range(lenmodels)])
            if attrname_in_label_args[ai] is None:
                attrname_in_label_args[ai] = True

        # Add the unit either to arg label if common across all models or to each key label
        # [unit] added to the end of the string
        if unit_in_label_args[ai] is not False:
            unique_data_units = {*data_units_am[ai]}
            unique_data_units.discard(None)
            if len(unique_data_units) == 1:
                arg_label = f'{arg_label} [{unique_data_units.pop()}]'
            elif len(unique_data_units) > 1:
                for mi, arg_data_labels_k in enumerate(data_labels_amk[-1]):
                    for ki, key in enumerate(arg_data_labels_k):
                        if data_units_am[ai][mi] is not None:
                            data_labels_amk[-1][mi][ki] = f'{key} [{data_units_am[ai][mi]}]'.strip()

        # Add the attrname either to arg label if common across all models or to each key label
        # arrname added to the start of the string
        if attrname_in_label_args[ai]:
            unique_data_label = {*data_label_am[ai]}
            unique_data_label.discard(None)
            if len(unique_data_label) == 1:
                if arg_label == '':
                    arg_label = unique_data_label.pop().strip()
                else:
                    arg_label = f'{unique_data_label.pop()} | {arg_label}'.strip()
            elif len(unique_data_label) > 1:
                for mi, arg_data_labels_k in enumerate(data_labels_amk[-1]):
                    for ki, key in enumerate(arg_data_labels_k):
                        if data_label_am[ai][mi] is not None:
                            if key == '':
                                data_labels_amk[-1][mi][ki] = data_label_am[ai][mi].strip()
                            else:
                                data_labels_amk[-1][mi][ki] = f'{data_label_am[ai][mi]} | {key}'.strip()

        axis_label_arg = axis_label_args[ai]
        if axis_label_arg is True:
            prefix = axis_prefix_label_args[ai]
            suffix = axis_suffix_label_args[ai]
            if prefix:
                arg_label = f"{prefix}{arg_label}"
            if suffix:
                arg_label = f"{arg_label}{suffix}"

            result_axis_label[axis_name_args[ai]] = arg_label or None
        else:
            result_axis_label[axis_name_args[ai]] = axis_label_arg or None

    has_labels = False
    for mi in range(lenmodels):
        results = []
        for ki in range(lenkeys):
            results.append({})

            label = ''
            for ai in range(lenargs):
                data_array = data_arrays_am[ai][mi]
                keytype = keytype_a[ai]

                if keytype == 'rat':
                    key = keys_ak[ai][ki]
                    n = get_data_index(data_array, key.numer, mi, ai)
                    d = get_data_index(data_array, key.denom, mi, ai)
                    data = n/d

                elif keytype == 'iso' or keytype == 'index':
                    key = keys_ak[ai][ki]
                    data = get_data_index(data_array, key, mi, ai)
                else: # keytype == 'none'
                    data = data_array

                results[-1][axis_name_args[ai]] = data

                data_label = data_labels_amk[ai][mi][ki].strip()
                if data_label != '':
                    if axis_name_in_label_args[ai]:
                        label += f"<{axis_name_args[ai]}: {data_label}>"
                    else:
                        label += data_label

            if mask_args[mi] is not None:
                imask = models[mi].get_mask(mask, **results[-1])
                if mask_na_args[mi] and False not in (np.issubdtype(v.dtype, np.floating) for v in results[-1].values()):
                    for k, v in results[-1].items():
                        v = v.copy()
                        v[np.logical_not(imask)] = np.nan
                        results[-1][k] = v
                else:
                    for k, v in results[-1].items():
                        results[-1][k] = v[imask]

            label_arg = label_args[(mi * lenkeys) + ki]
            if label_arg is True:
                prefix = prefix_label_args[mi * lenkeys + ki]
                suffix = suffix_label_args[mi * lenkeys + ki]

                if model_in_label_args[ai] or (model_in_label_args[ai] is None and lenmodels > 1):
                    if label == '':
                        label = models[mi].name
                    else:
                        label = f'{label} ({models[mi].name})'.strip()
                if type(prefix) is str:
                    label = f"{prefix}{label}"
                if type(suffix) is str:
                    label = f"{label}{suffix}"

                results[-1]['label'] = label.strip() or None
            else:
                results[-1]['label'] = label_arg or None
            if results[-1]['label']:
                has_labels = True

        result_data[models[mi]] = tuple(results)

    if has_labels and kwargs.get('legend', False) is None:
        kwargs['legend'] = True

    return result_data, result_axis_label

get_isotopes_of_element

get_isotopes_of_element(isotopes, element, isotopes_without_suffix=False)

Returns a tuple of all isotopes in a sequence that contain the given element symbol.

Note The strings in isotopes will be passed through asisotopes before the evaluation and therefore do not have to be correcly formatted. Invalid isotope string are allowed but will be ignored by the evaluation.

Parameters:

  • isotopes

    An iterable of strings representing isotopes.

  • element (str) –

    The element symbol.

  • isotopes_without_suffix (bool, default: False ) –

    If True suffixes will be removed from the isotopes in isotopes before the evaluation takes place.

Examples:

>>> simple.utils.get_isotopes_of_element(["Ru-101", "Pd-102", "Rh-103", "Pd-104"], "Pd")
>>> ("Pd-102", "Pd-104")
Source code in simple/utils.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
def get_isotopes_of_element(isotopes, element, isotopes_without_suffix=False):
    """
    Returns a tuple of all isotopes in a sequence that contain the given element symbol.

    **Note** The strings in ``isotopes`` will be passed through [asisotopes][simple.asisotopes] before
    the evaluation and therefore do not have to be correcly formatted. Invalid isotope string are allowed
    but will be ignored by the evaluation.

    Args:
        isotopes (): An iterable of strings representing isotopes.
        element (str): The element symbol.
        isotopes_without_suffix (bool): If ``True`` suffixes will be removed from the isotopes in ``isotopes``
            before the evaluation takes place.

    Examples:
        >>> simple.utils.get_isotopes_of_element(["Ru-101", "Pd-102", "Rh-103", "Pd-104"], "Pd")
        >>> ("Pd-102", "Pd-104")
    """
    isotopes = asisolist(isotopes, without_suffix=isotopes_without_suffix, allow_invalid=True)
    element = aselement(element)
    return tuple(iso for iso in isotopes if (type(iso) is Isotope and iso.element == element))

hist

hist(models, xkey=None, ykey=None, weights=1, r=None, *, sum_weights=True, norm_weights=True, bins=True, fill=None, rescale=False, default_attrname=None, unit=None, weights_default_attrname=None, weights_unit=None, weights_default_value=0, where=None, mask=None, mask_na=True, ax=None, legend=None, update_ax=True, update_fig=True, kwargs=None)

Make a traditional histogram of xkey or ykey, or a circular histogram for the slope of ykey/xkey on axis, for each model in models.

This function retrieves data using get_data and plots it using matplotlib plot for 1d histograms and SIMPLE's RoseAxes.mhist for 2d histograms. It supports optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using keyword prefixes to control axes, figure appearance, legends, and more.

This function is split into two stages: hist_get_data and [hist_draw][simple.plotting.hist_draw], which can be used independently.

Parameters:

  • models (ModelCollection) –

    A collection of models to plot. A subset can be selected using the where argument.

  • xkey, ykey (str, int, or slice) –

    Keys or indices used to retrieve the x and y data arrays. These may refer to array indices (relative to default_attrname) or full attribute paths. See get_data for more information. If only xkey or ykey is specified then a traditional histogram is drawn. If both are specified, then a circular histogram of the slopes is drawn.

  • weights (float or str, default: 1 ) –

    Weighting factor for the histogram. See add_weights for details.

  • r (float, default: None ) –

    Radius of the circular histogram. If None, the radius is automatically determined. A sequence of values can be passed, one for each dataset.

  • sum_weights (bool, default: True ) –

    Whether to sum the weights if multiple weight datasets are present. See add_weights for details.

  • norm_weights (bool, default: True ) –

    Whether to normalise the weights to sum to 1. See add_weights for details.

  • default_attrname (str, default: None ) –

    Name of the default attribute used when xkey or ykey is an index.

  • unit (str or tuple, default: None ) –

    Desired unit(s) for the x and y axes. Use a tuple (xunit, yunit) for different units.

  • where (str, default: None ) –

    Filter expression to select a subset of models. See ModelCollection.where.

  • mask (str, int, or slice, default: None ) –

    Optional mask to apply to the data. See the get_mask method on model instances.

  • mask_na (bool, default: True ) –

    If True, masked values are replaced with np.nan. Only applies if xkey and ykey are float-based.

  • ax (Axes or None, default: None ) –

    The axes to plot on. If None, defaults to plt.gca().

  • legend (bool, default: None ) –

    Whether to add a legend. If None, a legend is shown if at least one datapoint has a label. Legend made using create_legend.

  • update_ax, update_fig (bool) –

    Whether to apply ax_<keyword> and fig_<keyword> arguments using update_axes.

  • kwargs (dict, default: None ) –

    Keyword arguments can be provided either explicitly via kwargs or implicitly via **kwargs. If the same keyword is provided in both, the value in kwargs takes precedence. A description of accepted keywords is provided below.

Accepted keyword arguments

Direct keywords: - Any keyword accepted by simple.get_data(). - color: Can be a list of colours, True for defaults, or False to use black. - linestyle: Can be a list of styles, True for defaults, or False to disable lines. - color_by_model, linestyle_by_model: If True every dataset for each model will be plotted with the same colour/linestyle value. If False, the corresponding datasets for each model will be plotted with the same value. If None the default behaviour is used.

Prefixed keywords: - plt_<keyword>: Keywords passed to the primary plotting function, axline. - where_<keyword>: Keywords passed to the model filtering function, ModelCollection.where. - weights_<keyword>: Keywords passed to add_weights. - ax_<keyword>: Keywords passed to update_axes. - fig_<keyword>: Keywords passed to [update_fig][simple.plotting.update_fig]. - legend_<keyword>: Keywords passed to create_legend. - histogram_<keyword>: Keywords for numpys histogram function. Only used for 1-d histograms. - rose_<keyword>: Keywords passed to [create_rose_plot][simple.roseaxes.create_rose_plot]. Only used for 2-d histograms (and only if the figure is not already a RoseAxes instance).

Axis and data labels

Axis labels are automatically inferred based on shared and unique elements in the data. You can override them using ax_xlabel and ax_ylabel in kwargs. Datapoint labels can be overridden with a list of labels (one per line in the legend).

Shortcuts and default values

This function includes shortcut variants with predefined default values:

  • plot.intnorm: sets default_attrname="intnorm.eRi" and unit=None
  • plot.stdnorm: sets default_attrname="stdnorm.Ri" and unit=None
  • plot.abundance: sets default_attrname="abundance" and unit=None

Default argument values can also be updated through plot.update_kwargs(). Values defined in the function signature are used only if not overridden there. You can retrieve the default arguments using plot.kwargs

Returns:

  • matplotlib.axes.Axes: The axes object used for plotting.

Source code in simple/plotting.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
@utils.add_shortcut('abundance', default_attrname ='abundance', unit=None)
@utils.add_shortcut('stdnorm', default_attrname ='stdnorm.Ri', unit=None)
@utils.add_shortcut('intnorm', default_attrname='intnorm.eRi', unit=None)
@utils.set_default_kwargs(
    linestyle=True, color=True,
    linestyle_by_model = None, color_by_model = None,
    ax_kw_xlabel_fontsize=15,
    ax_kw_ylabel_fontsize=15,
    legend_outside=True,
    ax_tick_params=dict(axis='both', left=True, right=True, top=True),
    fig_size=(7,6.5),
    )
def hist(models, xkey=None, ykey=None, weights=1, r=None, *,
         sum_weights=True, norm_weights=True,
         bins = True, fill=None, rescale=False,
         default_attrname=None, unit=None,
         weights_default_attrname = None, weights_unit=None, weights_default_value=0,
         where=None, mask=None, mask_na = True, ax=None,
         legend=None, update_ax=True, update_fig=True,
         kwargs=None):
    """
    Make a traditional histogram of *xkey* or *ykey*, or a circular histogram for the slope of *ykey*/*xkey*
    on *axis*, for each model in *models*.

    This function retrieves data using [`get_data`][simple.get_data] and plots it using matplotlib
    [`plot`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html) for 1d histograms and
    SIMPLE's [`RoseAxes.mhist`][simple.roseaxes.RoseAxes.mhist] for 2d histograms. It supports
    optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using
    keyword prefixes to control axes, figure appearance, legends, and more.

    This function is split into two stages: [`hist_get_data`][simple.plotting.hist_get_data] and
    [`hist_draw`][simple.plotting.hist_draw], which can be used independently.

    Args:
        models (ModelCollection): A collection of models to plot. A subset can be selected using the *where* argument.
        xkey, ykey (str, int, or slice): Keys or indices used to retrieve the x and y data arrays. These may refer to
            array indices (relative to *default_attrname*) or full attribute paths. See [`get_data`][simple.get_data]
            for more information. If only *xkey* or *ykey* is specified then a traditional histogram is drawn. If
            both are specified, then a circular histogram of the slopes is drawn.
        weights (float or str): Weighting factor for the histogram. See [`add_weights`][simple.add_weights] for
            details.
        r (float): Radius of the circular histogram. If None, the radius is automatically determined. A sequence of
            values can be passed, one for each dataset.
        sum_weights (bool): Whether to sum the weights if multiple weight datasets are present. See
            [`add_weights`][simple.add_weights] for details.
        norm_weights (bool): Whether to normalise the weights to sum to 1. See [`add_weights`][simple.add_weights]
            for details.
        default_attrname (str): Name of the default attribute used when *xkey* or *ykey* is an index.
        unit (str or tuple): Desired unit(s) for the x and y axes. Use a tuple `(xunit, yunit)` for different units.
        where (str): Filter expression to select a subset of *models*. See
            [`ModelCollection.where`][simple.models.ModelCollection.where].
        mask (str, int, or slice): Optional mask to apply to the data. See the `get_mask` method on model instances.
        mask_na (bool): If True, masked values are replaced with `np.nan`. Only applies if *xkey* and *ykey* are
            float-based.
        ax (matplotlib.axes.Axes or None): The axes to plot on. If None, defaults to `plt.gca()`.
        legend (bool): Whether to add a legend. If `None`, a legend is shown if at least one datapoint has a label.
            Legend made using [`create_legend`][simple.plotting.create_legend].
        update_ax, update_fig (bool): Whether to apply `ax_<keyword>` and `fig_<keyword>` arguments using
            [`update_axes`][simple.plotting.update_axes].
        kwargs (dict, optional): Keyword arguments can be provided either explicitly via `kwargs` or implicitly via
            `**kwargs`. If the same keyword is provided in both, the value in kwargs takes precedence. A description of
            accepted keywords is provided below.

    Accepted keyword arguments:
        Direct keywords:
            - Any keyword accepted by [`simple.get_data()`][simple.get_data].
            - `color`: Can be a list of colours, `True` for defaults, or `False` to use black.
            - `linestyle`: Can be a list of styles, `True` for defaults, or `False` to disable lines.
            - `color_by_model`, `linestyle_by_model`: If `True` every dataset for each model will be
              plotted with the same colour/linestyle value. If `False`, the corresponding datasets for each model
              will be plotted with the same value. If `None` the default behaviour is used.


        Prefixed keywords:
            - `plt_<keyword>`: Keywords passed to the primary plotting function, [`axline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html).
            - `where_<keyword>`: Keywords passed to the model filtering function, [`ModelCollection.where`][simple.models.ModelCollection.where].
            - `weights_<keyword>`: Keywords passed to [`add_weights`][simple.add_weights].
            - `ax_<keyword>`: Keywords passed to [`update_axes`][simple.plotting.update_axes].
            - `fig_<keyword>`: Keywords passed to [`update_fig`][simple.plotting.update_fig].
            - `legend_<keyword>`: Keywords passed to [`create_legend`][simple.plotting.create_legend].
            - `histogram_<keyword>`: Keywords for numpys
                [`histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html) function. Only
                used for 1-d histograms.
            - `rose_<keyword>`: Keywords passed to [`create_rose_plot`][simple.roseaxes.create_rose_plot]. Only used
                for 2-d histograms (and only if the figure is not already a `RoseAxes` instance).


    Axis and data labels:
        Axis labels are automatically inferred based on shared and unique elements in the data. You can override them
        using `ax_xlabel` and `ax_ylabel` in *kwargs*. Datapoint labels can be overridden with a list of labels
        (one per line in the legend).

    Shortcuts and default values:
        This function includes shortcut variants with predefined default values:

        - `plot.intnorm`: sets `default_attrname="intnorm.eRi"` and `unit=None`
        - `plot.stdnorm`: sets `default_attrname="stdnorm.Ri"` and `unit=None`
        - `plot.abundance`: sets `default_attrname="abundance"` and `unit=None`

        Default argument values can also be updated through `plot.update_kwargs()`. Values defined in the function
        signature are used only if not overridden there. You can retrieve the default arguments using `plot.kwargs`

    Returns:
        matplotlib.axes.Axes: The axes object used for plotting.
    """

    modeldata, axis_labels, axis = hist_get_data(models, xkey, ykey, weights,
                                                 sum_weights=sum_weights, norm_weights=norm_weights,
                                                 default_attrname=default_attrname, unit=unit,
                                                 weights_default_attrname=weights_default_attrname,
                                                 weights_unit=weights_unit, weights_default_value=weights_default_value,
                                                 where=where, mask=mask, mask_na=mask_na, kwargs=kwargs)

    if axis == 'xy':
        # 2d - circular histogram
        return hist_draw2d(modeldata, axis_labels, r, bins=bins, fill=fill, rescale=rescale,
                             legend=legend, update_ax=update_ax, update_fig=update_fig,
                             ax=ax, kwargs=kwargs)
    else:
        # 1d - traditional histogram
        return hist_draw1d(modeldata, axis_labels, axis, bins=bins, fill=fill, rescale=rescale,
                             legend=legend, update_ax=update_ax, update_fig=update_fig,
                             ax=ax, kwargs=kwargs)

hist_ccsne

hist_ccsne(models, xkey=None, ykey=None, weights=1, r=None, kwargs=None)

CCSNe implementation of hist. See this function for more details and a description of the optional arguments.

Note Weights are calculated using add_weights_ccsne where each weight is multiplied by the mass associated with each mass coordinate in CCSNe models.

Source code in simple/ccsne.py
817
818
819
820
821
822
823
824
825
826
827
828
829
@utils.set_default_kwargs(inherits_=plotting.hist,
                                  weights_default_attrname='abundance', weights_unit='mass',
                                  )
def hist_ccsne(models, xkey=None, ykey=None, weights=1, r=None, kwargs=None):
    """
    CCSNe implementation of [`hist`][simple.hist]. See this function for more details and a
    description of the optional arguments.

    **Note** Weights are calculated using [`add_weights_ccsne`][simple.ccsne.add_weights_ccsne] where each
    weight is multiplied by the mass associated with each mass coordinate in CCSNe models.
    """
    kwargs.setdefault('SIMPLE_add_weights', add_weights_ccsne)
    return plotting.hist(models, xkey, ykey, weights=weights, r=r, kwargs=kwargs)

load_collection

load_collection(filename, dbfilename=None, *, default_isolist=None, convert_unit=True, overwrite=False, where=None, **where_kwargs)

Loads a selection of models from a file.

If that file does not exist it will create the file from the specified models file. Only when doing this is the default_isolist applied. If filename already exits the assumption is it has the correct isolist.

*Notes

The entire file will be read into memory. This might be an issue if reading very large files. The hdf5 are compressed so will be significantly larger when stored in memory.

When reading the database file to create a subselection of the data using default_isolist, the subselection is made when each model is loaded which reduces the amount of memory used.

Parameters:

  • filename (str) –

    Name of the file to load or create.

  • dbfilename (str, default: None ) –

    Name of the _func models file

  • default_isolist

    Isolist applied to loaded models from dbfilename.

  • convert_units (bool) –

    If True and data is stored in a mass unit all values will be divided by the mass number of the isotope before summing values together. The final value is then multiplied by the mass number of the output isotope.

  • overwrite (bool, default: False ) –

    If True a new file will be created even if filename already exists.

  • where (str, default: None ) –

    Used to select which models to load.

  • **where_kwargs

    Keyword arguments used in combination with where.

Returns:

Source code in simple/models.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def load_collection(filename, dbfilename=None, *, default_isolist=None, convert_unit=True, overwrite=False,
                    where=None, **where_kwargs):
    """
    Loads a selection of models from a file.

    If that file does not exist it will create the file from the specified models file. Only when doing this
    is the ``default_isolist`` applied. If ``filename`` already exits the **assumption** is it has the correct isolist.

    ***Notes**

    The entire file will be read into memory. This might be an issue if reading very large files. The hdf5 are
    compressed so will be significantly larger when stored in memory.

    When reading the database file to create a subselection of the data using ``default_isolist``, the subselection is
     made when each model is loaded which reduces the amount of memory used.

    Args:
        filename (str): Name of the file to load or create.
        dbfilename (str): Name of the _func models file
        default_isolist (): Isolist applied to loaded models from ``dbfilename``.
        convert_units (bool): If ``True``  and data is stored in a mass unit all values will be divided by the
            mass number of the isotope before summing values together. The final value is then multiplied by the
            mass number of the output isotope.
        overwrite (bool): If ``True`` a new file will be created even if ``filename`` already exists.
        where (str): Used to select which models to load.
        **where_kwargs (): Keyword arguments used in combination with ``where``.

    Returns:
        A [ModelCollection][simple.models.ModelCollection] object containing all the loaded models.
    """
    mc = ModelCollection()
    if os.path.exists(filename) and not overwrite:
        logger.info(f'Loading existing file: {filename}')
        mc.load_file(filename, where=where, **where_kwargs)
    elif filename[-5:].lower() != '.hdf5' and os.path.exists(f'{filename}.hdf5') and not overwrite:
        logger.info(f'Loading existing file: {filename}.hdf5')
        mc.load_file(f'{filename}.hdf5', where=where, **where_kwargs)
    elif dbfilename is None:
        raise ValueError(f'File {filename} does not exist')
    elif os.path.exists(dbfilename):
        logger.info(f'Creating: "{filename}" from database: "{dbfilename}"')
        mc.load_file(dbfilename, isolist=default_isolist, convert_unit=convert_unit, where=where, **where_kwargs)
        mc.save(filename)
    else:
        raise ValueError(f'Neither "{filename}" or "{dbfilename}" exist')
    return mc

load_defaults

load_defaults(filename)

Loads default arguments for functions from a YAML formatted file.

To use a set of default values, unpack the arguments in the function call (See example).

You can still arguments and keyword arguments as normal as long as they are not included in the default dictionary.

Returns:

  • A named dictionary mapping the prefixes given in the yaml file to another dictionary mapping the arguments

  • to the specified values.

Examples:

The file default.yaml is expected to look like this:

somefunction:
    arg: value
    listarg:
        - first thing in list
        - second thing in list

anotherfunction:
    arg: value

It can be used like this

>>> defaults = simple.load_defaults('defaults.yaml')
>>> somefunction(**defaults['somefunction']) # Unpack arguments into function call
Source code in simple/utils.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def load_defaults(filename: str):
    """
    Loads default arguments for functions from a YAML formatted file.

    To use a set of default values, unpack the arguments in the function call (See example).

    You can still arguments and keyword arguments as normal as long as they are not included in the default dictionary.

    Returns:
        A named dictionary mapping the prefixes given in the yaml file to another dictionary mapping the arguments
        to the specified values.

    Examples:
        The file ``default.yaml`` is expected to look like this:
        ```
        somefunction:
            arg: value
            listarg:
                - first thing in list
                - second thing in list

        anotherfunction:
            arg: value
        ```

        It can be used like this
        >>> defaults = simple.load_defaults('defaults.yaml')
        >>> somefunction(**defaults['somefunction']) # Unpack arguments into function call


    """
    return dict(yaml.safe_load(open(filename, 'r').read()))

new_collection

new_collection()

Return an empty ModelCollection object.

Source code in simple/models.py
168
169
170
171
172
def new_collection():
    """
    Return an empty [ModelCollection][simple.models.ModelCollection] object.
    """
    return ModelCollection()

plot

plot(models, xkey, ykey, *, default_attrname=None, unit=None, where=None, mask=None, mask_na=True, ax=None, legend=None, update_ax=True, update_fig=True, hist=False, hist_size=0.3, hist_pad=0.05, kwargs=None)

Plot xkey against ykey for each model in models.

This function retrieves data using get_data and plots it using matplotlib. It supports optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using keyword prefixes to control axes, figure appearance, legends, and more.

This function is split into two stages: plot_get_data and plot_draw, which can be used independently.

Parameters:

  • models (ModelCollection) –

    A collection of models to plot. A subset can be selected using the where argument.

  • xkey, ykey (str, int, or slice) –

    Keys or indices used to retrieve the x and y data arrays. These may refer to array indices (relative to default_attrname) or full attribute paths. See get_data for more.

  • default_attrname (str, default: None ) –

    Name of the default attribute used when xkey or ykey is an index.

  • unit (str or tuple, default: None ) –

    Desired unit(s) for the x and y axes. Use a tuple (xunit, yunit) for different units. where (str): Filter expression to select a subset of models. See ModelCollection.where.

  • mask (str, int, or slice, default: None ) –

    Optional mask to apply to the data. See the get_mask method on model instances.

  • mask_na (bool, default: True ) –

    If True, masked values are replaced with np.nan. Only applies if xkey and ykey are float-based.

  • ax (Axes or None, default: None ) –

    The axes to plot on. If None, defaults to plt.gca().

  • legend (bool, default: None ) –

    Whether to add a legend. If None, a legend is shown if at least one datapoint has a label. Legend made using create_legend.

  • update_ax, update_fig (bool) –

    Whether to apply ax_<keyword> and fig_<keyword> arguments using update_axes.

  • hist (bool, default: False ) –

    Whether to show marginal histograms along the axis.

  • hist_size (float, default: 0.3 ) –

    Relative size of the histogram axes.

  • hist_pad (float, default: 0.05 ) –

    Padding between the main plot and histogram axes.

  • kwargs (dict, default: None ) –

    Keyword arguments can be provided either explicitly via kwargs or implicitly via **kwargs. If the same keyword is provided in both, the value in kwargs takes precedence. A description of accepted keywords is provided below.

  • Accepted keyword arguments

    Direct keywords: - Any keyword accepted by simple.get_data. - color: Can be a list of colours, True for defaults, or False to use black. - linestyle: Can be a list of styles, True for defaults, or False to disable lines. - marker: Can be a list of markers, True for defaults, or False to disable markers. - color_by_model, linestyle_by_model, marker_by_model: If True every dataset for each model will be plotted with the same colour/linestyle/maker value. If False, the corresponding datasets for each model will be plotted with the same value. If None the default behaviour is used. - yhist, xhist: If True, show a histogram along the specified axis. Takes precedence over `hist'.

    Prefixed keywords: - plt_<keyword>: Keywords passed to the primary plotting function, axline. - where_<keyword>: Keywords passed to the model filtering function, ModelCollection.where. - ax_<keyword>: Keywords passed to update_axes. - fig_<keyword>: Keywords passed to [update_fig][simple.plotting.update_fig]. - legend_<keyword>: Keywords passed to create_legend. - hist_<keyword>: Default keywords for xhist_<keyword> and yhist_<keyword>. - xhist_<keyword>: Keywords passed to [axhist][simple.plotting.axhist] for the x axis. - yhist_<keyword>: Keywords passed to [axhist][simple.plotting.axhist] for the y axis.

Axis and data labels

Axis labels are automatically inferred based on shared and unique elements in the data. You can override them using ax_xlabel and ax_ylabel in kwargs. Datapoint labels can be overridden with a list of labels (one per line in the legend).

Shortcuts and default values

This function includes shortcut variants with predefined argument:

  • plot.intnorm: sets default_attrname="intnorm.eRi" and unit=None
  • plot.stdnorm: sets default_attrname="stdnorm.Ri" and unit=None
  • plot.abundance: sets default_attrname="abundance" and unit=None

Default argument values can also be updated through plot.update_kwargs(). Values defined in the function signature are used only if not overridden there. You can retrieve the default arguments using plot.kwargs

Returns:

  • matplotlib.axes.Axes: The axes object used for plotting.

Source code in simple/plotting.py
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
@utils.add_shortcut('abundance', default_attrname ='abundance', unit=None)
@utils.add_shortcut('stdnorm', default_attrname ='stdnorm.Ri', unit=None)
@utils.add_shortcut('intnorm', default_attrname='intnorm.eRi', unit=None)
@utils.set_default_kwargs(
    linestyle=False, color=True, marker=True,
    linestyle_by_model = None, color_by_model = None, marker_by_model = None,
    ax_kw_xlabel_fontsize=15,
    ax_kw_ylabel_fontsize=15,
    plt_markersize=4,
    legend_outside=True,
    ax_tick_params=dict(axis='both', left=True, right=True, top=True),
    fig_size=(7,6.5),
    )
def plot(models, xkey, ykey, *,
         default_attrname=None, unit=None,
         where=None, mask = None, mask_na = True, ax = None,
         legend = None, update_ax = True, update_fig = True,
         hist=False, hist_size=0.3, hist_pad=0.05, kwargs=None):
    """
    Plot *xkey* against *ykey* for each model in *models*.

    This function retrieves data using [`get_data`][simple.get_data] and plots it using matplotlib. It supports
    optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using
    keyword prefixes to control axes, figure appearance, legends, and more.

    This function is split into two stages: [`plot_get_data`][simple.plotting.plot_get_data] and
    [`plot_draw`][simple.plotting.plot_draw], which can be used independently.

    Args:
        models (ModelCollection): A collection of models to plot. A subset can be selected using the *where* argument.
        xkey, ykey (str, int, or slice): Keys or indices used to retrieve the x and y data arrays. These may refer to
            array indices (relative to *default_attrname*) or full attribute paths.
            See [`get_data`][simple.get_data] for more.
        default_attrname (str): Name of the default attribute used when *xkey* or *ykey* is an index.
        unit (str or tuple): Desired unit(s) for the x and y axes. Use a tuple `(xunit, yunit)` for different units.
         where (str): Filter expression to select a subset of *models*. See
            [`ModelCollection.where`][simple.models.ModelCollection.where].
        mask (str, int, or slice): Optional mask to apply to the data. See the `get_mask` method on model instances.
        mask_na (bool): If True, masked values are replaced with `np.nan`. Only applies if *xkey* and *ykey* are
            float-based.
        ax (matplotlib.axes.Axes or None): The axes to plot on. If None, defaults to `plt.gca()`.
        legend (bool): Whether to add a legend. If `None`, a legend is shown if at least one datapoint has a label.
            Legend made using [`create_legend`][simple.plotting.create_legend].
        update_ax, update_fig (bool): Whether to apply `ax_<keyword>` and `fig_<keyword>` arguments using
            [`update_axes`][simple.plotting.update_axes].
        hist (bool): Whether to show marginal histograms along the axis.
        hist_size (float): Relative size of the histogram axes.
        hist_pad (float): Padding between the main plot and histogram axes.
        kwargs (dict, optional): Keyword arguments can be provided either explicitly via `kwargs` or implicitly via
            `**kwargs`. If the same keyword is provided in both, the value in kwargs takes precedence. A description of
            accepted keywords is provided below.


        Accepted keyword arguments:
            Direct keywords:
                - Any keyword accepted by [`simple.get_data`][simple.get_data].
                - `color`: Can be a list of colours, `True` for defaults, or `False` to use black.
                - `linestyle`: Can be a list of styles, `True` for defaults, or `False` to disable lines.
                - `marker`: Can be a list of markers, `True` for defaults, or `False` to disable markers.
                - `color_by_model`, `linestyle_by_model`, `marker_by_model`: If `True` every dataset for each model will be
                  plotted with the same colour/linestyle/maker value. If `False`, the corresponding datasets for each model
                  will be plotted with the same value. If `None` the default behaviour is used.
                - `yhist`, `xhist`: If `True`, show a histogram along the specified axis. Takes precedence over `hist'.


            Prefixed keywords:
                - `plt_<keyword>`: Keywords passed to the primary plotting function, [`axline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html).
                - `where_<keyword>`: Keywords passed to the model filtering function, [`ModelCollection.where`][simple.models.ModelCollection.where].
                - `ax_<keyword>`: Keywords passed to [`update_axes`][simple.plotting.update_axes].
                - `fig_<keyword>`: Keywords passed to [`update_fig`][simple.plotting.update_fig].
                - `legend_<keyword>`: Keywords passed to [`create_legend`][simple.plotting.create_legend].
                - `hist_<keyword>`: Default keywords for `xhist_<keyword>` and `yhist_<keyword>`.
                - `xhist_<keyword>`: Keywords passed to [`axhist`][simple.plotting.axhist] for the x axis.
                - `yhist_<keyword>`: Keywords passed to [`axhist`][simple.plotting.axhist] for the y axis.

    Axis and data labels:
        Axis labels are automatically inferred based on shared and unique elements in the data. You can override them
        using `ax_xlabel` and `ax_ylabel` in *kwargs*. Datapoint labels can be overridden with a list of labels
        (one per line in the legend).


    Shortcuts and default values:
        This function includes shortcut variants with predefined argument:

        - `plot.intnorm`: sets `default_attrname="intnorm.eRi"` and `unit=None`
        - `plot.stdnorm`: sets `default_attrname="stdnorm.Ri"` and `unit=None`
        - `plot.abundance`: sets `default_attrname="abundance"` and `unit=None`

        Default argument values can also be updated through `plot.update_kwargs()`. Values defined in the function
        signature are used only if not overridden there. You can retrieve the default arguments using `plot.kwargs`


    Returns:
        matplotlib.axes.Axes: The axes object used for plotting.
    """

    modeldata, axis_labels = plot_get_data(models, xkey, ykey,
                                           default_attrname=default_attrname, unit=unit,
                                           where=where, mask=mask, mask_na=mask_na, hist=hist,
                                           kwargs=kwargs)
    return plot_draw(modeldata, axis_labels, ax=ax, legend=legend,
                     update_ax=update_ax, update_fig=update_fig,
                     hist=hist, hist_size=hist_size, hist_pad=hist_pad,
                     kwargs=kwargs)

plot_ccsne

plot_ccsne(models, ykey, *, semilog=False, onion=None, kwargs=None)

CCSNe implementation of the plot function where you specify the data on the y-axis which is automatically plotted against the mass coordinates on the x-axis. See this function for more details and a description of the optional arguments.

If a single model is shown, then by default the onion shell structure is also drawn if onion=True or if onion=None.

The y-axis is drawn on a logarithmic scale if semilog=True.

Note Weights are calculated using add_weights_ccsne where each weight is multiplied by the mass associated with each mass coordinate in CCSNe models.

Source code in simple/ccsne.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
@utils.set_default_kwargs(inherits_=plotting.plot,
                                  linestyle=True, marker=False, fig_size=(10,5),
                                  xhist=False)
def plot_ccsne(models, ykey, *,
         semilog = False, onion=None,
         kwargs=None):
    """
    CCSNe implementation of the [`plot`][simple.plot] function where you specify the data on the y-axis which is
    automatically plotted against the mass coordinates on the x-axis. See this function for more details and a
    description of the optional arguments.

    If a single model is shown, then by default the onion shell structure is also drawn if
    `onion=True` or if `onion=None`.

    The y-axis is drawn on a logarithmic scale if `semilog=True`.

    **Note** Weights are calculated using [`add_weights_ccsne`][simple.ccsne.add_weights_ccsne] where each
    weight is multiplied by the mass associated with each mass coordinate in CCSNe models.
    """

    onion_kwargs = kwargs.pop_many(prefix=['onion', 'zone'])
    if semilog: kwargs.setdefault('ax_yscale', 'log')
    kwargs.setdefault('SIMPLE_add_weights', add_weights_ccsne)

    modeldata, axis_labels = plotting.plot_get_data(models, '.masscoord', ykey,
                                           xunit=None, kwargs=kwargs)

    ax = plotting.plot_draw(modeldata, axis_labels, kwargs=kwargs)

    if onion or (onion is None and len(modeldata) == 1):
        if len(modeldata) > 1:
            raise ValueError(f"Can only plot onion structure for a single model")
        else:
            plot_zonal_structure(list(modeldata.keys())[0], ax=ax, **onion_kwargs)

    return ax

set_logging_level

set_logging_level(level)

Set the level of messages to be displayed.

Options are: DEBUG, INFO, WARNING, ERROR.

Source code in simple/utils.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def set_logging_level(level):
    """
    Set the level of messages to be displayed.

    Options are: DEBUG, INFO, WARNING, ERROR.
    """
    if level.upper() == 'DEBUG':
        level = logging.DEBUG
    elif level.upper() == 'INFO':
        level = logging.INFO
    elif level.upper() == 'WARNING':
        level = logging.WARNING
    elif level.upper() == 'ERROR':
        level = logging.ERROR

    SimpleLogger.setLevel(level)

slope

slope(models, xkey, ykey, xycoord=(0, 0), *, arrow=True, arrow_position=0.9, default_attrname=None, unit=None, where=None, mask=None, mask_na=True, ax=None, legend=None, update_ax=True, update_fig=True, kwargs=None)

Plot the slope of ykey/xkey for each model in models.

This function retrieves data using get_data and plots it using matplotlib axline. It supports optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using keyword prefixes to control axes, figure appearance, legends, and more.

This function is split into two stages: slope_get_data and slope_draw, which can be used independently.

Parameters:

  • models (ModelCollection) –

    A collection of models to plot. A subset can be selected using the where argument.

  • xkey, ykey (str, int, or slice) –

    Keys or indices used to retrieve the x and y data arrays. These may refer to array indices (relative to default_attrname) or full attribute paths. See get_data for more information.

  • xycoord (tuple, default: (0, 0) ) –

    Coordinates to a point the slope passes through. Defaults to (0, 0).

  • arrow (bool, default: True ) –

    Whether to draw arrows indicating the direction of the endmember given by the x and y coordinates.

  • arrow_position (float, default: 0.9 ) –

    Relative position of the arrow on the line. Defaults to 0.9.

  • default_attrname (str, default: None ) –

    Name of the default attribute used when xkey or ykey is an index.

  • unit (str or tuple, default: None ) –

    Desired unit(s) for the x and y axes. Use a tuple (xunit, yunit) for different units.

  • where (str, default: None ) –

    Filter expression to select a subset of models. See ModelCollection.where.

  • mask (str, int, or slice, default: None ) –

    Optional mask to apply to the data. See the get_mask method on model instances.

  • mask_na (bool, default: True ) –

    If True, masked values are replaced with np.nan. Only applies if xkey and ykey are float-based.

  • ax (Axes or None, default: None ) –

    The axes to plot on. If None, defaults to plt.gca().

  • legend (bool, default: None ) –

    Whether to add a legend. If None, a legend is shown if at least one datapoint has a label. Legend made using create_legend.

  • update_ax, update_fig (bool) –

    Whether to apply ax_<keyword> and fig_<keyword> arguments using update_axes.

  • kwargs (dict, default: None ) –

    Keyword arguments can be provided either explicitly via kwargs or implicitly via **kwargs. If the same keyword is provided in both, the value in kwargs takes precedence. A description of accepted keywords is provided below.

Accepted keyword arguments

Direct keywords: - Any keyword accepted by simple.get_data. - color: Can be a list of colours, True for defaults, or False to use black. - linestyle: Can be a list of styles, True for defaults, or False to disable lines. - color_by_model, linestyle_by_model: If True every dataset for each model will be plotted with the same colour/linestyle value. If False, the corresponding datasets for each model will be plotted with the same value. If None the default behaviour is used.

Prefixed keywords: - plt_<keyword>: Keywords passed to the primary plotting function, axline. - where_<keyword>: Keywords passed to the model filtering function, ModelCollection.where. - ax_<keyword>: Keywords passed to update_axes. - fig_<keyword>: Keywords passed to [update_fig][simple.plotting.update_fig]. - legend_<keyword>: Keywords passed to create_legend. - arrow_<keyword>: Keywords passed to matplotlib.axes.Axes.arrow.

Axis and data labels

Axis labels are automatically inferred based on shared and unique elements in the data. You can override them using ax_xlabel and ax_ylabel in kwargs. Datapoint labels can be overridden with a list of labels (one per line in the legend).

Shortcuts and default values

This function includes shortcut variants with predefined argument:

  • slope.intnorm: sets default_attrname="intnorm.eRi" and unit=None
  • slope.stdnorm: sets default_attrname="stdnorm.Ri" and unit=None
  • slope.abundance: sets default_attrname="abundance" and unit=None

Default argument values can also be updated through slope.update_kwargs(). Values defined in the function signature are used only if not overridden there. You can retrieve the default arguments using slope.kwargs.

Returns:

  • matplotlib.axes.Axes: The axes object used for plotting.

Source code in simple/plotting.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
@utils.add_shortcut('abundance', default_attrname ='abundance', unit=None)
@utils.add_shortcut('stdnorm', default_attrname ='stdnorm.Ri', unit=None)
@utils.add_shortcut('intnorm', default_attrname='intnorm.eRi', unit=None)
@utils.set_default_kwargs(
    linestyle=True, color=True,
    linestyle_by_model = None, color_by_model = None,
    ax_kw_xlabel_fontsize=15,
    ax_kw_ylabel_fontsize=15,
    legend_outside=True,
    ax_tick_params=dict(axis='both', left=True, right=True, top=True),
    fig_size=(7,6.5),
    arrow_linewidth=0, arrow_length_includes_head=True, arrow_head_width=0.05,
    arrow_zorder=3
    )
def slope(models, xkey, ykey, xycoord=(0, 0), *,
          arrow=True, arrow_position=0.9,
          default_attrname=None, unit=None,
          where=None, mask = None, mask_na = True, ax = None,
          legend = None, update_ax = True, update_fig = True,
          kwargs=None):

    """
    Plot the slope of *ykey*/*xkey* for each model in *models*.

    This function retrieves data using [`get_data`][simple.get_data] and plots it using matplotlib
    [`axline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html). It supports
    optional filtering, masking, and per-model or per-dataset styling. Additional arguments can be passed using
    keyword prefixes to control axes, figure appearance, legends, and more.

    This function is split into two stages: [`slope_get_data`][simple.plotting.slope_get_data] and
    [`slope_draw`][simple.plotting.slope_draw], which can be used independently.


    Args:
        models (ModelCollection): A collection of models to plot. A subset can be selected using the *where* argument.
        xkey, ykey (str, int, or slice): Keys or indices used to retrieve the x and y data arrays. These may refer to
            array indices (relative to *default_attrname*) or full attribute paths. See [`get_data`][simple.get_data]
            for more information.
        xycoord (tuple): Coordinates to a point the slope passes through. Defaults to `(0, 0)`.
        arrow (bool): Whether to draw arrows indicating the direction of the endmember given by the x and y coordinates.
        arrow_position (float): Relative position of the arrow on the line. Defaults to 0.9.
        default_attrname (str): Name of the default attribute used when *xkey* or *ykey* is an index.
        unit (str or tuple): Desired unit(s) for the x and y axes. Use a tuple `(xunit, yunit)` for different units.
        where (str): Filter expression to select a subset of *models*. See
            [`ModelCollection.where`][simple.models.ModelCollection.where].
        mask (str, int, or slice): Optional mask to apply to the data. See the `get_mask` method on model instances.
        mask_na (bool): If True, masked values are replaced with `np.nan`. Only applies if *xkey* and *ykey* are
            float-based.
        ax (matplotlib.axes.Axes or None): The axes to plot on. If None, defaults to `plt.gca()`.
        legend (bool): Whether to add a legend. If `None`, a legend is shown if at least one datapoint has a label.
            Legend made using [`create_legend`][simple.plotting.create_legend].
        update_ax, update_fig (bool): Whether to apply `ax_<keyword>` and `fig_<keyword>` arguments using
            [`update_axes`][simple.plotting.update_axes].
        kwargs (dict, optional): Keyword arguments can be provided either explicitly via `kwargs` or implicitly via
            `**kwargs`. If the same keyword is provided in both, the value in kwargs takes precedence. A description of
            accepted keywords is provided below.


    Accepted keyword arguments:
        Direct keywords:
            - Any keyword accepted by [`simple.get_data`][simple.get_data].
            - `color`: Can be a list of colours, `True` for defaults, or `False` to use black.
            - `linestyle`: Can be a list of styles, `True` for defaults, or `False` to disable lines.
             - `color_by_model`, `linestyle_by_model`: If `True` every dataset for each model will be
              plotted with the same colour/linestyle value. If `False`, the corresponding datasets for each model
              will be plotted with the same value. If `None` the default behaviour is used.


        Prefixed keywords:
            - `plt_<keyword>`: Keywords passed to the primary plotting function, [`axline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html).
            - `where_<keyword>`: Keywords passed to the model filtering function, [`ModelCollection.where`][simple.models.ModelCollection.where].
            - `ax_<keyword>`: Keywords passed to [`update_axes`][simple.plotting.update_axes].
            - `fig_<keyword>`: Keywords passed to [`update_fig`][simple.plotting.update_fig].
            - `legend_<keyword>`: Keywords passed to [`create_legend`][simple.plotting.create_legend].
            - `arrow_<keyword>`: Keywords passed to [`matplotlib.axes.Axes.arrow`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.arrow.html).


    Axis and data labels:
        Axis labels are automatically inferred based on shared and unique elements in the data. You can override them
        using `ax_xlabel` and `ax_ylabel` in *kwargs*. Datapoint labels can be overridden with a list of labels
        (one per line in the legend).


    Shortcuts and default values:
        This function includes shortcut variants with predefined argument:

        - `slope.intnorm`: sets `default_attrname="intnorm.eRi"` and `unit=None`
        - `slope.stdnorm`: sets `default_attrname="stdnorm.Ri"` and `unit=None`
        - `slope.abundance`: sets `default_attrname="abundance"` and `unit=None`

        Default argument values can also be updated through `slope.update_kwargs()`. Values defined in the function
        signature are used only if not overridden there. You can retrieve the default arguments using `slope.kwargs`.


    Returns:
        matplotlib.axes.Axes: The axes object used for plotting.
    """

    modeldata, axis_labels = slope_get_data(models, xkey, ykey,
                                                default_attrname=default_attrname, unit=unit,
                                                where=where, mask=mask, mask_na=mask_na,
                                                kwargs=kwargs)
    return slope_draw(modeldata, axis_labels, xycoord=xycoord,
                   arrow=arrow, arrow_position=arrow_position,
                   ax=ax,
                   legend=legend, update_ax=update_ax, update_fig=update_fig,
                   kwargs=kwargs)

update_axes

update_axes(ax, kwargs, *, update_ax=True, update_fig=True)

Updates the axes and figure objects.

Keywords beginning with ax_<name>, xax_<name>, yax_<name> and fig_<name> will be stripped from kwargs. These will then be used to call the set_<name> or <name> method of the axes, axis or figure object.

If the value mapped to the above arguments is: - A bool it is used to determine whether to call the method. The boolean itself will not be passed to the method. - A tuple then the contents of the tuple is unpacked and used as arguments for the method call. - A dict then the contents of the dictionary is unpacked and used as keyword arguments for the method call. - Any other type of value will be passed as the first argument to the method call. To pass one of the above types as a single argument use a tuple, e.g. (True, ).

Additional keyword arguments can be passed to methods by mapping e.g. <ax|xax|yax|fig>_kw_<name>_<keyword> kwargs to the value. These additional keyword arguments are only used if the <ax|xax|yax|fig>_<name> kwargs exists.

The figure will not be updated if ax is a subplot created by simple.create_subplots.

Source code in simple/plotting.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
def update_axes(ax, kwargs, *, update_ax = True, update_fig = True):
    """
    Updates the axes and figure objects.

    Keywords beginning with ``ax_<name>``, ``xax_<name>``, ``yax_<name>`` and ``fig_<name>`` will be stripped
    from kwargs. These will then be used to call the ``set_<name>`` or ``<name>`` method of the axes, axis or
    figure object.

    If the value mapped to the above arguments is:
    - A `bool` it is used to determine whether to call the method. The boolean itself will not be passed to
        the method.
    - A `tuple` then the contents of the tuple is unpacked and used as arguments for the method call.
    - A `dict` then the contents of the dictionary is unpacked and used as keyword arguments for the method call.
    - Any other type of value will be passed as the first argument to the method call. To pass one of the above types
     as a single argument use a tuple, e.g. `(True, )`.

    Additional keyword arguments can be passed to methods by mapping e.g. ``<ax|xax|yax|fig>_kw_<name>_<keyword>``
    kwargs to the value. These additional keyword arguments are only used if the
    ``<ax|xax|yax|fig>_<name>`` kwargs exists.

    The figure will not be updated if ``ax`` is a subplot created by [simple.create_subplots][simple.plotting.create_subplots].
    """

    ax = get_axes(ax)
    axes_meth = kwargs.pop_many(prefix='ax')
    axes_kw = axes_meth.pop_many(prefix='kw')

    xaxes_meth = kwargs.pop_many(prefix='xax')
    xaxes_kw = xaxes_meth.pop_many(prefix='kw')

    yaxes_meth = kwargs.pop_many(prefix='yax')
    yaxes_kw = yaxes_meth.pop_many(prefix='kw')

    if update_ax:
        _update_fig_or_ax(ax, 'ax', axes_meth, axes_kw)
        if xaxes_meth:
            _update_fig_or_ax(ax.xaxis, 'xax', xaxes_meth, xaxes_kw)
        if yaxes_meth:
            _update_fig_or_ax(ax.yaxis, 'yax', yaxes_meth, yaxes_kw)

    # Dont update figure if subplot was created using create subplots.
    # Figure stuff should be done there instead
    update_figure(ax.get_figure(), kwargs, update_fig = False if hasattr(ax, '_SIMPLE_subplot_dict') else update_fig)