text:
import weakref
import numpy as np

from .util import logger

kinds = ["string", "int", "float", "bool"]

class Parameter(object):
    """ Processor parameter object. """

    def __init__(self, name, value, kind, processor=None, units="", minimum=None, maximum=None,
                options=[], print_precision=1, randomize_value=True, **kwargs):

        self.kind  = kind
        self.name  = name
        self.hold  = False
        if processor:
            self.processor = processor
        else:
            self.processor = processor

        if   self.kind == "string":
            if len(options) < 1:
                raise ValueError("Parameter of kind 'string' must have at least one option defined.")
            self.min = 0
            self.max = len(options)-1
            self.options = options

        elif self.kind == "int" or self.kind == "float":
            if minimum is None or maximum is None:
                raise ValueError("Parameter of kind 'int' and 'float' must have minimum and maximum values defined.")
            self.min = minimum
            self.max = maximum
            self.range = np.abs(self.min - self.max)

        self.value = value
        self.units = units
        self._default = value
        self.print_precision = print_precision
        self.randomize_value = randomize_value

        for key, val in kwargs.items():
            setattr(self, key, val)

    def __repr__(self):
        if self.kind == "int":
            return f"{self.name} {self.value:d} kind: {self.kind} range: ({self.min:d} to {self.max:d})"
        elif self.kind == "float":
            s1 = f"{self.name} {self.value:.{self.print_precision}f} {self.units} "
            s2 = f"kind: '{self.kind}' "
            s3 = f"default: {self._default:.{self.print_precision}f} {self.units} "
            s4 = f"range: ({self.min:.{self.print_precision}f} to {self.max:.{self.print_precision}f})"
            return s1 + s2 + s3 + s4
        elif self.kind == "string":
            return f"{self.name} {self.value} kind: {self.kind} options: ({self.options})"
        elif self.kind == "bool":
            return f"{self.name} {self.value} kind: {self.kind}"

    def check_value(self, value):
        # if the value is a string check its in options
        if self.kind == "string":
            if not value in self.options:
                raise ValueError(f"Invalid value {value}. Must be one of {self.options}")

        # if the value is int or float check if its in valid range
        elif self.kind in ["int", "float"]:
            if value < self.min or value > self.max:
                raise ValueError(f"Invalid value {value} for {self}")

    def reset(self):
        self.value = self._default

    def randomize(self, distribution="default", hold=False):
        """ Randomize the value of a parameter.

        By default this will select a value from a uniform distribution
        over the range [min, max] if it is a `float`, it will use a uniform
        distriubtion over [min, max] for an `int`, and it will
        selection an index from the options of [0, len(options)-1] if
        it is a `string`.

        For many parameters a uniform distribution over [min, max] is
        a very bad choice, and instead we may want to sample the new value
        from a normal distribution (gaussian). In this cause we can set `mu`
        and `sigma` values for a float type parameter when we create it.
        This will force the use of normal distriubtion. If the value
        drawn is beyond the acceptable range it is simply capped.

        Example for randomizing a gain parameter centered at 0dB
        >>> gain.randomize(distribution="normal", mu=0.0, sigma=4.0)

        """
        if distribution == "default":
            if   self.kind == "int":
                distribution = "uniform"
            elif self.kind == "float":
                if (hasattr(self, "mu") and hasattr(self, "sigma")):
                    distribution = "normal"
                else:
                    # if mu and sigma omitted we use uniform
                    distribution = "uniform"
            elif self.kind == "string":
                distribution = "uniform"
            elif self.kind == "bool":
                distribution = "uniform"
        if   distribution == "uniform":
            if   self.kind == "int" and self.min != self.max:
                self.value = np.random.randint(self.min, high=self.max, dtype='int')
            elif self.kind == "float":
                self.value = (np.random.rand() * self.range) + self.min
            elif self.kind == "string":
                self.value = np.random.choice(self.options)
            elif self.kind == "bool":
                if not hasattr(self, "p"):
                    p = 0.5
                else:
                    p = self.p
                self.value = np.random.choice([True, False], p=[p, 1-p])
        elif distribution == "normal":
            if self.kind == "int":
                raise NotImplementedError("Can only use 'uniform' for int types not 'normal'.")
            elif self.kind == "float":
                sampled_value = np.random.normal(self.mu,self.sigma)
                # check if it exceeds the bounds and then cap it
                if sampled_value > self.max:
                    sampled_value = self.max
                elif sampled_value < self.min:
                    sampled_value = self.min
                # finally set the new value
                self.value = sampled_value
            if self.kind == "string":
                raise NotImplementedError()
            if self.kind == "bool":
                raise NotImplementedError()
        else:
            raise ValueError(f"Invalid distribtuion: {distribution}.")

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self.check_value(value)
        self._value = value

        # if there is a processor reference call its update method
        # but only if we have added all parameters first?
        if self.processor and hasattr(self.processor.parameters, self.name) and not self.hold:
            #log = logger.getLog(logger.LOG_NAME)
            #if self.kind == "float":
            #    s = f"changing {self.processor.name} {self.name} to {value:.{self.print_precision}f} {self.units}"
            #else:
            #    s = f"changing {self.name} to {value}."
            #log.info(s)
            self.processor.update(self.name)

    def serialize(self, normalize=False, one_hot_encode=False):
        if self.kind in ["float", "int"]:
            val = {"value" : self.value, "min" : self.min, "max" : self.max}
        elif self.kind == "bool":
            val = {"value" : self.value}
        elif self.kind == "string":
            val = {"value" : self.value, "options" : self.options}
        return val

    @property
    def kind(self):
        return self._kind

    @kind.setter
    def kind(self, kind):
        if kind not in kinds:
            raise ValueError(f"Invalid kind. Must be one of {kinds}.")
        self._kind = kind

    def db2linear(self):
        return np.power(10, self.value/20)

    def linear2db(self):
        return 20 * np.log10(self.value)

max_stars_repo_name: TE-StefanUhlich/pymixconsole

max_issues_repo_name: TE-StefanUhlich/pymixconsole

max_forks_repo_name: TE-StefanUhlich/pymixconsole


text:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# from torch_geometric.nn import GCNConv
# from torch_sparse import spmm, transpose
# from scipy.linalg import block_diag
# from scipy.sparse import csr_matrix
import pdb

class EncoderRNN(nn.Module):
    '''
    EncoderRNN helps in building the sentence encoding module for a batched version
    of data that is sent in [T x B] having corresponding input lengths in [1 x B]

    Args:
        hidden_size: Hidden size of the RNN cell
        embedding: Embeddings matrix [vocab_size, embedding_dim]
        cell_type: Type of RNN cell to be used : LSTM, GRU
        nlayers: Number of layers of LSTM (default = 1)
        dropout: Dropout Rate (default = 0.1)
        bidirectional: Bidirectional model to be formed (default: False)
    '''
    def __init__(self, hidden_size, embedding, cell_type, nlayers=1, dropout=0.1, bidirectional=False):
        super(EncoderRNN, self).__init__()
        self.hidden_size = hidden_size
        self.nlayers = nlayers
        self.dropout = dropout
        self.embedding = embedding
        self.cell_type = cell_type
        self.embedding_size = self.embedding.embedding_dim
        self.bidirectional = bidirectional

        if self.cell_type == 'lstm':
            self.rnn = nn.LSTM(self.embedding_size, self.hidden_size,
                               num_layers=self.nlayers, dropout = (0 if self.nlayers == 1 else dropout),
                               bidirectional=bidirectional)
        else:
            self.rnn = nn.GRU(self.embedding_size, self.hidden_size,
                              num_layers=self.nlayers, dropout=(0 if self.nlayers == 1 else dropout),
                              bidirectional=bidirectional)

    def forward(self, input_seqs, input_lengths, hidden=None):
        embedded = self.embedding(input_seqs)
        packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths, enforce_sorted=False)
        outputs, hidden = self.rnn(packed, hidden)
        outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) # unpack (back to padded)
        if self.bidirectional:
            outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] # Sum bidirectional outputs

        return outputs, hidden

