Skip to content

remeta.model.ReMeta

ReMeta

Usage
rem = remeta.ReMeta()

for a default model, or otherwise:

cfg = remeta.Configuration()
cfg.<some_setting> = <some_value>
rem = remeta.ReMeta(cfg)

Parameters:

Name Type Description Default
cfg Configuration

Configuration object. If None is passed, the default configuration (but see kwargs).

None
**kwargs

kwargs entries are passed to the Configuration

{}
Source code in remeta/model.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(
    self,
    cfg: Configuration = None,
    **kwargs
):
    """

    Usage:
        ```
        rem = remeta.ReMeta()
        ```

        for a default model, or otherwise:

        ```
        cfg = remeta.Configuration()
        cfg.<some_setting> = <some_value>
        rem = remeta.ReMeta(cfg)
        ```

    Args:
        cfg: Configuration object. If None is passed, the default configuration (but see kwargs).
        **kwargs: kwargs entries are passed to the Configuration

    """

    if cfg is None:
        # Set configuration attributes that match keyword arguments
        cfg_kwargs = {k: v for k, v in kwargs.items() if k in Configuration.__dict__}
        self.cfg = Configuration(**cfg_kwargs)
    else:
        self.cfg = cfg
        for k, v in kwargs.items():
            if k in Configuration.__dict__:
                setattr(self.cfg, k, v)
    self.cfg.setup()

    self.modeldata = ModelData(cfg=self.cfg)
    self.data = None
    self.result = None

    self.type1_is_fitted = False
    self.type2_is_fitted = False

.fit()

Usage
rem = ReMeta()
rem.fit(stimuli, choices, confidence)

Parameters:

Name Type Description Default
stimuli list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of signed stimulus intensities

required
choices list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of choices (coded as -1/1 or 0/1)

required
confidence list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of confidence ratings (normalized to the range 0-1)

None
verbosity int

verbosity level (possible values: 0, 1, 2)

1
silence_warnings bool

if True, warnings during model fitting are supressed.

False
Source code in remeta/model.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def fit(
    self,
    stimuli: list[float] | list[list[float]]  | np.typing.NDArray[float],
    choices: list[float] | list[list[float]]  | np.typing.NDArray[float],
    confidence: list[float] | list[list[float]]  | np.typing.NDArray[float] = None,
    verbosity: int = 1,
    silence_warnings: bool = False
):
    """

    Usage:
        ```
        rem = ReMeta()
        rem.fit(stimuli, choices, confidence)
        ```

    Args:
        stimuli: 1d or 2d array or list of signed stimulus intensities
        choices: 1d or 2d array or list of choices (coded as -1/1 or 0/1)
        confidence: 1d or 2d array or list of confidence ratings (normalized to the range 0-1)
        verbosity: verbosity level (possible values: 0, 1, 2)
        silence_warnings: if `True`, warnings during model fitting are supressed.
    """

    self.data = Data(self.cfg, stimuli, choices, confidence)

    self.result = Summary(self.data, self.cfg)

    self.fit_type1(verbosity=verbosity, store_final_results=self.cfg.skip_type2, silence_warnings=silence_warnings)

    if not self.cfg.skip_type2:
        self.fit_type2(verbosity=verbosity, silence_warnings=silence_warnings)

.fit_type1()

Usage
rem = ReMeta()
rem.fit_type1(stimuli, choices)

Parameters:

Name Type Description Default
stimuli None | list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of signed stimulus intensities

None
choices None | list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of choices (coded as -1/1 or 0/1)

None
confidence None | list[float] | list[list[float]] | NDArray[float]

1d or 2d array or list of confidence ratings (normalized to the range 0-1)

None
store_final_results bool

if True, save final results. Mostly used internally - will be set to False, if followed by fit_type2.

True
verbosity int

verbosity level (possible values: 0, 1, 2)

1
silence_warnings bool

if True, warnings during model fitting are supressed.

