Skip to content

Utility functions

profile_plot

profile_plot(amplitude, displacement, elevation, r2, angles, scores, label, ax=None, reorder_scales=True, incl_pred=True, incl_fit=True, incl_disp=True, incl_amp=True, c_scores='red', c_fit='black')

Plot the SSM profile.

PARAMETER DESCRIPTION
reorder_scales

DEFAULT: True

incl_pred

DEFAULT: True

incl_fit

DEFAULT: True

incl_disp

DEFAULT: True

incl_amp

DEFAULT: True

RETURNS DESCRIPTION
Axes

plt.Axes: A tuple containing the figure and axis objects.

Source code in circumplex/circumplex.py
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
def profile_plot(
    amplitude,
    displacement,
    elevation,
    r2,
    angles,
    scores,
    label,
    ax=None,
    reorder_scales=True,
    incl_pred=True,
    incl_fit=True,
    incl_disp=True,
    incl_amp=True,
    c_scores='red',
    c_fit='black',
) -> plt.Axes:
    """
    Plot the SSM profile.

    Args:
        reorder_scales:
        incl_pred:
        incl_fit:
        incl_disp:
        incl_amp:

    Returns:
        plt.Axes: A tuple containing the figure and axis objects.
    """

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 4))
    else:
        fig = ax.get_figure()

    if reorder_scales:
        angles, scores = sort_angles(angles, scores)
        if angles[-1] == 360:
            angles = (0,) + angles
            scores = (scores[-1],) + scores

    if incl_pred:
        thetas = np.linspace(0, 360, 1000)
        fit = cosine_form(thetas, amplitude, displacement, elevation)
        ax.plot(thetas, fit, color=c_fit)

    ax.plot(angles, scores, color=c_scores, marker="o")
    # ax.scatter(self.angles, self.scores, marker="o", color="black")
    if incl_disp:
        ax.axvline(displacement, color="black", linestyle="--")
        ax.text(
            displacement + 5,
            elevation,
            f"d = {int(displacement)}",
        )
    if incl_amp:
        ax.axhline(amplitude + elevation, color="black", linestyle="--")
        ax.text(0, amplitude + elevation * 0.9, f"a = {amplitude:.2f}")

    if incl_fit:
        ax.text(0, elevation * 0.5, f"R2 = {r2:.2f}")

    ax.set_xticks(OCTANTS)
    ax.set_xticklabels(
        ["0", "45", "90", "135", "180", "225", "270", "315"], fontsize=14
    )
    ax.set_xlabel("Angle [deg]", fontsize=16)
    ax.set_ylabel("Score", fontsize=16)
    ax.set_title(f"{label} Profile", fontsize=20)
    return fig, ax

ssm_analyse

ssm_analyse(data, scales, measures=None, grouping=None, angles=OCTANTS, grouped_angles=None)

Analyse a set of data using the SSM method.

PARAMETER DESCRIPTION
data

A dataframe containing the data to be analysed.

TYPE: DataFrame

scales

A list of the names of the circumplex scales to be included in the analysis.

TYPE: list

measures

A list of the names of the measures to be included in the analysis. Defaults to None.

TYPE: list DEFAULT: None

grouping

A list of the names of the groups to be included in the analysis. Defaults to None.

TYPE: list DEFAULT: None

angles

A tuple containing the angular displacement of each circumplex scale included in scores. Defaults to OCTANTS.

TYPE: tuple DEFAULT: OCTANTS

grouped_angles

A dictionary containing the angular displacement of each circumplex scale included in scores for each group. Defaults to None.

TYPE: dict DEFAULT: None

RETURNS DESCRIPTION
SSMResults

A SSMResults object containing the results of the analysis.

TYPE: SSMResults

Source code in circumplex/circumplex.py
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
def ssm_analyse(
    data: pd.DataFrame,
    scales: list,
    measures: list | None = None,
    grouping: list | None = None,
    angles: tuple = OCTANTS,
    grouped_angles: dict = None,
) -> SSMResults:
    """
    Analyse a set of data using the SSM method.

    Args:
        data (pd.DataFrame): A dataframe containing the data to be analysed.
        scales (list): A list of the names of the circumplex scales to be included in the analysis.
        measures (list, optional): A list of the names of the measures to be included in the analysis. Defaults to None.
        grouping (list, optional): A list of the names of the groups to be included in the analysis. Defaults to None.
        angles (tuple, optional): A tuple containing the angular displacement of each circumplex scale
            included in `scores`. Defaults to OCTANTS.
        grouped_angles (dict, optional): A dictionary containing the angular displacement of each circumplex scale
            included in `scores` for each group. Defaults to None.

    Returns:
        SSMResults: A SSMResults object containing the results of the analysis.

    """
    if grouping is not None and measures is not None:
        return ssm_analyse_grouped_corrs(
            data, scales, measures, grouping, angles, grouped_angles
        )
    elif measures is not None:
        return ssm_analyse_corrs(data, scales, measures, angles)
    elif grouping is not None:
        return ssm_analyse_means(data, scales, grouping, angles, grouped_angles)
    else:
        ssm = SSMParams(data[scales].mean(), scales, angles)
        # ssm.param_calc()
        return SSMResults(ssm)