ext: py

max_stars_repo_name: malllabiisc/SGCP

max_issues_repo_name: malllabiisc/SGCP

max_forks_repo_name: malllabiisc/SGCP

reason: import numpy,from scipy


text:
import json

import pandas as pd
import matplotlib
matplotlib.use("Agg")
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

fastqc = json.load(open(snakemake.input[0]))

qualdist = pd.DataFrame.from_records(fastqc["Per base sequence quality"]["contents"])
qualdist.Base = qualdist.Base.apply(lambda b: int(b.split("-")[0]))
qualdist = qualdist.replace("NaN", np.NaN)
single_value = qualdist["Lower Quartile"].isnull()
qualdist = qualdist[~single_value]

if not qualdist.empty:
    plt.fill_between(x=qualdist.Base, y2=qualdist["Lower Quartile"], y1=qualdist["Upper Quartile"], color="#cee3a3")
    plt.plot(qualdist.Base, qualdist.Mean, "-", color="#649600")

sns.despine()
plt.xlabel("read base")
plt.ylabel("quality (PHRED scale)")
plt.xticks(rotation="vertical")

plt.savefig(snakemake.output[0], bbox_inches="tight")

max_stars_repo_name: koesterlab/nanopore-qc

max_issues_repo_name: koesterlab/nanopore-qc

max_forks_repo_name: koesterlab/nanopore-qc

reason: import numpy


text:
from distutils.ccompiler import new_compiler
import scipy.io as scio
from iotoolkit.mat_data import MatData
from iotoolkit.mpii import *
from iotoolkit.coco_toolkit import JOINTS_PAIR
import pickle
import wml_utils as wmlu
import random
import cv2
import os
import os.path as osp
import img_utils as wmli
import object_detection2.keypoints as odk
import object_detection2.visualization as odv
import object_detection2.bboxes as odb
from keypoints.get_keypoints import KPDetection

os.environ['CUDA_VISIBLE_DEVICES'] = "0"

if __name__ == "__main__":
    mat_path = "/home/wj/ai/mldata1/MPII/MPII/mpii_human_pose_v1_u12_2/mpii_human_pose_v1_u12_1.mat"
    pt_path = "/home/wj/ai/mldata1/MPII/MPII/mpii_human_pose_v1_u12_2/mpii_human_pose_v1_u12_1.pt"
    coco_pt_path = "/home/wj/ai/mldata1/MPII/MPII/mpii_human_pose_v1_u12_2/mpii_coco.pt"
    imgs_dir = "/home/wj/ai/mldata1/MPII/MPII/images"
    save_dir = wmlu.get_unused_path("/home/wj/ai/mldata1/MPII/tmp/vis")
    coco_model = KPDetection()
    trans_model = Trans2COCO()
    '''mpii_data = read_mpii_data(mat_path)
    with open(pt_path,"wb") as f:
        pickle.dump(mpii_data,f)'''
    with open(pt_path,"rb") as f:
        mpii_data = pickle.load(f)
    new_coco_data = []
    for data in mpii_data:
        img_name,bboxes,kps = data
        org_bboxes = bboxes
        bboxes = odb.npscale_bboxes(bboxes,1.25)
        img_path = osp.join(imgs_dir,img_name)
        img = wmli.imread(img_path)
        coco_kps = coco_model.get_kps_by_bboxes(img,bboxes,return_fea=False)
        kps = trans_model(kps,coco_kps)
        new_coco_data.append([img_name,org_bboxes,kps])

    with open(coco_pt_path,"wb") as f:
        pickle.dump(new_coco_data,f)

    '''for data in mpii_data:
        img_name,bboxes,kps = data
        bboxes = odb.npscale_bboxes(bboxes,1.25)
        img_path = osp.join(imgs_dir,img_name)
        img = wmli.imread(img_path)
        coco_kps = coco_model.get_kps_by_bboxes(img,bboxes,return_fea=False)
        kps = trans_model(kps,coco_kps)
        bboxes = odb.npchangexyorder(bboxes)
        img = odv.draw_bboxes(img,bboxes=bboxes,is_relative_coordinate=False)
        img = odv.draw_keypoints(img,kps,no_line=False,joints_pair=JOINTS_PAIR)
        img = odv.draw_keypoints(img,coco_kps,no_line=True)
        save_path = osp.join(save_dir,img_name)

        wmli.imwrite(save_path,img)'''

    print(mpii_data)

reason: import scipy


text:
# --------------
# import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Code starts here
data = pd.read_csv(path)
print(data.shape)
print(data.describe())
data = data.drop(['Serial Number'],axis=1)
print(data.shape)

# code ends here

# --------------
#Importing header files
from scipy.stats import chi2_contingency
import scipy.stats as stats

#Critical value
critical_value = stats.chi2.ppf(q = 0.95, # Find the critical value for 95% confidence*
                      df = 11)   # Df = number of variable categories(in purpose) - 1

# Code starts here
return_rating = data['morningstar_return_rating'].value_counts()
print(return_rating)
risk_rating = data['morningstar_risk_rating'].value_counts()
print(risk_rating)
observed = pd.concat([return_rating.transpose(),risk_rating.transpose()],axis=1,keys=['return','risk'])
print(observed)
chi2, p, dof, ex = chi2_contingency(observed)
print("p value")
print(p)
print("Chi Statistic")
print(chi2)
if chi2 > critical_value:
    print("Null Hypothesis is Rejected")
else:
    print("Null Hypothesis is Accepted")
# Code ends here

# --------------
# Code starts here
correlation = abs(data.corr())
print(correlation)
us_correlation = correlation.unstack()
print(us_correlation)
us_correlation = us_correlation.sort_values(ascending = False)
print(us_correlation)
max_correlated = us_correlation[(us_correlation>0.75) & (us_correlation<1)]
print(max_correlated)
data.drop(['morningstar_rating', 'portfolio_stocks', 'category_12' ,'sharpe_ratio_3y'],axis=1,inplace=True)
print(data.shape)
# code ends here

# --------------
# Code starts here
fig, (ax_1, ax_2) = plt.subplots(1, 2, figsize=(10,25))
ax_1.boxplot(data['price_earning'])
ax_1.set_title("price_earning")
ax_2.boxplot(data['net_annual_expenses_ratio'])
ax_2.set_title("net_annual_expenses_ratio")
# code ends here

# --------------
# import libraries
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score,mean_squared_error

# Code starts here
# independent variable
X = data.drop(columns = 'bonds_aaa')
# target variable
y = data.bonds_aaa
# train test split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3, random_state=3)
# Instantiate linear model
lr = LinearRegression()
# fit the model on training data
lr.fit(X_train,y_train)
# predict on test
y_pred = lr.predict(X_test)
#Calculate rmse
rmse = np.sqrt(mean_squared_error(y_pred,y_test))
print("The RMSE Score For Simple Linear Model is {}".format(rmse.round(2)))
# Code ends here

# --------------
# import libraries
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.linear_model import Ridge,Lasso

# regularization parameters for grid search
ridge_lambdas = [0.01, 0.03, 0.06, 0.1, 0.3, 0.6, 1, 3, 6, 10, 30, 60]
lasso_lambdas = [0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1, 0.3, 0.6, 1]