False
Source code in remeta/model.py
108
109
110
111
112
113
114
115
116
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
def fit_type1(
    self,
    stimuli: None | list[float] | list[list[float]]  | np.typing.NDArray[float] = None,
    choices: None | list[float] | list[list[float]]  | np.typing.NDArray[float] = None,
    confidence: None | list[float] | list[list[float]]  | np.typing.NDArray[float] = None,
    store_final_results: bool = True,
    verbosity: int = 1,
    silence_warnings: bool = False
):
    """

    Usage:
        ```
        rem = ReMeta()
        rem.fit_type1(stimuli, choices)
        ```

    Args:
        stimuli: 1d or 2d array or list of signed stimulus intensities
        choices: 1d or 2d array or list of choices (coded as -1/1 or 0/1)
        confidence: 1d or 2d array or list of confidence ratings (normalized to the range 0-1)
        store_final_results: if `True`, save final results. Mostly used internally - will be set to `False`,
            if followed by `fit_type2`.
        verbosity: verbosity level (possible values: 0, 1, 2)
        silence_warnings: if `True`, warnings during model fitting are supressed.
    """

    if self.data is None:
        if stimuli is None or choices is None:
            raise ValueError('If the data attribute of the ReMeta instance is None, at least stimuli '
                             'and choices have to be passed to fits_type1_subject()')
        else:
            self.data = Data(self.cfg, stimuli, choices, confidence)

    if verbosity >= 1:
        print(f'Dataset characteristics:')
        print(f'{TAB}No. subjects: {self.data.nsubjects}')
        print(f"{TAB}No. samples: {np.array2string(np.array(self.data.nsamples).squeeze(), separator=', ', threshold=3)}")
        print(f'{TAB}Accuracy: {100*self.data.stats.accuracy:.1f}% correct')
        print(f"{TAB}d': {self.data.stats.dprime:.3f}")
        print(f"{TAB}Choice bias: {100*self.data.stats.choice_bias:.1f}%")
        if not self.cfg.skip_type2 and not store_final_results:
            print(f"{TAB}Mean confidence: {self.data.stats.mean_confidence:.3f} "
                  f"(min: {np.min(self.data.c_conf):.3f}, max: {np.max(self.data.c_conf):.3f})")

    self.result = Summary(self.data, self.cfg)

    if verbosity:
        print('\n+++ Type 1 level +++')
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=UserWarning, module='scipy.optimize',
                                message='delta_grad == 0.0. Check if the approximated function is linear. If the '
                                        'function is linear better results can be obtained by defining the Hessian '
                                        'as zero instead of using quasi-Newton approximations.')

        fits_type1_subject, fit_type1_group = None, None
        if self.cfg._paramset_type1.nparams > 0:

            if verbosity:
                print(f'{SP2}Subject-level estimation (MLE)')
                tind = timeit.default_timer()

            # Single-subject fits via MLE
            use_multiproc_for_subject_loop = (self.cfg._optim_num_cores >= 8) and (self.data.nsubjects >= 8)
            def subject_loop(s):
                return subject_estimation(
                    self.compute_type1_negll, self.cfg._paramset_type1, args=[s],
                    gridsearch=self.cfg.optim_type1_gridsearch,
                    scipy_solvers=self.cfg.optim_type1_scipy_solvers,
                    num_cores=1 if use_multiproc_for_subject_loop else self.cfg._optim_num_cores,
                    minimize_along_grid=self.cfg.optim_type1_minimize_along_grid,
                    global_minimization=self.cfg.optim_type1_global_minimization,
                    # fine_gridsearch=self.cfg.optim_type1_fine_gridsearch,
                    verbosity=verbosity
                )
            if use_multiproc_for_subject_loop:
                with DillPool(self.cfg._optim_num_cores) as pool:
                    fits_type1_subject = pool.map(subject_loop, range(self.data.nsubjects))
            else:
                fits_type1_subject = [None for _ in range(self.data.nsubjects)]
                for s in range(self.data.nsubjects):
                    if (verbosity > 0) and (self.data.nsubjects > 1):
                        print(f'{TAB} Subject {s + 1} / {self.data.nsubjects}')
                    fits_type1_subject[s] = subject_loop(s)
            # Store single-subject results
            params_subject = [fits_type1_subject[s].x for s in range(self.data.nsubjects)]
            params_hessian_subject = [fits_type1_subject[s].hessian for s in range(self.data.nsubjects)]
            self.result.type1.subject.store(
                'type1', self.cfg, self.data, self.compute_type1_negll, params_subject,
                hessian=params_hessian_subject, fit=fits_type1_subject,
                execution_time=np.sum([fits_type1_subject[s].execution_time for s in range(self.data.nsubjects)])
            )

            if verbosity:
                print(f'{TAB}.. finished ({timeit.default_timer() - tind:.1f} secs).')

            if self.data.nsubjects > 1:
                idx_fe = np.array([i for i, p in enumerate(self.cfg._paramset_type1.parameters_flat.values()) if p.group == 'fixed'])
                idx_re = np.array([i for i, p in enumerate(self.cfg._paramset_type1.parameters_flat.values()) if p.group == 'random'])
                if (len(idx_fe) > 0) or (len(idx_re) > 0):

                    fit_type1_group = group_estimation(
                        fun=self.compute_type1_negll,
                        nsubjects=self.data.nsubjects,
                        params_init=params_subject,
                        bounds=self.cfg._paramset_type1.bounds,
                        idx_fe=idx_fe,
                        idx_re=idx_re,
                        num_cores=self.cfg._optim_num_cores,
                        max_iter=30, sigma_floor=1e-3,
                        verbosity=verbosity,
                        # tau=0.05
                    )

                    self.result.type1.init_group()
                    self.result.type1.group.store(
                        'type1', self.cfg, self.data, self.compute_type1_negll,
                        params=[fit_type1_group.x[s] for s in range(self.data.nsubjects)],
                        params_se=[fit_type1_group.x_se[s] for s in range(self.data.nsubjects)],
                        params_cov=[fit_type1_group.x_cov[s] for s in range(self.data.nsubjects)],
                        pop_mean_sd=fit_type1_group.x_re_pop_mean_sd,
                        execution_time=fit_type1_group.execution_time
                    )

        self.result.type1.store(cfg=self.cfg, data=self.data, fun=self.compute_type1_negll)
        if verbosity:
            self.result.type1.report_fit(self.cfg)
        self.type1_is_fitted = True

    if store_final_results:
        self.result.store(store_type1_only=True)

    if verbosity:
        print('Type 1 level finished')