ssm_analyse_corrs

ssm_analyse_corrs(data, scales, measures, angles=OCTANTS, group=None)

Perform SSM analysis of correlations for a set of data.

PARAMETER DESCRIPTION
data

A dataframe containing the data to be analysed.

TYPE: DataFrame

scales

A list of the names of the circumplex scales to be included in the analysis.

TYPE: tuple

measures

A list of the names of the measures to be included in the analysis.

TYPE: list

angles

A tuple containing the angular displacement of each circumplex scale included in scores. Defaults to OCTANTS.

TYPE: tuple DEFAULT: OCTANTS

group

The name of the group to be included in the analysis. Defaults to None.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
SSMResults

A SSMResults object containing the results of the analysis.

TYPE: SSMResults

Source code in circumplex/circumplex.py
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
def ssm_analyse_corrs(
    data: pd.DataFrame,
    scales: tuple,
    measures: list,
    angles: tuple = OCTANTS,
    group: str | None = None,
) -> SSMResults:
    """
    Perform SSM analysis of correlations for a set of data.

    Args:
        data (pd.DataFrame): A dataframe containing the data to be analysed.
        scales (tuple): A list of the names of the circumplex scales to be included in the analysis.
        measures (list): A list of the names of the measures to be included in the analysis.
        angles (tuple, optional): A tuple containing the angular displacement of each circumplex scale
            included in `scores`. Defaults to OCTANTS.
        group (str, optional): The name of the group to be included in the analysis. Defaults to None.

    Returns:
        SSMResults: A SSMResults object containing the results of the analysis.
    """
    res = []
    for measure in measures:
        r = data[scales].corrwith(data[measure])
        ssm = SSMParams(r, scales, angles, measure=measure, group=group)
        # ssm.param_calc()
        res.append(ssm)

    return SSMResults(res, measures)

ssm_analyse_grouped_corrs

ssm_analyse_grouped_corrs(data, scales, measures, grouping, angles=OCTANTS, grouped_angles=None)

Perform SSM analysis of correlations for a set of grouped data.

PARAMETER DESCRIPTION
data

A dataframe containing the data to be analysed.

TYPE: DataFrame

scales

A list of the names of the circumplex scales to be included in the analysis.

TYPE: tuple

measures

A list of the names of the measures to be included in the analysis.

TYPE: list

grouping

A list of the names of the groups to be included in the analysis.

TYPE: list

angles

A tuple containing the angular displacement of each circumplex scale included in scores. Defaults to OCTANTS.

TYPE: tuple DEFAULT: OCTANTS

RETURNS DESCRIPTION
SSMResults

A SSMResults object containing the results of the analysis.

TYPE: SSMResults

Source code in circumplex/circumplex.py
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
def ssm_analyse_grouped_corrs(
    data: pd.DataFrame,
    scales: tuple,
    measures: list,
    grouping: list,
    angles: tuple = OCTANTS,
    grouped_angles: dict = None,
) -> SSMResults:
    """
    Perform SSM analysis of correlations for a set of grouped data.

    Args:
        data (pd.DataFrame): A dataframe containing the data to be analysed.
        scales (tuple): A list of the names of the circumplex scales to be included in the analysis.
        measures (list): A list of the names of the measures to be included in the analysis.
        grouping (list): A list of the names of the groups to be included in the analysis.
        angles (tuple, optional): A tuple containing the angular displacement of each circumplex scale
            included in `scores`. Defaults to OCTANTS.

    Returns:
            SSMResults: A SSMResults object containing the results of the analysis.
    """
    res = []
    for group_var in grouping:
        for group, group_data in data.groupby(group_var):
            if grouped_angles is not None:
                angles = grouped_angles[group]  # grouped angles will override angles
            try:
                res.append(
                    ssm_analyse_corrs(
                        group_data, scales, measures, angles, group=group
                    ).results[0]
                )
            except ValueError as e:
                print(f"Error: {e} | in {group_var} = {group}")

    return SSMResults(res, measures, grouping)

ssm_analyse_means

ssm_analyse_means(data, scales, grouping, angles=OCTANTS, grouped_angles=None)