# Code starts here
ridge_model = Ridge()
ridge_grid = GridSearchCV(estimator = ridge_model, param_grid = dict(alpha = ridge_lambdas))
ridge_grid.fit(X_train,y_train)
ridge_pred = ridge_grid.predict(X_test)
ridge_rmse = np.sqrt(mean_squared_error(ridge_pred,y_test))
print("RMSE Score For Ridge Model is {}".format(ridge_rmse.round(2)))

lasso_model = Lasso()
lasso_grid = GridSearchCV(estimator = lasso_model, param_grid = dict(alpha = lasso_lambdas))
lasso_grid.fit(X_train,y_train)
lasso_pred = lasso_grid.predict(X_test)
lasso_rmse = np.sqrt(mean_squared_error(lasso_pred,y_test))
print("RMSE Score For Lasso Model is {}".format(lasso_rmse.round(2)))
# Code ends here

reason: import numpy,import scipy,from scipy


text:
import pytest
import pytikz as pt
import numpy as np

def test_node():
    n = pt.Node(pt.Vector(1), "test")
    assert str(n) == "\\node at (1) {test};"

    m = pt.Node(pt.vector.AnchoredVector(pt.Vector(3), pt.Vector(5)), "test")
    assert str(m) == "\\node at (8) {test};"

    t = pt.vector.Transformation(lambda x: 2 * x)
    assert str(t(n)) == "\\node at (2) {test};"
    assert str(t(m)) == "\\node at (11) {test};"

    assert str(n) == "\\node at (1) {test};"
    assert str(m) == "\\node at (8) {test};"

    t(n, True)
    t(m, True)

    assert str(n) == "\\node at (2) {test};"
    assert str(m) == "\\node at (11) {test};"

    n = pt.Node(pt.Vector(1), "test", pt.Orientation.SOUTH_EAST)
    assert str(n) == "\\node[anchor=south east] at (1) {test};"

max_stars_repo_name: pglammers/pytikz

max_issues_repo_name: pglammers/pytikz

max_forks_repo_name: pglammers/pytikz


text:
from typing import Tuple

import jax
import jax.numpy as jnp

from jax_rl.agents.actor_critic_temp import ActorCriticTemp
from jax_rl.datasets import Batch
from jax_rl.networks.common import InfoDict, Params

def target_update(sac: ActorCriticTemp, tau: float,
                  target_update_period: int) -> ActorCriticTemp:
    # A mix of soft and hard target updates.
    params = sac.critic.optimizer.target

    if tau < 1:
        new_target_params = jax.tree_multimap(
            lambda p, tp: p * tau + tp * (1 - tau), params,
            sac.target_critic.params)
    else:
        new_target_params = params

    if target_update_period > 1:
        step = sac.critic.optimizer.state.step
        new_target_params = jax.lax.cond(step % target_update_period == 0,
                                         lambda _: new_target_params,
                                         lambda _: sac.target_critic.params,
                                         operand=None)

    new_target_critic = sac.target_critic.replace(params=new_target_params)

    return sac.replace(target_critic=new_target_critic)

def update(sac: ActorCriticTemp, batch: Batch, discount: float,
           soft_critic: bool) -> Tuple[ActorCriticTemp, InfoDict]:
    dist = sac.actor(batch.next_observations)
    rng, key = jax.random.split(sac.rng)
    next_actions = dist.sample(seed=key)
    next_q1, next_q2 = sac.target_critic(batch.next_observations, next_actions)
    next_q = jnp.minimum(next_q1, next_q2)

    target_q = batch.rewards + discount * batch.masks * next_q

    if soft_critic:
        next_log_probs = dist.log_prob(next_actions)
        target_q -= discount * batch.masks * sac.temp() * next_log_probs

    def critic_loss_fn(critic_params: Params) -> Tuple[jnp.ndarray, InfoDict]:
        q1, q2 = sac.critic.apply({'params': critic_params},
                                  batch.observations, batch.actions)
        critic_loss = ((q1 - target_q)**2 + (q2 - target_q)**2).mean()
        return critic_loss, {
            'critic_loss': critic_loss,
            'q1': q1.mean(),
            'q2': q2.mean()
        }

    new_critic, info = sac.critic.apply_gradient(critic_loss_fn)

    new_sac = sac.replace(critic=new_critic, rng=rng)

    return new_sac, info

reason: import jax,from jax


text:
# -*- coding: utf-8 -*-

# ----------------------------------------------------------------------------
#
# TITLE   :
# AUTHOR  :
# PROJECT :
#
# ----------------------------------------------------------------------------

# Docstring
"""**DOCSTRING**.

description

Routing Listings
----------------

"""

__author__ = "Jo Bovy"
__maintainer__ = "Nathaniel Starkman"

__all__ = [
    "fiducial_model",
    "model_vary_c_along_the_best_fit_line",
    "model-vary_b_for_c_1_pa_0",
    "model_vary_b_for_c_1_pa_45",
    "model_vary_d",
    "model_vary_pm_pll",
    "model_vary_pm_perp",
    "model_stream_struct_vary_c",
    "model_stream_struct_vary_vcirc",
    "model_stream_struct_vary_d",
    "model_stream_struct_vary_pm",
    "plot_all",
    "make_parser",
    "main",
]

###############################################################################
# IMPORTS

# GENERAL
import os
import os.path
import argparse
import pickle
import warnings
from typing import Optional

import numpy as np

from tqdm import tqdm

# galpy
from galpy.actionAngle import actionAngleIsochroneApprox
from galpy.orbit import Orbit
from galpy.df import streamdf
from galpy.util import bovy_plot, bovy_conversion, bovy_coords, save_pickles

# plotting
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import cm, gridspec
from matplotlib.ticker import NullFormatter
from matplotlib.cbook import MatplotlibDeprecationWarning

# PROJECT-SPECIFIC
# fmt: off
import sys; sys.path.insert(0, '../../../')
# fmt: on
from pal5_constrain_mwhalo_shape import mw_pot
from pal5_constrain_mwhalo_shape.streams.pal5 import pal5_util

###############################################################################
# PARAMETERS

_MW_POT_SCRIPT_FOLDER = "../../0-create_MW_potential_2014/2019/"

save_figures = False

cmap = cm.plasma

warnings.filterwarnings("ignore", category=MatplotlibDeprecationWarning)

REFR0 = mw_pot.REFR0
REFV0 = mw_pot.REFV0

pos_radec, rvel_ra = pal5_util.pal5_data_total()

###############################################################################
# CODE
###############################################################################

def plot_data_add_labels(
    radeconly=False,
    rvonly=False,
    color=sns.color_palette()[2],
    p1=(1, 2, 1),
    p2=(1, 2, 2),
    noxlabel_dec=False,
    noxlabel_vlos=False,
    noylabel=False,
):
    """plot_data_add_labels."""
    if noxlabel_dec or noylabel:
        nullfmt = NullFormatter()
    if not radeconly and not rvonly:
        plt.subplot(*p1)
    if not rvonly:
        if not noxlabel_dec:
            plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
        else:
            plt.gca().xaxis.set_major_formatter(nullfmt)
        if not noylabel:
            plt.ylabel(r"$\mathrm{Dec}\,(\mathrm{degree})$")
        else:
            plt.gca().yaxis.set_major_formatter(nullfmt)
        plt.xlim(250.0, 210.0)
        plt.ylim(-15.0, 9.0)
        bovy_plot._add_ticks()
        plt.errorbar(
            pos_radec[:, 0],
            pos_radec[:, 1],
            yerr=pos_radec[:, 2],
            ls="none",
            marker="o",
            color=color,
        )
    if radeconly:
        return None
    if not rvonly:
        plt.subplot(*p2)
    if not noxlabel_vlos:
        plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$")
    else:
        plt.gca().xaxis.set_major_formatter(nullfmt)
    if not noylabel:
        plt.ylabel(r"$V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$")
    else:
        plt.gca().yaxis.set_major_formatter(nullfmt)
    plt.xlim(250.0, 221.0)
    plt.ylim(-80.0, 0.0)
    bovy_plot._add_ticks()
    plt.errorbar(
        rvel_ra[rvel_ra[:, 0] > 230.5, 0],
        rvel_ra[rvel_ra[:, 0] > 230.5, 1],
        yerr=rvel_ra[rvel_ra[:, 0] > 230.5, 2],
        ls="none",
        marker="o",
        color=color,
    )

    return None

