Plot the swim speed during experimental indices

    Args
    ----
    exp_ind: ndarray
        Indices of tag data where experiment is active
    swim_speed: ndarray
        Swim speed data at sensor sampling rate
963568
def plot_swim_speed(exp_ind, swim_speed):
    '''
    '''
    import numpy

    fig, ax = plt.subplots()

    ax.title.set_text('Swim speed from depth change and pitch angle (m/s^2')
    ax.plot(exp_ind, swim_speed, linewidth=_linewidth, label='speed')
    ymax = numpy.ceil(swim_speed[~numpy.isnan(swim_speed)].max())
    ax.set_ylim(0, ymax)
    ax.legend(loc='upper right')

    plt.show()

    return ax
252374
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
    """"""
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print('matplotlib is not available.')
    else:
        if ax is None:
            _, ax = plt.subplots(1, 1, figsize=(8, 4))

        ax.plot(x, 'b', lw=1)
        if ind.size:
            label = 'valley' if valley else 'peak'
            label = label + 's' if ind.size > 1 else label
            ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
                    label='%d %s' % (ind.size, label))
            ax.legend(loc='best', framealpha=.5, numpoints=1)
        ax.set_xlim(-.02*x.size, x.size*1.02-1)
        ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
        yrange = ymax - ymin if ymax > ymin else 1
        ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
        ax.set_xlabel('Data #', fontsize=14)
        ax.set_ylabel('Amplitude', fontsize=14)
        mode = 'Valley detection' if valley else 'Peak detection'
        ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')"
                     % (mode, str(mph), mpd, str(threshold), edge))
239026
def construct_experiment_id(time_interval):
    
    # Construct id based on unix epoch timestamps
    epoch = udatetime.utcfromtimestamp(0).replace(tzinfo=UTC)
    start = int((time_interval.start - epoch).total_seconds() * 1000.0)
    end = int((time_interval.end - epoch).total_seconds() * 1000.0)
    return "{}-{}".format(start, end)
92697
def start_exp():
    
    if not (('hitId' in request.args) and ('assignmentId' in request.args) and
            ('workerId' in request.args) and ('mode' in request.args)):
        raise ExperimentError('hit_assign_worker_id_not_set_in_exp')
    hit_id = request.args['hitId']
    assignment_id = request.args['assignmentId']
    worker_id = request.args['workerId']
    mode = request.args['mode']
    app.logger.info("Accessing /exp: %(h)s %(a)s %(w)s " % {
        "h" : hit_id,
        "a": assignment_id,
        "w": worker_id
    })
    if hit_id[:5] == "debug":
        debug_mode = True
    else:
        debug_mode = False

    # Check first to see if this hitId or assignmentId exists.  If so, check to
    # see if inExp is set
    allow_repeats = CONFIG.getboolean('HIT Configuration', 'allow_repeats')
    if allow_repeats:
        matches = Participant.query.\
            filter(Participant.workerid == worker_id).\
            filter(Participant.assignmentid == assignment_id).\
            all()
    else:
        matches = Participant.query.\
            filter(Participant.workerid == worker_id).\
            all()

    numrecs = len(matches)
    if numrecs == 0:
        # Choose condition and counterbalance
        subj_cond, subj_counter = get_random_condcount(mode)

        worker_ip = "UNKNOWN" if not request.remote_addr else \
            request.remote_addr
        browser = "UNKNOWN" if not request.user_agent.browser else \
            request.user_agent.browser
        platform = "UNKNOWN" if not request.user_agent.platform else \
            request.user_agent.platform
        language = "UNKNOWN" if not request.user_agent.language else \
            request.user_agent.language

        # Set condition here and insert into database.
        participant_attributes = dict(
            assignmentid=assignment_id,
            workerid=worker_id,
            hitid=hit_id,
            cond=subj_cond,
            counterbalance=subj_counter,
            ipaddress=worker_ip,
            browser=browser,
            platform=platform,
            language=language,
            mode=mode
        )
        part = Participant(**participant_attributes)
        db_session.add(part)
        db_session.commit()

    else:
        # A couple possible problems here:
        # 1: They've already done an assignment, then we should tell them they
        #    can't do another one
        # 2: They've already worked on this assignment, and got too far to
        #    start over.
        # 3: They're in the database twice for the same assignment, that should
        #    never happen.
        # 4: They're returning and all is well.
        nrecords = 0
        for record in matches:
            other_assignment = False
            if record.assignmentid != assignment_id:
                other_assignment = True
            else:
                nrecords += 1
        if nrecords <= 1 and not other_assignment:
            part = matches[0]
            # In experiment (or later) can't restart at this point
            if part.status >= STARTED and not debug_mode:
                raise ExperimentError('already_started_exp')
        else:
            if nrecords > 1:
                app.logger.error("Error, hit/assignment appears in database \
                                 more than once (serious problem)")
                raise ExperimentError(
                    'hit_assign_appears_in_database_more_than_once'
                )
            if other_assignment:
                raise ExperimentError('already_did_exp_hit')

    use_psiturk_ad_server = CONFIG.getboolean('Shell Parameters', 'use_psiturk_ad_server')
    if use_psiturk_ad_server and (mode == 'sandbox' or mode == 'live'):
        # If everything goes ok here relatively safe to assume we can lookup
        # the ad.
        ad_id = get_ad_via_hitid(hit_id)
        if ad_id != "error":
            if mode == "sandbox":
                ad_server_location = 'https://sandbox.ad.psiturk.org/complete/'\
                    + str(ad_id)
            elif mode == "live":
                ad_server_location = 'https://ad.psiturk.org/complete/' +\
                str(ad_id)
        else:
            raise ExperimentError('hit_not_registered_with_ad_server')
    else:
        ad_server_location = '/complete'

    return render_template(
        'exp.html', uniqueId=part.uniqueid,
        condition=part.cond,
        counterbalance=part.counterbalance,
        adServerLoc=ad_server_location,
        mode = mode,
        contact_address=CONFIG.get('HIT Configuration', 'contact_email_on_error')
    )