.plot_psychometric()

Invoke remeta.plotting.plot_psychomtric on the ReMeta instance.

Usage
rem = ReMeta()
rem.fit(stimuli, choices, confidence)
rem.plot_psychometric()

Parameters:

Name Type Description Default
sub_ind int

subject index (only applicable if group data were fitted)

0
model_prediction bool

if True, plot model predictions

True
**kwargs

Pass parameters to remeta.plotting.plot_psychomtric

{}
Source code in remeta/model.py
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
def plot_psychometric(
    self,
    sub_ind: int = 0,
    model_prediction: bool = True,
    **kwargs
):
    """
    Invoke `remeta.plotting.plot_psychomtric` on the `ReMeta` instance.

    Usage:
        ```
        rem = ReMeta()
        rem.fit(stimuli, choices, confidence)
        rem.plot_psychometric()
        ```

    Args:
        sub_ind: subject index (only applicable if group data were fitted)
        model_prediction: if `True`, plot model predictions
        **kwargs: Pass parameters to `remeta.plotting.plot_psychomtric`
    """

    # self._check_fit()
    plot_psychometric(
        self.data.x_stim[sub_ind], self.data.d_dec[sub_ind],
        params=self.result.params[sub_ind] if model_prediction else None,
        cfg=self.cfg, **kwargs
    )

.plot_stimulus_versus_confidence()

Invoke remeta.plotting.plot_stimulus_versus_confidence on the ReMeta instance.

Usage
rem = ReMeta()
rem.fit(stimuli, choices, confidence)
rem.plot_stimulus_versus_confidence()

Parameters:

Name Type Description Default
sub_ind int

subject index (only applicable if group data were fitted)

0
model_prediction bool

if True, plot model predictions

True
**kwargs

Pass parameters to remeta.plotting.plot_stimulus_versus_confidence

{}
Source code in remeta/model.py
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
914
915
def plot_stimulus_versus_confidence(
    self,
    sub_ind: int = 0,
    model_prediction: bool = True,
    **kwargs
):
    """
    Invoke `remeta.plotting.plot_stimulus_versus_confidence` on the `ReMeta` instance.

    Usage:
        ```
        rem = ReMeta()
        rem.fit(stimuli, choices, confidence)
        rem.plot_stimulus_versus_confidence()
        ```

    Args:
        sub_ind: subject index (only applicable if group data were fitted)
        model_prediction: if `True`, plot model predictions
        **kwargs: Pass parameters to `remeta.plotting.plot_stimulus_versus_confidence`
    """
    # self._check_fit()
    plot_stimulus_versus_confidence(
        self.data.x_stim[sub_ind], self.data.c_conf[sub_ind],self.data.d_dec[sub_ind],
        params=self.result.params[sub_ind] if model_prediction else None,
        model_prediction=model_prediction,
        cfg=self.cfg, **kwargs
    )

.plot_confidence_histogram()

Invoke remeta.plotting.plot_confidence_histogram on the ReMeta instance.

Usage
rem = ReMeta()
rem.fit(stimuli, choices, confidence)
rem.plot_confidence_histogram()

Parameters:

Name Type Description Default
sub_ind int

subject index (only applicable if group data were fitted)

0
model_prediction bool

if True, plot model predictions

True
**kwargs

Pass parameters to remeta.plotting.plot_confidence_histogram

{}
Source code in remeta/model.py
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
def plot_confidence_histogram(
    self,
    sub_ind: int = 0,
    model_prediction: bool = True,
    **kwargs
):
    """
    Invoke `remeta.plotting.plot_confidence_histogram` on the `ReMeta` instance.

    Usage:
        ```
        rem = ReMeta()
        rem.fit(stimuli, choices, confidence)
        rem.plot_confidence_histogram()
        ```

    Args:
        sub_ind: subject index (only applicable if group data were fitted)
        model_prediction: if `True`, plot model predictions
        **kwargs: Pass parameters to `remeta.plotting.plot_confidence_histogram`
    """
    # self._check_fit()
    plot_confidence_histogram(
        self.data.c_conf[sub_ind], self.data.x_stim[sub_ind], self.data.d_dec[sub_ind],
        params=self.result.params[sub_ind] if model_prediction else None,
        cfg=self.cfg, **kwargs
    )