# /def

def add_colorbar(vmin, vmax, clabel, save_figures=False):
    """Add Colorbar."""
    fig = plt.gcf()
    if save_figures:
        cbar_ax = fig.add_axes([0.9, 0.135, 0.025, 0.815])
    else:
        fig.subplots_adjust(right=0.95)
        cbar_ax = fig.add_axes([0.975, 0.13, 0.025, 0.78])
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
    sm._A = []
    cbar = fig.colorbar(sm, cax=cbar_ax, use_gridspec=True, format=r"$%.1f$")
    cbar.set_label(clabel)

    return None

# /def

def fiducial_model(
    sdf_trailing="output/sdf_trailing.pkl",
    sdf_leading="output/sdf_leading.pkl",
    threshold=0.3,
    ro=REFR0,
    vo=REFV0,
):
    """Fiducial Model.

    The fiducial model assumes a spherical halo, with the best-fit
    parameters from fitting to the MWPotential2014 data

    """
    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]

    pot = mw_pot.setup_potential(p_b15, 1.0, False, False, ro, vo)

    prog = Orbit(
        [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
        radec=True,
        ro=ro,
        vo=vo,
        solarmotion=[-11.1, 24.0, 7.25],
    )
    aAI = actionAngleIsochroneApprox(pot=pot, b=0.8)
    sigv = 0.2

    # ----------------------------------------------------------

    try:
        with open(sdf_trailing, "rb") as file:
            sdf_trailing = pickle.load(file)
    except Exception:
        sdf_trailing = streamdf(
            sigv / vo,
            progenitor=prog,
            pot=pot,
            aA=aAI,
            leading=False,
            nTrackChunks=11,
            tdisrupt=10.0 / bovy_conversion.time_in_Gyr(vo, ro),
            ro=ro,
            vo=vo,
            R0=ro,
            vsun=[-11.1, vo + 24.0, 7.25],
            custom_transform=pal5_util._TPAL5,
        )
        with open(sdf_trailing, "wb") as file:
            pickle.dump(sdf_trailing, file)

    try:
        with open(sdf_leading, "rb") as file:
            sdf_leading = pickle.load(file)
    except Exception:
        sdf_leading = streamdf(
            sigv / vo,
            progenitor=prog,
            pot=pot,
            aA=aAI,
            leading=True,
            nTrackChunks=11,
            tdisrupt=10.0 / bovy_conversion.time_in_Gyr(vo, ro),
            ro=ro,
            vo=vo,
            R0=ro,
            vsun=[-11.1, vo + 24.0, 7.25],
            custom_transform=pal5_util._TPAL5,
        )
        with open(sdf_leading, "wb") as file:
            pickle.dump(sdf_leading, file)

    # ----------------------------------------------------------

    print(
        "Angular length: %f deg (leading,trailing)=(%f,%f) deg"
        % (
            sdf_leading.length(ang=True, coord="customra", threshold=threshold)
            + sdf_trailing.length(ang=True, coord="customra", threshold=threshold),
            sdf_leading.length(ang=True, coord="customra", threshold=threshold),
            sdf_trailing.length(ang=True, coord="customra", threshold=threshold),
        )
    )
    print("Angular width (FWHM): %f arcmin" % (pal5_util.width_trailing(sdf_trailing)))
    print("Velocity dispersion: %f km/s" % (pal5_util.vdisp_trailing(sdf_trailing)))

    # ----------------------------------------------------------

    trackRADec_trailing = bovy_coords.lb_to_radec(
        sdf_trailing._interpolatedObsTrackLB[:, 0],
        sdf_trailing._interpolatedObsTrackLB[:, 1],
        degree=True,
    )
    trackRADec_leading = bovy_coords.lb_to_radec(
        sdf_leading._interpolatedObsTrackLB[:, 0],
        sdf_leading._interpolatedObsTrackLB[:, 1],
        degree=True,
    )
    lb_sample_trailing = sdf_trailing.sample(n=10000, lb=True)
    lb_sample_leading = sdf_leading.sample(n=10000, lb=True)
    radec_sample_trailing = bovy_coords.lb_to_radec(
        lb_sample_trailing[0], lb_sample_trailing[1], degree=True
    )
    radec_sample_leading = bovy_coords.lb_to_radec(
        lb_sample_leading[0], lb_sample_leading[1], degree=True
    )

    # ----------------------------------------------------------
    # plotting

    plt.figure(figsize=(12, 4))
    plt.subplot(1, 2, 1)
    bovy_plot.bovy_plot(
        trackRADec_trailing[:, 0],
        trackRADec_trailing[:, 1],
        color=sns.color_palette()[0],
        xrange=[250.0, 210.0],
        yrange=[-15.0, 9.0],
        xlabel=r"$\mathrm{RA}\,(\mathrm{degree})$",
        ylabel=r"$\mathrm{Dec}\,(\mathrm{degree})$",
        gcf=True,
    )
    bovy_plot.bovy_plot(
        trackRADec_leading[:, 0],
        trackRADec_leading[:, 1],
        color=sns.color_palette()[0],
        overplot=True,
    )
    plt.plot(
        radec_sample_trailing[:, 0],
        radec_sample_trailing[:, 1],
        "k.",
        alpha=0.01,
        zorder=0,
    )
    plt.plot(
        radec_sample_leading[:, 0],
        radec_sample_leading[:, 1],
        "k.",
        alpha=0.01,
        zorder=0,
    )
    plt.errorbar(
        pos_radec[:, 0],
        pos_radec[:, 1],
        yerr=pos_radec[:, 2],
        ls="none",
        marker="o",
        color=sns.color_palette()[2],
    )
    plt.subplot(1, 2, 2)
    bovy_plot.bovy_plot(
        trackRADec_trailing[:, 0],
        sdf_trailing._interpolatedObsTrackLB[:, 3],
        color=sns.color_palette()[0],
        xrange=[250.0, 210.0],
        yrange=[-80.0, 0.0],
        xlabel=r"$\mathrm{RA}\,(\mathrm{degree})$",
        ylabel=r"$V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$",
        gcf=True,
    )
    bovy_plot.bovy_plot(
        trackRADec_leading[:, 0],
        sdf_leading._interpolatedObsTrackLB[:, 3],
        color=sns.color_palette()[0],
        overplot=True,
    )
    plt.plot(
        radec_sample_trailing[:, 0], lb_sample_trailing[3], "k.", alpha=0.01, zorder=0,
    )
    plt.plot(
        radec_sample_leading[:, 0], lb_sample_leading[3], "k.", alpha=0.01, zorder=0,
    )
    plt.errorbar(
        rvel_ra[:, 0],
        rvel_ra[:, 1],
        yerr=rvel_ra[:, 2],
        ls="none",
        marker="o",
        color=sns.color_palette()[2],
    )

    plt.savefig("figures/fiducial_model.pdf")

    return

# /def

def model_vary_c_along_the_best_fit_line():

    bf_savefilename = _MW_POT_SCRIPT_FOLDER + "/output/mwpot14varyc-bf.pkl"
    if os.path.exists(bf_savefilename):
        with open(bf_savefilename, "rb") as savefile:
            cs = pickle.load(savefile)
            bf_params = pickle.load(savefile)
    else:
        IOError(
            (
                "Need to calculate best-fit potentials for different c "
                "in MWPotential2014-varyc.ipynb first"
            )
        )
    bf_params = np.array(bf_params)
    bf_params = bf_params[cs <= 3.0]
    cs = cs[cs <= 3.0]

    # ----------------------------------------------------------

    progs = []
    progfs = []
    times = np.linspace(0.0, 3.0, 101)

    for bp, c in zip(bf_params, cs):
        pot = mw_pot.setup_potential(bp, c, False, False, REFR0, REFV0)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        prog.flip(inplace=True)
        progfs.append(prog)

    # ----------------------------------------------------------
    # Vary $c$ along the best-fit line

    plt.figure(figsize=(12, 4))

    for c, orb, orbf in zip(cs, progs, progfs):
        tc = cmap((c - 0.5) / 2.5)
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)

    plot_data_add_labels(color="k")
    add_colorbar(0.5, 3.0, r"$c$", save_figures=False)
    plt.savefig("figures/varyc_bestfitline.pdf")

    return