965159
def parse_expvar_data(self, data, tags, metrics, max_metrics, namespace):
        '''
        
        '''
        count = 0
        for metric in metrics:
            path = metric.get(PATH)
            metric_type = metric.get(TYPE, DEFAULT_TYPE)
            metric_tags = list(metric.get(TAGS, []))
            metric_tags += tags
            alias = metric.get(ALIAS)

            if not path:
                self.warning("Metric %s has no path" % metric)
                continue

            if metric_type not in SUPPORTED_TYPES:
                self.warning("Metric type %s not supported for this check" % metric_type)
                continue

            keys = path.split("/")
            values = self.deep_get(data, keys)

            if len(values) == 0:
                self.warning("No results matching path %s" % path)
                continue

            tag_by_path = alias is not None

            for traversed_path, value in values:
                actual_path = ".".join(traversed_path)
                path_tag = ["path:%s" % actual_path] if tag_by_path else []

                metric_name = alias or self.normalize(actual_path, namespace, fix_case=True)

                try:
                    float(value)
                except ValueError:
                    self.log.warning("Unreportable value for path %s: %s" % (path, value))
                    continue

                if count >= max_metrics:
                    self.warning(
                        "Reporting more metrics than the allowed maximum. "
                        "Please contact support@datadoghq.com for more information."
                    )
                    return

                SUPPORTED_TYPES[metric_type](self, metric_name, value, metric_tags + path_tag)
                count += 1
618668
def show_experiment_info():
    ''''''
    experiment_config = Experiments()
    experiment_dict = experiment_config.get_all_experiments()
    if not experiment_dict:
        print('There is no experiment running...')
        exit(1)
    update_experiment()
    experiment_id_list = []
    for key in experiment_dict.keys():
        if experiment_dict[key]['status'] != 'STOPPED':
            experiment_id_list.append(key)
    if not experiment_id_list:
        print_warning('There is no experiment running...')
        return
    for key in experiment_id_list:
        print(EXPERIMENT_MONITOR_INFO % (key, experiment_dict[key]['status'], experiment_dict[key]['port'], \
             experiment_dict[key].get('platform'), experiment_dict[key]['startTime'], get_time_interval(experiment_dict[key]['startTime'], experiment_dict[key]['endTime'])))
        print(TRIAL_MONITOR_HEAD)
        running, response = check_rest_server_quick(experiment_dict[key]['port'])
        if running:
            response = rest_get(trial_jobs_url(experiment_dict[key]['port']), REST_TIME_OUT)
            if response and check_response(response):
                content = json.loads(response.text)
                for index, value in enumerate(content):
                    content[index] = convert_time_stamp_to_date(value)
                    print(TRIAL_MONITOR_CONTENT % (content[index].get('id'), content[index].get('startTime'), content[index].get('endTime'), content[index].get('status')))
        print(TRIAL_MONITOR_TAIL)
381853
def print_experiments(experiments):
    
    headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
    expt_list = []
    for experiment in experiments:
        expt_list.append([normalize_job_name(experiment.name),
                          experiment.created_pretty, experiment.state,
                          experiment.duration_rounded, experiment.instance_type_trimmed,
                          experiment.description, format_metrics(experiment.latest_metrics)])
    floyd_logger.info(tabulate(expt_list, headers=headers))
