Ejemplo n.º 1
0
def _get_param_estimates_1d(x, z: np.array) -> lm.Parameters:
    """Returns lm.Parameters for x, z data"""
    assert z.ndim == 1
    z, x = CU.resample_data(z, x, max_num_pnts=500)
    params = lm.Parameters()
    s = pd.Series(
        z)  # Put into Pandas series so I can work with NaN's more easily
    sx = pd.Series(x, index=s.index)
    z = s[s.first_valid_index():s.last_valid_index() + 1]  # type: pd.Series
    x = sx[s.first_valid_index():s.last_valid_index() + 1]
    if np.count_nonzero(~np.isnan(
            z)) > 10:  # Prevent trying to work on rows with not enough data
        try:
            smooth_gradient = np.gradient(
                savgol_filter(x=z,
                              window_length=int(len(z) / 20) * 2 + 1,
                              polyorder=2,
                              mode='interp'))  # window has to be odd
        except np.linalg.linalg.LinAlgError:  # Came across this error on 9/9/20 -- Weirdly works second time...
            logger.warning('LinAlgError encountered, retrying')
            smooth_gradient = np.gradient(
                savgol_filter(x=z,
                              window_length=int(len(z) / 20) * 2 + 1,
                              polyorder=2,
                              mode='interp'))  # window has to be odd
        x0i = np.nanargmin(
            smooth_gradient)  # Index of steepest descent in data
        mid = x.iloc[x0i]  # X value of guessed middle index
        amp = np.nanmax(z) - np.nanmin(
            z)  # If needed, I should look at max/min near middle only
        lin = (z[z.last_valid_index()] - z[z.first_valid_index()] +
               amp) / (x[z.last_valid_index()] - x[z.first_valid_index()])
        theta = 5
        const = z.mean()
        G = 0
        # add with tuples: (NAME    VALUE   VARY  MIN   MAX     EXPR  BRUTE_STEP)
        params.add_many(('mid', mid, True, None, None, None, None),
                        ('theta', theta, True, 0.01, None, None, None),
                        ('amp', amp, True, 0, None, None, None),
                        ('lin', lin, True, 0, None, None, None),
                        ('const', const, True, None, None, None, None))
    return params