# /def

def model_vary_b_for_c_1_pa_0():

    # ----------------------------------------------------------
    # Vary $b$ for $c=1$ (pa=0):

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    progs = []
    progfs = []
    times = np.linspace(0.0, 3.0, 101)
    bs = np.arange(0.5, 2.1, 0.1)

    for b in bs:
        pot = mw_pot.setup_potential(p_b15, 1.0, False, False, REFR0, REFV0, b=b)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        prog.flip(inplace=True)
        progfs.append(prog)

    # -------------------------------------------

    plt.figure(figsize=(12, 4))

    for b, orb, orbf in zip(bs, progs, progfs):
        tc = cmap((b - 0.5) / 1.5)
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)

    plot_data_add_labels(color="k")
    add_colorbar(0.5, 2.0, r"$b$", save_figures=False)
    plt.savefig("figures/varyb_c-1_pa-0.pdf")

    return

# /def

def model_vary_b_for_c_1_pa_45():

    # ----------------------------------------------------------
    # Vary $b$ for $c=1$ (pa=45 degree):

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    progs = []
    progfs = []
    times = np.linspace(0.0, 3.0, 101)
    bs = np.arange(0.5, 2.1, 0.1)
    for b in bs:
        pot = mw_pot.setup_potential(
            p_b15, 1.0, False, False, REFR0, REFV0, b=b, pa=np.pi / 4.0
        )
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        prog.flip(inplace=True)
        progfs.append(prog)

    # -------------------------------------------

    plt.figure(figsize=(12, 4))

    for b, orb, orbf in zip(bs, progs, progfs):
        tc = cmap((b - 0.5) / 1.5)
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)

    plot_data_add_labels(color="k")
    add_colorbar(0.5, 2.0, r"$b$", save_figures=False)
    plt.savefig("figures/varyb_c-1_pa-45.pdf")

    return

# /def

def model_vary_d():

    # ----------------------------------------------------------
    # The Pal 5 stream is not very sensitive to changes in $b$.
    # Vary the distance:

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    progs = []
    progfs = []
    times = np.linspace(0.0, 3.0, 101)
    ds = np.linspace(22.5, 24.5, 101)
    for d in ds:
        pot = mw_pot.setup_potential(p_b15, 1.0, False, False, REFR0, REFV0)
        prog = Orbit(
            [229.018, -0.124, d, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, d, -2.296, -2.257, -58.7],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        prog.flip(inplace=True)
        progfs.append(prog)

    # -------------------------------------------

    plt.figure(figsize=(12, 4))

    for d, orb, orbf in zip(ds, progs, progfs):
        tc = cmap((d - np.amin(ds)) / (np.amax(ds) - np.amin(ds)))
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)
    plot_data_add_labels(color="k")
    add_colorbar(
        np.amin(ds),
        np.amax(ds),
        r"$\mathrm{distance}\,(\mathrm{kpc})$",
        save_figures=False,
    )
    plt.savefig("figures/varyd.pdf")

def model_vary_pm_pll():

    # ----------------------------------------------------------
    # Vary the proper motion parallel to the stream

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    progs = []
    progfs = []
    times = np.linspace(0.0, 2.5, 101)
    pms = np.linspace(-0.3, 0.3, 101)
    for pm in pms:
        pot = mw_pot.setup_potential(p_b15, 1.0, False, False, REFR0, REFV0)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296 + pm, -2.257 + 2.257 / 2.296 * pm, -58.7,],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296 + pm, -2.257 + 2.257 / 2.296 * pm, -58.7,],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        # prog._orb.orbit[:,1]*= -1.
        # prog.orbit[:,1]*= -1.
        # prog.orbit[:,2]*= -1.
        # prog.orbit[:,4]*= -1.
        prog.flip(inplace=True)
        progfs.append(prog)

    plt.figure(figsize=(12, 4))

    for pm, orb, orbf in zip(pms, progs, progfs):
        tc = cmap((pm - np.amin(pms)) / (np.amax(pms) - np.amin(pms)))
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)
    plot_data_add_labels(color="k")
    add_colorbar(
        np.amin(pms),
        np.amax(pms),
        r"$\mathrm{proper\ motion\ offset}\,(\mathrm{mas\,yr}^{-1})$",
        save_figures=False,
    )
    plt.savefig("figures/varypm-prll.pdf")

def model_vary_pm_perp():

    # ----------------------------------------------------------
    # Vary the proper motion perpendicular to the stream:

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    progs = []
    progfs = []
    times = np.linspace(0.0, 2.5, 101)
    pms = np.linspace(-0.3, 0.3, 101)
    for pm in pms:
        pot = mw_pot.setup_potential(p_b15, 1.0, False, False, REFR0, REFV0)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296 + pm, -2.257 - 2.296 / 2.257 * pm, -58.7,],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        )
        prog.integrate(times, pot)
        progs.append(prog)
        prog = Orbit(
            [229.018, -0.124, 23.2, -2.296 + pm, -2.257 - 2.296 / 2.257 * pm, -58.7,],
            radec=True,
            ro=REFR0,
            vo=REFV0,
            solarmotion=[-11.1, 24.0, 7.25],
        ).flip()
        prog.integrate(times, pot)
        prog.flip(inplace=True)
        progfs.append(prog)

    plt.figure(figsize=(12, 4))
    for pm, orb, orbf in zip(pms, progs, progfs):
        tc = cmap((pm - np.amin(pms)) / (np.amax(pms) - np.amin(pms)))
        plt.subplot(1, 2, 1)
        orb.plot(d1="ra", d2="dec", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="dec", color=tc, overplot=True)
        plt.subplot(1, 2, 2)
        orb.plot(d1="ra", d2="vlos", color=tc, overplot=True)
        orbf.plot(d1="ra", d2="vlos", color=tc, overplot=True)
    plot_data_add_labels(color="k")
    add_colorbar(
        np.amin(pms),
        np.amax(pms),
        r"$\mathrm{proper\ motion\ offset}\,(\mathrm{mas\,yr}^{-1})$",
        save_figures=False,
    )
    plt.savefig("figures/varypm-perp.pdf")