611462
def Exp(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
    
    return Double(context.jvm_view().ExpVertex, label, cast_to_double_vertex(input_vertex))
195856
def exp_transform(params):
    """"""
    weights = np.exp(np.asarray(params) - np.mean(params))
    return (len(weights) / weights.sum()) * weights
37739
def ior_effect(durations, angle_diffs, length_diffs,
               summary_stat=np.mean, parallel=True, min_samples=20):
    
    raster = np.empty((len(e_dist) - 1, len(e_angle) - 1), dtype=object)
    for a, (a_low, a_upp) in enumerate(zip(e_angle[:-1], e_angle[1:])):
        for d, (d_low, d_upp) in enumerate(zip(e_dist[:-1], e_dist[1:])):
            idx = ((d_low <= length_diffs) & (length_diffs < d_upp) &
                   (a_low <= angle_diffs) & (angle_diffs < a_upp))
            if sum(idx) < min_samples:
                raster[d, a] = np.array([np.nan])
            else:
                raster[d, a] = durations[idx]
    if parallel:
        p = pool.Pool(3)
        result = p.map(summary_stat, list(raster.flatten()))
        p.terminate()
    else:
        result = list(map(summary_stat, list(raster.flatten())))
    for idx, value in enumerate(result):
        i, j = np.unravel_index(idx, raster.shape)
        raster[i, j] = value
    return raster
245986
def _exec_loop(self, a, bd_all, xyz, mask, n_withdrifts, spec_drift_grids):
        """"""

        npt = bd_all.shape[0]
        n = self.X_ADJUSTED.shape[0]
        kvalues = np.zeros(npt)
        sigmasq = np.zeros(npt)

        a_inv = scipy.linalg.inv(a)

        for j in np.nonzero(~mask)[0]:   # Note that this is the same thing as range(npt) if mask is not defined,
            bd = bd_all[j]               # otherwise it takes the non-masked elements.
            if np.any(np.absolute(bd) <= self.eps):
                zero_value = True
                zero_index = np.where(np.absolute(bd) <= self.eps)
            else:
                zero_value = False
                zero_index = None

            if self.UNBIAS:
                b = np.zeros((n_withdrifts+1, 1))
            else:
                b = np.zeros((n_withdrifts, 1))
            b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)
            if zero_value:
                b[zero_index[0], 0] = 0.0

            i = n
            if self.regional_linear_drift:
                b[i, 0] = xyz[j, 2]
                i += 1
                b[i, 0] = xyz[j, 1]
                i += 1
                b[i, 0] = xyz[j, 0]
                i += 1
            if self.specified_drift:
                for spec_vals in spec_drift_grids:
                    b[i, 0] = spec_vals.flatten()[i]
                    i += 1
            if self.functional_drift:
                for func in self.functional_drift_terms:
                    b[i, 0] = func(xyz[j, 2], xyz[j, 1], xyz[j, 0])
                    i += 1
            if i != n_withdrifts:
                warnings.warn("Error in setting up kriging system. "
                              "Kriging may fail.", RuntimeWarning)
            if self.UNBIAS:
                b[n_withdrifts, 0] = 1.0

            x = np.dot(a_inv, b)
            kvalues[j] = np.sum(x[:n, 0] * self.VALUES)
            sigmasq[j] = np.sum(x[:, 0] * -b[:, 0])

        return kvalues, sigmasq
1334262
def log_sum_exp(self,x, axis):
        ''''''
        x_max = np.max(x, axis=axis)
        if axis == 1:
            return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) )
        else:
            return x_max + np.log( np.sum(np.exp(x-x_max), axis=0) )
595917
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx):
        
        import scipy.linalg.lapack

        npt = bd_all.shape[0]
        n = bd_idx.shape[1]
        kvalues = np.zeros(npt)
        sigmasq = np.zeros(npt)

        for i in np.nonzero(~mask)[0]:
            b_selector = bd_idx[i]
            bd = bd_all[i]

            a_selector = np.concatenate((b_selector, np.array([a_all.shape[0] - 1])))
            a = a_all[a_selector[:, None], a_selector]

            if np.any(np.absolute(bd) <= self.eps):
                zero_value = True
                zero_index = np.where(np.absolute(bd) <= self.eps)
            else:
                zero_value = False
                zero_index = None
            b = np.zeros((n+1, 1))
            b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)
            if zero_value:
                b[zero_index[0], 0] = 0.0
            b[n, 0] = 1.0

            x = scipy.linalg.solve(a, b)

            kvalues[i] = x[:n, 0].dot(self.VALUES[b_selector])
            sigmasq[i] = - x[:, 0].dot(b[:, 0])

        return kvalues, sigmasq
594091
def calc_wtd_exp(skydir, ltc, event_class, event_types,
                 egy_bins, cth_bins, fn, nbin=16):
    
    cnts = calc_counts_edisp(skydir, ltc, event_class, event_types,
                             egy_bins, cth_bins, fn, nbin=nbin)
    flux = fn.flux(egy_bins[:-1], egy_bins[1:])
    return cnts / flux[:, None]
1194682
def getThroughput(self, instId: int) -> float:
        
        # We are using the instanceStarted time in the denominator instead of
        # a time interval. This is alright for now as all the instances on a
        # node are started at almost the same time.
        if instId not in self.instances.ids:
            return None
        perf_time = time.perf_counter()
        throughput = self.throughputs[instId].get_throughput(perf_time)
        return throughput
92852
def exp(cls, x: 'TensorFluent') -> 'TensorFluent':
        '''
        '''
        return cls._unary_op(x, tf.exp, tf.float32)
254626
def filter_butter_plot_freqresponse(b, a, samplerate, numpoints=2000):
    # type: (Seq[float], Seq[float], int, int) -> None
    
    import matplotlib.pyplot as plt
    plt.figure(1)
    plt.clf()
    w, h = signal.freqz(b, a, worN=numpoints)
    plt.semilogx((samplerate*0.5/np.pi) * w, np.abs(h))
    plt.xlabel('Freq (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.show()