Perform SSM analysis of means for a set of data.

PARAMETER DESCRIPTION
data

A dataframe containing the data to be analysed.

TYPE: DataFrame

scales

A list of the names of the circumplex scales to be included in the analysis.

TYPE: tuple

grouping

A list of the names of the groups to be included in the analysis.

TYPE: list

angles

A tuple containing the angular displacement of each circumplex scale included in scores. Defaults to OCTANTS.

TYPE: tuple DEFAULT: OCTANTS

RETURNS DESCRIPTION
SSMResults

A SSMResults object containing the results of the analysis.

TYPE: SSMResults

Source code in circumplex/circumplex.py
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
def ssm_analyse_means(
    data: pd.DataFrame,
    scales: tuple,
    grouping: list,
    angles: tuple = OCTANTS,
    grouped_angles: dict = None,
) -> SSMResults:
    """
    Perform SSM analysis of means for a set of data.

    Args:
        data (pd.DataFrame): A dataframe containing the data to be analysed.
        scales (tuple): A list of the names of the circumplex scales to be included in the analysis.
        grouping (list): A list of the names of the groups to be included in the analysis.
        angles (tuple, optional): A tuple containing the angular displacement of each circumplex scale
            included in `scores`. Defaults to OCTANTS.

    Returns:
        SSMResults: A SSMResults object containing the results of the analysis.
    """
    means = data.groupby(grouping)[scales].mean()
    res = []
    for group, scores in means.iterrows():
        if grouped_angles is not None:
            angles = grouped_angles[group]
        scores = means.loc[group]
        ssm = SSMParams(scores, scales, angles, group=group)
        # ssm.param_calc()
        res.append(ssm)

    return SSMResults(res, grouping=grouping)

ssm_parameters

ssm_parameters(scores, angles, bounds=BOUNDS)

Calculate SSM parameters (without confidence intervals) for a set of scores.

PARAMETER DESCRIPTION
scores

A numeric vector (or single row dataframe) containing one score for each of a set of circumplex scales.

TYPE: array

angles

A numeric vector containing the angular displacement of each circumplex scale included in scores.

TYPE: tuple

bounds

The bounds for each of the parameters of the curve optimisation. Defaults to ([0, 0, -1], [np.inf, 360, 1]).

TYPE: tuple DEFAULT: BOUNDS

RETURNS DESCRIPTION
tuple

A tuple containing the elevation, x-value, y-value, amplitude, displacement, and R2 fit of the SSM curve.

TYPE: tuple

Examples:

>>> scores = np.array([-0.5, 0, 0.25, 0.51, 0.52, 0.05, -0.26, -0.7])
>>> angles = OCTANTS
>>> results = ssm_parameters(scores, angles)
>>> [round(i, 3) for i in results]
[-0.016, -0.478, 0.333, 0.582, 145.158, 0.967]
Source code in circumplex/circumplex.py
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
def ssm_parameters(scores, angles, bounds=BOUNDS) -> tuple:
    """Calculate SSM parameters (without confidence intervals) for a set of scores.

    Args:
        scores (np.array): A numeric vector (or single row dataframe) containing one score for each of a
            set of circumplex scales.
        angles (tuple): A numeric vector containing the angular displacement of each circumplex scale
            included in `scores`.
        bounds (tuple, optional): The bounds for each of the parameters of the curve optimisation.
            Defaults to ([0, 0, -1], [np.inf, 360, 1]).

    Returns:
        tuple: A tuple containing the elevation, x-value, y-value, amplitude, displacement, and R2 fit of the SSM curve.

    Examples:
        >>> scores = np.array([-0.5, 0, 0.25, 0.51, 0.52, 0.05, -0.26, -0.7])
        >>> angles = OCTANTS
        >>> results = ssm_parameters(scores, angles)
        >>> [round(i, 3) for i in results]
        [-0.016, -0.478, 0.333, 0.582, 145.158, 0.967]
    """

    # noinspection PyTupleAssignmentBalance
    # NOTE: Bug - Sometimes returns displacement at the trough, not the crest, so 180 degrees off
    # This was addressed by setting the lower bound of amplitude to 0, not -np.inf. Need a less hard-coded solution
    param, covariance = curve_fit(
        cosine_form, xdata=angles, ydata=scores, bounds=bounds
    )
    r2 = _r2_score(scores, cosine_form(angles, *param))
    ampl, disp, elev = param

    def polar2cart(r, theta):
        x = r * np.cos(theta)
        y = r * np.sin(theta)
        return x, y

    xval, yval = polar2cart(ampl, np.deg2rad(disp))
    return elev, xval, yval, ampl, disp, r2