#################################################################
# How does the track, width, and length of the Pal 5 stream vary with the
# potential and the uncertain phase-space location of the Pal 5 cluster?

def _get_pal5varyc():

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varyc.pkl"
    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            cs = pickle.load(savefile)
            pal5varyc = pickle.load(savefile)
    else:
        cs = np.arange(0.5, 2.3, 0.1)
        pal5varyc = pal5_util.predict_pal5obs(
            p_b15,
            cs,
            multi=8,
            useTM=False,
            interpcs=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25],
        )
        save_pickles(savefilename, cs, pal5varyc)

    return pal5varyc, cs

# /def

def model_stream_struct_vary_c():

    # ----------------------------------------------------------
    # Varying the flattening $c$ of the halo
    # We compute the stream structure for a fiducial set of parameters, to get
    # a sense of where the track lies and how the width and length vary

    pal5varyc, cs = _get_pal5varyc()

    # -------------------------------------------

    plt.figure(figsize=(12, 4))
    for ii, c in enumerate(cs):
        tc = cmap((c - np.amin(cs)) / (np.amax(cs) - np.amin(cs)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyc[0][ii, :, 0], pal5varyc[0][ii, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[1][ii, :, 0], pal5varyc[1][ii, :, 1], color=tc, overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyc[2][ii, :, 0], pal5varyc[2][ii, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[3][ii, :, 0], pal5varyc[3][ii, :, 1], color=tc, overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyc.pdf")

    return

# /def

def _get_pal5varyvc():

    pal5varyc, cs = _get_pal5varyc()

    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varyvc.pkl"

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]
    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            vcs = pickle.load(savefile)
            pal5varyvc = pickle.load(savefile)
    else:
        vcs = np.arange(200.0, 255.0, 5.0)
        pal5varyvc = np.zeros(
            (len(vcs), 4, pal5varyc[0].shape[1], pal5varyc[0].shape[2])
        )
        for ii, vc in enumerate(vcs):
            t = pal5_util.predict_pal5obs(
                p_b15, 1.0, multi=8, vo=vc, singlec=True, useTM=False
            )
            for jj in range(4):
                pal5varyvc[ii, jj] = t[jj][0]
        save_pickles(savefilename, vcs, pal5varyvc)

    return pal5varyvc, vcs

def model_stream_struct_vary_vcirc():
    # ----------------------------------------------------------
    # Varying the circular velocity $V_c(R_0)$ to change the normalization of the potential

    pal5varyvc, vcs = _get_pal5varyc()

    plt.figure(figsize=(12, 4))

    for ii, vc in enumerate(vcs):
        tc = cmap((vc - np.amin(vcs)) / (np.amax(vcs) - np.amin(vcs)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 0, :, 0], pal5varyvc[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 1, :, 0], pal5varyvc[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 2, :, 0], pal5varyvc[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 3, :500, 0],
            pal5varyvc[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyvc.pdf")

def _get_pal5varyd():

    pal5varyc, cs = _get_pal5varyc()

    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varyd.pkl"

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]

    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            ds = pickle.load(savefile)
            pal5varyd = pickle.load(savefile)
    else:
        ds = np.arange(20.0, 24.5, 0.5)
        pal5varyd = np.zeros((len(ds), 4, pal5varyc[0].shape[1], pal5varyc[0].shape[2]))
        for ii, d in enumerate(tqdm(ds)):
            t = pal5_util.predict_pal5obs(
                p_b15, 1.0, multi=8, dist=d, singlec=True, useTM=False
            )
            for jj in range(4):
                pal5varyd[ii, jj] = t[jj][0]
        save_pickles(savefilename, ds, pal5varyd)

    return pal5varyd, ds

def model_stream_struct_vary_d():

    pal5varyc, cs = _get_pal5varyc()
    pal5varyd, ds = _get_pal5varyd()

    # ----------------------------------------------------------
    # Varying the distance to the Pal 5 cluster

    plt.figure(figsize=(12, 4))

    for ii, d in enumerate(ds):
        tc = cmap((d - np.amin(ds)) / (np.amax(ds) - np.amin(ds)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varyd[ii, 0, :, 0], pal5varyd[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 1, :, 0], pal5varyd[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varyd[ii, 2, :, 0], pal5varyd[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 3, :500, 0],
            pal5varyd[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varyd.pdf")

def _get_pal5varypm():

    pal5varyc, cs = _get_pal5varyc()

    savefilename = _MW_POT_SCRIPT_FOLDER + "output/mwpot14-pal5-varypm.pkl"

    p_b15 = [
        0.60122692,
        0.36273147,
        -0.97591502,
        -3.34169377,
        0.71877924,
        -0.01519337,
        -0.01928001,
    ]

    if os.path.exists(savefilename):
        with open(savefilename, "rb") as savefile:
            pms = pickle.load(savefile)
            pal5varypm = pickle.load(savefile)
    else:
        pms = np.arange(-0.3, 0.35, 0.05)
        pal5varypm = np.zeros(
            (len(pms), 4, pal5varyc[0].shape[1], pal5varyc[0].shape[2])
        )
        for ii, pm in enumerate(tqdm(pms)):
            pmra, pmdec = -2.296 + pm, -2.257 + 2.257 / 2.296 * pm
            t = pal5_util.predict_pal5obs(
                p_b15, 1.0, multi=8, pmra=pmra, pmdec=pmdec, singlec=True, useTM=False,
            )
            for jj in range(4):
                pal5varypm[ii, jj] = t[jj][0]
        save_pickles(savefilename, pms, pal5varypm)

    return pal5varypm, pms

# /def

def model_stream_struct_vary_pm():

    pal5varyc, cs = _get_pal5varyc()
    pal5varypm, pms = _get_pal5varypm()

    # ----------------------------------------------------------
    # Varying the proper motion of the Pal 5 cluster

    plt.figure(figsize=(12, 4))

    for ii, pm in enumerate(pms):
        tc = cmap((pm - np.amin(pms)) / (np.amax(pms) - np.amin(pms)))
        plt.subplot(1, 2, 1)
        bovy_plot.bovy_plot(
            pal5varypm[ii, 0, :, 0], pal5varypm[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 1, :, 0], pal5varypm[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(1, 2, 2)
        bovy_plot.bovy_plot(
            pal5varypm[ii, 2, :, 0], pal5varypm[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 3, :500, 0],
            pal5varypm[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels()
    plt.tight_layout()
    plt.savefig("figures/mwpot14-pal5-varypm.pdf")

def plot_all():

    pal5varyc, cs = _get_pal5varyc()
    pal5varyd, ds = _get_pal5varyd()
    pal5varypm, pms = _get_pal5varypm()

    # ----------------------------------------------------------
    # All in one plot

    bovy_plot.bovy_print(
        axes_labelsize=17.0,
        text_fontsize=12.0,
        xtick_labelsize=15.0,
        ytick_labelsize=15.0,
    )
    plt.figure(figsize=(16, 7))

    gs = gridspec.GridSpec(
        3, 4, wspace=0.1, hspace=0.075, height_ratios=[0.075, 1.0, 1.0]
    )
    # c
    for ii, c in enumerate(cs):
        tc = cmap((c - np.amin(cs)) / (np.amax(cs) - np.amin(cs)))
        plt.subplot(gs[4])
        bovy_plot.bovy_plot(
            pal5varyc[0][ii, :, 0], pal5varyc[0][ii, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[1][ii, :, 0], pal5varyc[1][ii, :, 1], color=tc, overplot=True,
        )
        plt.subplot(gs[8])
        bovy_plot.bovy_plot(
            pal5varyc[2][ii, :, 0], pal5varyc[2][ii, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyc[3][ii, :, 0], pal5varyc[3][ii, :, 1], color=tc, overplot=True,
        )
    plot_data_add_labels(p1=(gs[4],), p2=(gs[8],), noxlabel_dec=True)
    # Vc
    for ii, vc in enumerate(vcs):
        tc = cmap((vc - np.amin(vcs)) / (np.amax(vcs) - np.amin(vcs)))
        plt.subplot(gs[5])
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 0, :, 0], pal5varyvc[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 1, :, 0], pal5varyvc[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(gs[9])
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 2, :, 0], pal5varyvc[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyvc[ii, 3, :500, 0],
            pal5varyvc[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels(p1=(gs[5],), p2=(gs[9],), noylabel=True, noxlabel_dec=True)
    # D
    for ii, d in enumerate(ds):
        tc = cmap((d - np.amin(ds)) / (np.amax(ds) - np.amin(ds)))
        plt.subplot(gs[6])
        bovy_plot.bovy_plot(
            pal5varyd[ii, 0, :, 0], pal5varyd[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 1, :, 0], pal5varyd[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(gs[10])
        bovy_plot.bovy_plot(
            pal5varyd[ii, 2, :, 0], pal5varyd[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varyd[ii, 3, :500, 0],
            pal5varyd[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels(p1=(gs[6],), p2=(gs[10],), noylabel=True, noxlabel_dec=True)
    # PM
    for ii, pm in enumerate(pms):
        tc = cmap((pm - np.amin(pms)) / (np.amax(pms) - np.amin(pms)))
        plt.subplot(gs[7])
        bovy_plot.bovy_plot(
            pal5varypm[ii, 0, :, 0], pal5varypm[ii, 0, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 1, :, 0], pal5varypm[ii, 1, :, 1], color=tc, overplot=True,
        )
        plt.subplot(gs[11])
        bovy_plot.bovy_plot(
            pal5varypm[ii, 2, :, 0], pal5varypm[ii, 2, :, 1], color=tc, overplot=True,
        )
        bovy_plot.bovy_plot(
            pal5varypm[ii, 3, :500, 0],
            pal5varypm[ii, 3, :500, 1],
            color=tc,
            overplot=True,
        )
    plot_data_add_labels(p1=(gs[7],), p2=(gs[11],), noylabel=True, noxlabel_dec=True)
    # Colorbars
    for ii, (label, vals, ticks) in enumerate(
        zip(
            [
                r"$\mathrm{halo\ axis\ ratio}$",
                r"$V_c\,(\mathrm{km\,s}^{-1})$",
                r"$\mathrm{Distance}\,(\mathrm{kpc})$",
                r"$\Delta\mu_{\parallel}\,(\mathrm{mas\,yr}^{-1})$",
            ],
            [cs, vcs, ds, pms * np.sqrt(1.0 + (2.257 / 2.296) ** 2.0)],
            [
                [0.5, 1.0, 1.5, 2.0],
                [200.0, 210.0, 220.0, 230.0, 240.0, 250.0],
                [20.0, 21, 22, 23, 24],
                [-0.4, -0.2, 0.0, 0.2, 0.4],
            ],
        )
    ):
        plt.subplot(gs[ii])
        sm = plt.cm.ScalarMappable(
            cmap=cmap, norm=plt.Normalize(vmin=np.amin(vals), vmax=np.amax(vals)),
        )
        sm._A = []
        CB1 = plt.colorbar(sm, orientation="horizontal", cax=plt.gca(), ticks=ticks)
        CB1.set_label(label, fontsize=16.0)
        CB1.ax.xaxis.set_ticks_position("top")
        CB1.ax.xaxis.set_label_position("top")
    if save_figures:
        plt.savefig(
            os.path.join(os.getenv("PAPERSDIR"), "2016-mwhalo-shape", "pal5track.pdf"),
            bbox_inches="tight",
        )
    plt.savefig("figures/2016-mwhalo-shape-pal5track.pdf")

###############################################################################
# Command Line
###############################################################################

def make_parser(inheritable=False):
    """Expose parser for ``main``.

    Parameters
    ----------
    inheritable: bool
        whether the parser can be inherited from (default False).
        if True, sets ``add_help=False`` and ``conflict_hander='resolve'``

    Returns
    -------
    parser: ArgumentParser

    """
    parser = argparse.ArgumentParser(
        description="",
        add_help=~inheritable,
        conflict_handler="resolve" if ~inheritable else "error",
    )

    return parser

# /def

# ------------------------------------------------------------------------

def main(args: Optional[list] = None, opts: Optional[argparse.Namespace] = None):
    """Script Function.

    Parameters
    ----------
    args : list, optional
        an optional single argument that holds the sys.argv list,
        except for the script name (e.g., argv[1:])
    opts : Namespace, optional
        pre-constructed results of parsed args
        if not None, used ONLY if args is None

    """
    if opts is not None and args is None:
        pass
    else:
        if opts is not None:
            warnings.warn("Not using `opts` because `args` are given")
        parser = make_parser()
        opts = parser.parse_args(args)

    return

# /def

# ------------------------------------------------------------------------

if __name__ == "__main__":

    main(args=None, opts=None)  # all arguments except script name

# /if

###############################################################################
# END


text:
import numpy as np
import cv2
from skimage.measure import compare_ssim
import imutils

from darkflow.net.build import TFNet

options = {"model": "yolov2-tiny.cfg", "load": "yolov2-tiny.weights", "threshold": 0.1, "labels": "labels.txt"}

tfnet = TFNet(options)

def get_img_objs(original, frame):
    res = frame.copy()

    grayA = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    (score, diff) = compare_ssim(grayA, grayB, full=True)
    if score > 0.90:
        return res
    diff = (diff * 255).astype("uint8")

    thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    cnts = cnts[0] if imutils.is_cv2() else cnts[1]

    # loop over the contours
    for c in cnts:
        # compute the bounding box of the contour and then draw the
        # bounding box on both input images to represent where the two
        # images differ
        (x, y, w, h) = cv2.boundingRect(c)
        if w * h < 3000:
            continue

        roi = res[y:y+h, x:x+w]
        result = tfnet.return_predict(roi)

        for obj in result:
            if obj['label'] == 'person' and obj['confidence'] >= 0.7:
                x1 = obj['topleft']['x']
                y1 = obj['topleft']['y']
                x2 = obj['bottomright']['x']
                y2 = obj['bottomright']['y']
                cv2.rectangle(roi, (x1, y1), (x2, y2), (0, 0, 255), 3)

        #cv2.rectangle(res, (x, y), (x + w, y + h), (0, 255, 0), 2)
    return res

cap = cv2.VideoCapture(0)

ret, original = cap.read()
for _ in range(50):
    ret, original = cap.read()

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    img_objs = get_img_objs(original, frame)

    # Display the resulting frame
    cv2.imshow('frame', img_objs)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


text:
# -*- coding: utf-8 -*-
#样本是32*32的二值图片，将其处理成1*1024的特征行向量

import numpy
import operator
from PIL import Image
from os import listdir

def img2vector(filename):
    #returnVect = zeros((1,400))   #产生一个数组将来用于存储图片数据

    img = Image.open(filename)
    img_ndarray=numpy.asarray(img,dtype='float64')
    returnVect=numpy.ndarray.flatten(img_ndarray)

#    for i in range(32):
#        lineStr = fr.readline()    #读取第一行的32个二值数据
#        for j in range(32):
#            returnVect[0,32*i+j] = int(lineStr[j])   #以32为一个循环 逐渐填满1024个
    return returnVect

def handwritingClassTest():
    #加载训练集到大矩阵trainingMat
    hwLabels = []
    trainingFileList = listdir('C:\\Anaconda\\trainingNum')           #os模块中的listdir('str')可以读取目录str下的所有文件名，返回一个字符串列表
    m = len(trainingFileList)                 #m表示总体训练样本个数
    trainingMat = numpy.zeros((m,400))             #用来存放m个样本
    for i in range(m):
        fileNameStr = trainingFileList[i]                  #训练样本的命名格式：1_120.txt 获取文件名
        fileStr = fileNameStr.split('.')[0]                #string.split('str')以字符str为分隔符切片，返回list，这里去list[0],得到类似1_120这样的
        classNumStr = int(fileStr.split('-')[0])           #以_切片，得到1，即数字类别
        hwLabels.append(classNumStr)                    #这样hwLabels列表中保存了m个样本点的所有类别
        trainingMat[i,:] = img2vector('C:\\Anaconda\\trainingNum\\%s' % fileNameStr)    #将每个样本存到m*1024矩阵

    #逐一读取测试图片，同时将其分类
    testFileList = listdir('C:\\Anaconda\\testNum')     #测试文件名列表
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]            #获取此刻要测试的文件名
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('-')[0])          #数字标签分类 重新生成的classNumStr 并没有使用上面已有的classNumStr
        vectorUnderTest = img2vector('C:\\Anaconda\\testNum\\%s' % fileNameStr)  #将要测试的数字转化为一行向量
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 5)   #传参
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)
        if (classifierResult != classNumStr): errorCount += 1.0
    print "\nthe total number of errors is: %d" % errorCount
    print "\nthe total error rate is: %f" % (errorCount/float(mTest))

#分类主程序，计算欧式距离，选择距离最小的前k个，返回k个中出现频次最高的类别作为分类别
#inX是所要测试的向量
#dataSet是训练样本集，一行对应一个样本，dataSet对应的标签向量为labels
#k是所选的最近邻数
def classify0(inX, dataSet, labels, k):      #参数和上面的一一对应
    dataSetSize = dataSet.shape[0]                       #shape[0]得出dataSet的行数，即训练样本个数
    diffMat = numpy.tile(inX, (dataSetSize,1)) - dataSet       #tile(A,(m,n))将数组A作为元素构造m行n列的数组 100*1024的数组
    sqDiffMat = diffMat**2
    sqDistances = sqDiffMat.sum(axis=1)                  #array.sum(axis=1)按行累加，axis=0为按列累加
    distances = sqDistances**0.5                        #就是sqrt的结果
    sortedDistIndicies = distances.argsort()             #array.argsort()，得到每个元素按次排序后分别在原数组中的下标 从小到大排列
    classCount={}                                        #sortedDistIndicies[0]表示排序后排在第一个的那个数在原来数组中的下标
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]   #最近的那个在原来数组中的下标位置
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 #一个字典从无到有的生成过程  get(key,x)从字典中获取key对应的value，没有key的话返回0
    #classCount的形式:{5:3,0:6,1:7,2:1}
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) #sorted()函数，按照第二个元素即value的次序逆向（reverse=True）排序
                                                         #sorted第一个参数表示要排序的对象 iteritems代表键值对
    return sortedClassCount[0][0]                        #经过sorted后的字典变成了[(),()]形式的键值对列表

max_stars_repo_name: Leejackie/plate-recognize

max_issues_repo_name: Leejackie/plate-recognize

max_forks_repo_name: Leejackie/plate-recognize


text:
import cv2
import os
import numpy as np
import glob
import pandas as pd
from scipy import ndimage
from scipy import misc
from PIL import Image
import matplotlib.pyplot as plt
import sys
sys.setrecursionlimit(10000)

#this will read the size of every test set to capture images equal to that size
fname = '/home/kiyanoush/UoLincoln/Projects/DeepIL Codes/DatasetSize.csv'
testSize = pd.read_csv(fname, header=None)
print(testSize)

videoList = 'p1_left.mp4', 'p1_right.mp4', 'p2_left.mp4', 'p2_right.mp4', 'p3_left.mp4', 'p3_right.mp4'
cameraName = 'p1_left', 'p1_right', 'p2_left', 'p2_right', 'p3_left', 'p3_right'

os.chdir('/home/kiyanoush/UoLincoln/Projects/DeepIL Codes/Data')
path = '/home/kiyanoush/UoLincoln/Projects/DeepIL Codes/Data/'

for testNumber in range(1, 61):
    newPath = path + str(testNumber)
    print(newPath)
    os.chdir(newPath)
    for vidNameCounter in range(1, 7):
        x = []
        os.chdir(newPath)
        x_StartPixel = 70
        x_EndPixel = 250
        y_StartPixel = 70
        y_EndPixel = 300

        print(vidNameCounter)
        vidcap = cv2.VideoCapture(videoList[vidNameCounter - 1])
        os.makedirs(newPath + '/camera_' + cameraName[vidNameCounter - 1] + '_data')
        os.chdir(newPath + '/camera_' + cameraName[vidNameCounter - 1] + '_data')

        # video to image function
        def getFrame(sec):
            vidcap.set(cv2.CAP_PROP_POS_MSEC, sec * 1000)
            hasFrames, image = vidcap.read()
            # gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            if hasFrames:
                gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                crop_img = gray_image[x_StartPixel:x_EndPixel, y_StartPixel:y_EndPixel]
                imgName = "test" + str(testNumber) + "_img" + str(count) + ".jpg"
                cv2.imwrite(str(count) + ".jpg", crop_img)  # save frame as JPG file
            return hasFrames

        vid_dur = vidcap.get(cv2.CAP_PROP_POS_MSEC)
        fps = vidcap.get(cv2.CAP_PROP_FPS)  # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
        print(fps)
        frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
        duration = frame_count / fps
        print(duration)
        sec = 0  # start time of capturing images
        frameRate = (duration - sec) / testSize[testNumber - 1]  # it will capture image in each 0.0625 second
        count = 1
        success = getFrame(sec)
        while success:
            count = count + 1
            sec = sec + frameRate
            sec = round(sec, 4)
            success = getFrame(sec)

        # convert the captured data for a test to a numpy array
        fileList = []
        for nameIndex in range(1, count):
            fileList.append(str(nameIndex) + ".jpg")

        for fname in fileList:
            x.append(np.array(Image.open(fname)))
            #x = np.array([x, np.array(Image.open(fname))])
        #x = np.array([x, np.array([np.array(Image.open(fname)) for fname in fileList])])

        #print(x.shape)

        varName = 'test_' + str(testNumber) + '_' + cameraName[vidNameCounter - 1] + '_numpyArray.npy'
        print("Saving training image binary...")
        np.save(varName, x)  # Saves as "training.npy"
        print("Done.")

x = np.load('/home/kiyanoush/UoLincoln/Projects/DeepIL Codes/Data/1/camera_p1_left_data/test_1_p1_left_numpyArray.npy', allow_pickle=True)
y = np.load('/home/kiyanoush/UoLincoln/Projects/DeepIL Codes/Data/2/camera_p1_left_data/test_2_p1_left_numpyArray.npy', allow_pickle=True)
print(x.shape)
print(y.shape)

max_stars_repo_name: imanlab/drlfd

max_issues_repo_name: imanlab/drlfd

max_forks_repo_name: imanlab/drlfd